commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
f9dd7f9b9e88ede0eb738d745bb82f722b8f159f
src/stdio/StandardProcess.as
src/stdio/StandardProcess.as
package stdio { import flash.display.* import flash.events.* import flash.utils.* import flash.net.* public class StandardProcess implements Process { private const buffered_stdin: BufferedStream = new BufferedStream private const stdin_socket: SocketStream = new SocketStream private const readline_socket: SocketStream = new SocketStream private const stdout_socket: SocketStream = new SocketStream private const stderr_socket: SocketStream = new SocketStream private var _env: Object private var _prompt: String = "> " public function StandardProcess(env: Object) { _env = env } public function initialize(callback: Function): void { if (available) { connect(callback) } else { callback() } } public function get available(): Boolean { return env["stdio.enabled"] } private function get http_url(): String { return env["stdio.http"] } private function get interactive(): Boolean { return env["stdio.interactive"] === "true" } private function connect(callback: Function): void { stdin_socket.onopen = onopen readline_socket.onopen = onopen stdout_socket.onopen = onopen stderr_socket.onopen = onopen var n: int = 0 function onopen(): void { if (++n === 3) { callback() } } stdin_socket.ondata = buffered_stdin.write stdin_socket.onclose = buffered_stdin.close readline_socket.ondata = buffered_stdin.write readline_socket.onclose = buffered_stdin.close const stdin_port: int = get_int("stdio.in") const readline_port: int = get_int("stdio.readline") if (interactive) { readline_socket.connect("localhost", readline_port) } else { stdin_socket.connect("localhost", stdin_port) } const stdout_port: int = get_int("stdio.out") const stderr_port: int = get_int("stdio.err") stdout_socket.connect("localhost", stdout_port) stderr_socket.connect("localhost", stderr_port) function get_int(name: String): int { return parseInt(env[name]) } } //---------------------------------------------------------------- public function get env(): * { return _env } public function get argv(): Array { if (env["stdio.argv"] === "") { return [] } else { return env["stdio.argv"].split(" ").map( function (argument: String, ...rest: Array): String { return decodeURIComponent(argument) } ) } } public function puts(value: *): void { if (available) { if (interactive) { readline_socket.puts("!" + value) } else { stdout.puts(value) } } else { debug.show("puts: " + value) } } public function warn(value: *): void { if (available) { stderr.puts(value) } else { debug.show("warn: " + value) } } public function die(value: *): void { if (available) { warn(value); exit(-1) } else { throw new Error("fatal error: " + String(value)) } } public function style(styles: String, string: String): String { const codes: Object = { none: 0, bold: 1, italic: 3, underline: 4, inverse: 7, black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37, gray: 90, grey: 90 } if (styles === "") { return string } else { return styles.split(/\s+/).map( function (style: String, ...rest: Array): String { if (style in codes) { return escape_sequence(codes[style]) } else { throw new Error("style not supported: " + style) } } ).join("") + string + escape_sequence(0) } function escape_sequence(code: int): String { return "\x1b[" + code + "m" } } public function gets(callback: Function): void { if (available) { if (interactive) { readline_socket.puts("?" + _prompt) } stdin.gets(callback) } else { callback(null) } } public function set prompt(value: String): void { _prompt = value } public function get stdin(): InputStream { return buffered_stdin } public function get stdout(): OutputStream { return stdout_socket } public function get stderr(): OutputStream { return stderr_socket } public function handle(error: *): void { if (error is UncaughtErrorEvent) { UncaughtErrorEvent(error).preventDefault() handle(UncaughtErrorEvent(error).error) exit(-1) } else if (error is Error) { // Important: Avoid the `Error(x)` casting syntax. http_post("/error", (error as Error).getStackTrace()) } else if (error is ErrorEvent) { const event: ErrorEvent = ErrorEvent(error) http_post("/error", ( getQualifiedClassName(event) + ": " + event.text + " [event.target: " + event.target + "]" )) } else { http_post("/error", String(error)) } } private function shell_quote(word: String): String { if (/^[-=.,\w]+$/.test(word)) { return word } else { return "'" + word.replace(/'/g, "'\\''") + "'" } } public function exec( command: *, callback: Function, errback: Function = null ): void { if (available) { var stdin: String = "" if ("command" in command && "stdin" in command) { stdin = command.stdin command = command.command } if (command is String) { command = ["sh", "-c", command] } const url: String = "/exec?" + command.map( function (word: String, ...rest: Array): String { return encodeURIComponent(word) } ).join("&") http_post(url, stdin, function (data: String): void { const result: XML = new XML(data) const status: int = result.@status const stdout: String = result.stdout.text() const stderr: String = result.stderr.text() if (status === 0) { if (callback.length === 1) { callback(stdout) } else { callback(stdout, stderr) } } else if (errback === null) { warn(stderr) } else if (errback.length === 1) { errback(new Error(stderr)) } else if (errback.length === 2) { errback(status, stderr) } else { errback(status, stderr, stdout) } }) } else { throw new Error("cannot execute command: process not available") } } public function exit(status: int = 0): void { if (available) { when_ready(function (): void { http_post("/exit", String(status)) }) } else { throw new Error("cannot exit: process not available") } } //---------------------------------------------------------------- private var n_pending_requests: int = 0 private var ready_callbacks: Array = [] private function when_ready(callback: Function): void { if (n_pending_requests === 0) { callback() } else { ready_callbacks.push(callback) } } private function handle_ready(): void { for each (var callback: Function in ready_callbacks) { callback() } ready_callbacks = [] } private function http_post( path: String, content: String, callback: Function = null ): void { const request: URLRequest = new URLRequest(http_url + path) request.method = "POST" request.data = content const loader: URLLoader = new URLLoader ++n_pending_requests loader.addEventListener( Event.COMPLETE, function (event: Event): void { if (callback !== null) { callback(loader.data) } if (--n_pending_requests === 0) { handle_ready() } } ) loader.load(request) } } }
package stdio { import flash.display.* import flash.events.* import flash.utils.* import flash.net.* public class StandardProcess implements Process { private const buffered_stdin: BufferedStream = new BufferedStream private const stdin_socket: SocketStream = new SocketStream private const readline_socket: SocketStream = new SocketStream private const stdout_socket: SocketStream = new SocketStream private const stderr_socket: SocketStream = new SocketStream private var _env: Object private var _prompt: String = "> " public function StandardProcess(env: Object) { _env = env } public function initialize(callback: Function): void { if (available) { connect(callback) } else { callback() } } public function get available(): Boolean { return env["stdio.enabled"] } private function get http_url(): String { return env["stdio.http"] } private function get interactive(): Boolean { return env["stdio.interactive"] === "true" } private function connect(callback: Function): void { stdin_socket.onopen = onopen readline_socket.onopen = onopen stdout_socket.onopen = onopen stderr_socket.onopen = onopen var n: int = 0 function onopen(): void { if (++n === 3) { callback() } } stdin_socket.ondata = buffered_stdin.write stdin_socket.onclose = buffered_stdin.close readline_socket.ondata = buffered_stdin.write readline_socket.onclose = buffered_stdin.close const stdin_port: int = get_int("stdio.in") const readline_port: int = get_int("stdio.readline") if (interactive) { readline_socket.connect("localhost", readline_port) } else { stdin_socket.connect("localhost", stdin_port) } const stdout_port: int = get_int("stdio.out") const stderr_port: int = get_int("stdio.err") stdout_socket.connect("localhost", stdout_port) stderr_socket.connect("localhost", stderr_port) function get_int(name: String): int { return parseInt(env[name]) } } //---------------------------------------------------------------- public function get env(): * { return _env } public function get argv(): Array { if (!env["stdio.argv"]) { return [] } else { return env["stdio.argv"].split(" ").map( function (argument: String, ...rest: Array): String { return decodeURIComponent(argument) } ) } } public function puts(value: *): void { if (available) { if (interactive) { readline_socket.puts("!" + value) } else { stdout.puts(value) } } else { debug.show("puts: " + value) } } public function warn(value: *): void { if (available) { stderr.puts(value) } else { debug.show("warn: " + value) } } public function die(value: *): void { if (available) { warn(value); exit(-1) } else { throw new Error("fatal error: " + String(value)) } } public function style(styles: String, string: String): String { const codes: Object = { none: 0, bold: 1, italic: 3, underline: 4, inverse: 7, black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37, gray: 90, grey: 90 } if (styles === "") { return string } else { return styles.split(/\s+/).map( function (style: String, ...rest: Array): String { if (style in codes) { return escape_sequence(codes[style]) } else { throw new Error("style not supported: " + style) } } ).join("") + string + escape_sequence(0) } function escape_sequence(code: int): String { return "\x1b[" + code + "m" } } public function gets(callback: Function): void { if (available) { if (interactive) { readline_socket.puts("?" + _prompt) } stdin.gets(callback) } else { callback(null) } } public function set prompt(value: String): void { _prompt = value } public function get stdin(): InputStream { return buffered_stdin } public function get stdout(): OutputStream { return stdout_socket } public function get stderr(): OutputStream { return stderr_socket } public function handle(error: *): void { if (error is UncaughtErrorEvent) { UncaughtErrorEvent(error).preventDefault() handle(UncaughtErrorEvent(error).error) exit(-1) } else if (error is Error) { // Important: Avoid the `Error(x)` casting syntax. http_post("/error", (error as Error).getStackTrace()) } else if (error is ErrorEvent) { const event: ErrorEvent = ErrorEvent(error) http_post("/error", ( getQualifiedClassName(event) + ": " + event.text + " [event.target: " + event.target + "]" )) } else { http_post("/error", String(error)) } } private function shell_quote(word: String): String { if (/^[-=.,\w]+$/.test(word)) { return word } else { return "'" + word.replace(/'/g, "'\\''") + "'" } } public function exec( command: *, callback: Function, errback: Function = null ): void { if (available) { var stdin: String = "" if ("command" in command && "stdin" in command) { stdin = command.stdin command = command.command } if (command is String) { command = ["sh", "-c", command] } const url: String = "/exec?" + command.map( function (word: String, ...rest: Array): String { return encodeURIComponent(word) } ).join("&") http_post(url, stdin, function (data: String): void { const result: XML = new XML(data) const status: int = result.@status const stdout: String = result.stdout.text() const stderr: String = result.stderr.text() if (status === 0) { if (callback.length === 1) { callback(stdout) } else { callback(stdout, stderr) } } else if (errback === null) { warn(stderr) } else if (errback.length === 1) { errback(new Error(stderr)) } else if (errback.length === 2) { errback(status, stderr) } else { errback(status, stderr, stdout) } }) } else { throw new Error("cannot execute command: process not available") } } public function exit(status: int = 0): void { if (available) { when_ready(function (): void { http_post("/exit", String(status)) }) } else { throw new Error("cannot exit: process not available") } } //---------------------------------------------------------------- private var n_pending_requests: int = 0 private var ready_callbacks: Array = [] private function when_ready(callback: Function): void { if (n_pending_requests === 0) { callback() } else { ready_callbacks.push(callback) } } private function handle_ready(): void { for each (var callback: Function in ready_callbacks) { callback() } ready_callbacks = [] } private function http_post( path: String, content: String, callback: Function = null ): void { const request: URLRequest = new URLRequest(http_url + path) request.method = "POST" request.data = content const loader: URLLoader = new URLLoader ++n_pending_requests loader.addEventListener( Event.COMPLETE, function (event: Event): void { if (callback !== null) { callback(loader.data) } if (--n_pending_requests === 0) { handle_ready() } } ) loader.load(request) } } }
Fix null pointer exception for process.argv sans run-swf.
Fix null pointer exception for process.argv sans run-swf.
ActionScript
mit
dbrock/stdio.as,dbrock/stdio.as,dbrock/stdio.as
1f1c2693b4b70d74d84b4cfcf0fdec6012ecb782
laboratory/core-src/krewdemo/actor/feature_test/PlatformerTester1.as
laboratory/core-src/krewdemo/actor/feature_test/PlatformerTester1.as
package krewdemo.actor.feature_test { import flash.display.Stage; import flash.geom.Rectangle; import starling.display.DisplayObject; import starling.display.Image; import starling.display.QuadBatch; import starling.display.Sprite; import starling.textures.Texture; import starling.textures.TextureSmoothing; import nape.geom.Vec2; import nape.geom.GeomPoly; import nape.geom.GeomPolyList; import nape.phys.Body; import nape.phys.BodyType; import nape.phys.Material; import nape.shape.Circle; import nape.shape.Polygon; import nape.shape.Shape; import nape.space.Space; import nape.util.BitmapDebug; import nape.util.Debug; import nape.callbacks.CbEvent; import nape.callbacks.CbType; import nape.callbacks.InteractionCallback; import nape.callbacks.InteractionListener; import nape.callbacks.InteractionType; import krewfw.NativeStageAccessor; import krewfw.builtin_actor.ui.SimpleVirtualJoystick; import krewfw.core.KrewActor; import krewfw.utils.starling.TileMapHelper; import krewdemo.GameEvent; import krewdemo.scene.PlatformerTestScene1; //------------------------------------------------------------ public class PlatformerTester1 extends KrewActor { private const _debugMode:Boolean = false; protected var _physicsSpace:Space; protected var _gravity:Number = 900; protected var _tileMapDisplays:Array = []; private var _clouds:Sprite; protected var _hero:Body; protected var _velocityX:Number = 0; protected var _velocityY:Number = 0; private var _interactionListener:InteractionListener; private var _wallCbType:CbType = new CbType(); private var _heroCbType:CbType = new CbType(); private var _jumpLife:int = 2; private var _isSceneEnding:Boolean = false; private var _debugDraw:Debug; //------------------------------------------------------------ public override function init():void { var gravity:Vec2 = Vec2.weak(0, _gravity); _physicsSpace = new Space(gravity); _clouds = _makeClouds(); addChild(_clouds); for (var i:int=0; i < 2; ++i) { _tileMapDisplays[i] = _makeMapDisplay("view_" + (i + 1)); _tileMapDisplays[i].scaleX = 1.0; _tileMapDisplays[i].scaleY = 1.0; addChild(_tileMapDisplays[i]); } _initWallCollision("collision_1", 0.0); _initWallCollision("collision_bound", 4.0); _initHero(); _initDebugDraw(); _interactionListener = new InteractionListener( CbEvent.BEGIN, InteractionType.COLLISION, _heroCbType, _wallCbType, _onHeroToWall ); _hero.cbTypes.add(_heroCbType); _physicsSpace.listeners.add(_interactionListener); listen(SimpleVirtualJoystick.UPDATE_JOYSTICK, _onUpdateJoystick); listen(GameEvent.TRIGGER_JUMP, _onTriggerJump); } protected override function onDispose():void { _physicsSpace.bodies.foreach(function(body:Body):void { _removePhysicsBody(body); }); _physicsSpace.bodies.clear(); _physicsSpace.clear(); _physicsSpace = null; if (_debugDraw) { _debugDraw.clear(); NativeStageAccessor.stage.removeChild(_debugDraw.display); _debugDraw = null; } removeChild(_clouds); _clouds = null; } private function _removePhysicsBody(body:Body):void { _physicsSpace.bodies.remove(body); var image:Image = body.userData.displayObj; if (image) { removeChild(image); image.texture.dispose(); image.dispose(); } body.shapes.foreach(function(shape:Shape):void { shape.body = null; shape = null; }); body.shapes.clear(); body.space = null; body = null; } private function _initHero():void { var physX:Number = 240; var physY:Number = 160; var imageX:Number = 240; var imageY:Number = 160; var size:Number = 32 * 0.94; // nape physics body var body:Body = new Body(BodyType.DYNAMIC); var shape:Polygon = new Polygon(Polygon.box(size * 0.9, size * 0.9, true)); shape.material.elasticity = 0.0; shape.material.dynamicFriction = 0.0; shape.material.staticFriction = 0.0; shape.material.density = 4.0; shape.material.rollingFriction = 1.0; body.shapes.add(shape); body.position.setxy(physX, physY); body.allowRotation = false; _physicsSpace.bodies.add(body); // starling display var image:Image = getImage('rectangle_taro'); addImage(image, size, size, imageX, imageY); body.userData.displayObj = image; _hero = body; } //---------------------------------------------------------------------- // load level-map view //---------------------------------------------------------------------- private function _makeMapDisplay(layerName:String):QuadBatch { var levelInfo:Object = getObject("level_1"); var quadBatch:QuadBatch = new QuadBatch(); for each (var el:Object in levelInfo.layers[layerName].elements) { var image:Image = getImage(el.name); var textureRect:Rectangle = image.texture.frame; image.pivotX = (textureRect.width * 0.5); image.pivotY = (textureRect.height * 0.5); image.x = el.x; image.y = el.y; image.width = el.width; image.height = el.height; image.rotation = krew.deg2rad(el.rotation); quadBatch.addImage(image); } return quadBatch; } private function _makeClouds():Sprite { var sprite:Sprite = new Sprite(); krew.times(16, function():void { var image:Image = getImage("cloud_1"); image.x = krew.rand(-300, 480 + 300); image.y = krew.rand(-200, 320 + 200); var scale:Number = krew.rand(0.4, 1.0); image.scaleX = scale; image.scaleY = scale; sprite.addChild(image); }); return sprite; } //---------------------------------------------------------------------- // load collision //---------------------------------------------------------------------- private function _initWallCollision(layerName:String, elasticity:Number=0):void { var levelInfo:Object = getObject("level_1"); for each (var vertices:Array in levelInfo.layers[layerName].polygons) { _makeCollisionBody(vertices, elasticity); } } private function _makeCollisionBody(vertices:Array, elasticity:Number=0):void { var vecList:Array = []; for each (var vertex:Object in vertices) { vecList.push(Vec2.get(vertex.x, vertex.y)); } var geomPolySrc:GeomPoly = new GeomPoly(vecList); var geomPolyList:GeomPolyList = geomPolySrc.convexDecomposition(); geomPolyList.foreach(function(geomPoly:GeomPoly):void { _addConvexCollision(geomPoly, elasticity); }); } private function _addConvexCollision(geomPoly:GeomPoly, elasticity:Number=0):void { var body:Body = new Body(BodyType.STATIC); var shape:Polygon = new Polygon(geomPoly); shape.material.elasticity = elasticity; // これ 2.0 とかにすればジャンプ床できる body.shapes.add(shape); _physicsSpace.bodies.add(body); body.cbTypes.add(_wallCbType); } //---------------------------------------------------------------------- // landing detection //---------------------------------------------------------------------- private function _onHeroToWall(cb:InteractionCallback):void { var hero:Body = cb.int1.castBody; var wall:Body = cb.int2.castBody; // ToDo: 着地判定をちゃんとやる _onHeroLanding(); // if (hero.position.y < wall.position.y - wall.userData.height/2) { // _onHeroLanding(); // } } private function _onHeroLanding():void { _jumpLife = 2; } //---------------------------------------------------------------------- // update handlers //---------------------------------------------------------------------- protected function _onUpdateJoystick(args:Object):void { _velocityX = args.velocityX * 300; } private function _onTriggerJump(args:Object):void { if (_jumpLife == 0) { return; } --_jumpLife; _hero.velocity.y = -430; } public override function onUpdate(passedTime:Number):void { // physics _hero.velocity.x = _velocityX; if (_hero.velocity.y > 2000) { _hero.velocity.y = 2000; } _physicsSpace.step(passedTime); // view var cloudDepth:Number = 0.2; _clouds.x = 240 - (_hero.position.x * cloudDepth); _clouds.y = 160 - (_hero.position.y * cloudDepth); for (var i:int=0; i < _tileMapDisplays.length; ++i) { _tileMapDisplays[i].x = 240 - _hero.position.x; _tileMapDisplays[i].y = 160 - _hero.position.y; } var heroImage:Image = _hero.userData.displayObj; heroImage.rotation = _hero.rotation; _onUpdatePhysicsDebugDraw(); // out of world border _checkExitWorld(); } private function _checkExitWorld():void { if (_isSceneEnding) { return; } if (_hero.position.y > 1000) { _isSceneEnding = true; sendMessage(GameEvent.NEXT_SCENE, {nextScene: new PlatformerTestScene1}); } } //---------------------------------------------------------------------- // nape debug display //---------------------------------------------------------------------- private function _initDebugDraw():void { if (!_debugMode) { return; } var stage:Stage = NativeStageAccessor.stage; _debugDraw = new BitmapDebug(stage.stageWidth, stage.stageHeight, stage.color); var scale:Number = stage.stageWidth / 480; _debugDraw.display.scaleX = scale; _debugDraw.display.scaleY = scale; _debugDraw.display.alpha = 0.5; stage.addChild(_debugDraw.display); } private function _onUpdatePhysicsDebugDraw():void { if (!_debugDraw) { return; } var scale:Number = NativeStageAccessor.stage.stageWidth / 480; _debugDraw.display.x = (240 - _hero.position.x) * scale; _debugDraw.display.y = (160 - _hero.position.y) * scale; _debugDraw.clear(); _debugDraw.draw(_physicsSpace); _debugDraw.flush(); } } }
package krewdemo.actor.feature_test { import flash.display.Stage; import flash.geom.Rectangle; import starling.display.DisplayObject; import starling.display.Image; import starling.display.QuadBatch; import starling.display.Sprite; import starling.textures.Texture; import starling.textures.TextureSmoothing; import nape.geom.Vec2; import nape.geom.GeomPoly; import nape.geom.GeomPolyList; import nape.phys.Body; import nape.phys.BodyType; import nape.phys.Material; import nape.shape.Circle; import nape.shape.Polygon; import nape.shape.Shape; import nape.space.Space; import nape.util.BitmapDebug; import nape.util.Debug; import nape.callbacks.CbEvent; import nape.callbacks.CbType; import nape.callbacks.InteractionCallback; import nape.callbacks.InteractionListener; import nape.callbacks.InteractionType; import krewfw.NativeStageAccessor; import krewfw.builtin_actor.ui.SimpleVirtualJoystick; import krewfw.core.KrewActor; import krewfw.utils.starling.TileMapHelper; import krewdemo.GameEvent; import krewdemo.scene.PlatformerTestScene1; //------------------------------------------------------------ public class PlatformerTester1 extends KrewActor { private const _debugMode:Boolean = false; protected var _physicsSpace:Space; protected var _gravity:Number = 900; private var _mapScale:Number = 0.5; protected var _tileMapDisplays:Array = []; private var _clouds:Sprite; protected var _hero:Body; protected var _velocityX:Number = 0; protected var _velocityY:Number = 0; private var _interactionListener:InteractionListener; private var _wallCbType:CbType = new CbType(); private var _heroCbType:CbType = new CbType(); private var _jumpLife:int = 2; private var _isSceneEnding:Boolean = false; private var _debugDraw:Debug; //------------------------------------------------------------ public override function init():void { var gravity:Vec2 = Vec2.weak(0, _gravity); _physicsSpace = new Space(gravity); _clouds = _makeClouds(); addChild(_clouds); for (var i:int=0; i < 2; ++i) { _tileMapDisplays[i] = _makeMapDisplay("view_" + (i + 1)); _tileMapDisplays[i].scaleX = _mapScale; _tileMapDisplays[i].scaleY = _mapScale; addChild(_tileMapDisplays[i]); } _initWallCollision("collision_1", 0.0); _initWallCollision("collision_bound", 4.0); _initHero(); _initDebugDraw(); _interactionListener = new InteractionListener( CbEvent.BEGIN, InteractionType.COLLISION, _heroCbType, _wallCbType, _onHeroToWall ); _hero.cbTypes.add(_heroCbType); _physicsSpace.listeners.add(_interactionListener); listen(SimpleVirtualJoystick.UPDATE_JOYSTICK, _onUpdateJoystick); listen(GameEvent.TRIGGER_JUMP, _onTriggerJump); } protected override function onDispose():void { _physicsSpace.bodies.foreach(function(body:Body):void { _removePhysicsBody(body); }); _physicsSpace.bodies.clear(); _physicsSpace.clear(); _physicsSpace = null; if (_debugDraw) { _debugDraw.clear(); NativeStageAccessor.stage.removeChild(_debugDraw.display); _debugDraw = null; } removeChild(_clouds); _clouds = null; } private function _removePhysicsBody(body:Body):void { _physicsSpace.bodies.remove(body); var image:Image = body.userData.displayObj; if (image) { removeChild(image); image.texture.dispose(); image.dispose(); } body.shapes.foreach(function(shape:Shape):void { shape.body = null; shape = null; }); body.shapes.clear(); body.space = null; body = null; } private function _initHero():void { var physX:Number = 240; var physY:Number = 160; var imageX:Number = 240; var imageY:Number = 160; var size:Number = 32 * 0.94; // nape physics body var body:Body = new Body(BodyType.DYNAMIC); var shape:Polygon = new Polygon(Polygon.box(size * 0.9, size * 0.9, true)); shape.material.elasticity = 0.0; shape.material.dynamicFriction = 0.0; shape.material.staticFriction = 0.0; shape.material.density = 4.0; shape.material.rollingFriction = 1.0; body.shapes.add(shape); body.position.setxy(physX, physY); body.allowRotation = false; _physicsSpace.bodies.add(body); // starling display var image:Image = getImage('rectangle_taro'); addImage(image, size * _mapScale, size * _mapScale, imageX, imageY); _hero = body; _hero.userData.displayObj = image; } //---------------------------------------------------------------------- // load level-map view //---------------------------------------------------------------------- private function _makeMapDisplay(layerName:String):QuadBatch { var levelInfo:Object = getObject("level_1"); var quadBatch:QuadBatch = new QuadBatch(); for each (var el:Object in levelInfo.layers[layerName].elements) { var image:Image = getImage(el.name); var textureRect:Rectangle = image.texture.frame; image.pivotX = (textureRect.width * 0.5); image.pivotY = (textureRect.height * 0.5); image.x = el.x; image.y = el.y; image.width = el.width; image.height = el.height; image.rotation = krew.deg2rad(el.rotation); quadBatch.addImage(image); } return quadBatch; } private function _makeClouds():Sprite { var sprite:Sprite = new Sprite(); krew.times(16, function():void { var image:Image = getImage("cloud_1"); image.x = krew.rand(-300, 480 + 300); image.y = krew.rand(-200, 320 + 200); var scale:Number = krew.rand(0.4, 1.0); image.scaleX = scale; image.scaleY = scale; sprite.addChild(image); }); return sprite; } //---------------------------------------------------------------------- // load collision //---------------------------------------------------------------------- private function _initWallCollision(layerName:String, elasticity:Number=0):void { var levelInfo:Object = getObject("level_1"); for each (var vertices:Array in levelInfo.layers[layerName].polygons) { _makeCollisionBody(vertices, elasticity); } } private function _makeCollisionBody(vertices:Array, elasticity:Number=0):void { var vecList:Array = []; for each (var vertex:Object in vertices) { vecList.push(Vec2.get(vertex.x, vertex.y)); } var geomPolySrc:GeomPoly = new GeomPoly(vecList); var geomPolyList:GeomPolyList = geomPolySrc.convexDecomposition(); geomPolyList.foreach(function(geomPoly:GeomPoly):void { _addConvexCollision(geomPoly, elasticity); }); } private function _addConvexCollision(geomPoly:GeomPoly, elasticity:Number=0):void { var body:Body = new Body(BodyType.STATIC); var shape:Polygon = new Polygon(geomPoly); shape.material.elasticity = elasticity; // これ 2.0 とかにすればジャンプ床できる body.shapes.add(shape); _physicsSpace.bodies.add(body); body.cbTypes.add(_wallCbType); } //---------------------------------------------------------------------- // landing detection //---------------------------------------------------------------------- private function _onHeroToWall(cb:InteractionCallback):void { var hero:Body = cb.int1.castBody; var wall:Body = cb.int2.castBody; // ToDo: 着地判定をちゃんとやる _onHeroLanding(); // if (hero.position.y < wall.position.y - wall.userData.height/2) { // _onHeroLanding(); // } } private function _onHeroLanding():void { _jumpLife = 2; } //---------------------------------------------------------------------- // update handlers //---------------------------------------------------------------------- protected function _onUpdateJoystick(args:Object):void { _velocityX = args.velocityX * 300; if (Math.abs(args.velocityY) > 0.5) { _updateMapScale(args.velocityY * 0.01); } } private function _updateMapScale(zoom:Number):void { _mapScale += zoom; for (var i:int=0; i < 2; ++i) { _tileMapDisplays[i].scaleX = _mapScale; _tileMapDisplays[i].scaleY = _mapScale; } var heroSize:Number = 32 * 0.94 * _mapScale; _hero.userData.displayObj.width = heroSize; _hero.userData.displayObj.height = heroSize; _updateView(); } private function _onTriggerJump(args:Object):void { if (_jumpLife == 0) { return; } --_jumpLife; _hero.velocity.y = -430; } public override function onUpdate(passedTime:Number):void { // physics _hero.velocity.x = _velocityX; if (_hero.velocity.y > 2000) { _hero.velocity.y = 2000; } _physicsSpace.step(passedTime); // view _updateView(); _onUpdatePhysicsDebugDraw(); // out of world border _checkExitWorld(); } private function _updateView():void { var cloudDepth:Number = 0.2; _clouds.x = 240 - (_hero.position.x * cloudDepth); _clouds.y = 160 - (_hero.position.y * cloudDepth); for (var i:int=0; i < _tileMapDisplays.length; ++i) { _tileMapDisplays[i].x = 240 - (_hero.position.x * _mapScale); _tileMapDisplays[i].y = 160 - (_hero.position.y * _mapScale); } var heroImage:Image = _hero.userData.displayObj; heroImage.rotation = _hero.rotation; } private function _checkExitWorld():void { if (_isSceneEnding) { return; } if (_hero.position.y > 1000) { _isSceneEnding = true; sendMessage(GameEvent.NEXT_SCENE, {nextScene: new PlatformerTestScene1}); } } //---------------------------------------------------------------------- // nape debug display //---------------------------------------------------------------------- private function _initDebugDraw():void { if (!_debugMode) { return; } var stage:Stage = NativeStageAccessor.stage; _debugDraw = new BitmapDebug(stage.stageWidth, stage.stageHeight, stage.color); var scale:Number = stage.stageWidth / 480; _debugDraw.display.scaleX = scale; _debugDraw.display.scaleY = scale; _debugDraw.display.alpha = 0.5; stage.addChild(_debugDraw.display); } private function _onUpdatePhysicsDebugDraw():void { if (!_debugDraw) { return; } var scale:Number = NativeStageAccessor.stage.stageWidth / 480; _debugDraw.display.x = (240 - _hero.position.x) * scale; _debugDraw.display.y = (160 - _hero.position.y) * scale; _debugDraw.clear(); _debugDraw.draw(_physicsSpace); _debugDraw.flush(); } } }
Modify lab.
Modify lab.
ActionScript
mit
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
184ff299cc1dd7fd83f2e2d855213e21176f6a54
src/aerys/minko/render/material/phong/multipass/PhongEmissiveShader.as
src/aerys/minko/render/material/phong/multipass/PhongEmissiveShader.as
package aerys.minko.render.material.phong.multipass { import aerys.minko.render.RenderTarget; import aerys.minko.render.material.basic.BasicShader; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.ShaderSettings; import aerys.minko.render.shader.part.phong.PhongShaderPart; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.BlendingDestination; import aerys.minko.type.enum.BlendingSource; import aerys.minko.type.enum.DepthTest; public class PhongEmissiveShader extends BasicShader { private var _lightAccumulator : ITextureResource; private var _screenPos : SFloat; public function PhongEmissiveShader(lightAccumulator : ITextureResource, renderTarget : RenderTarget = null, priority : Number = 0.0) { super(renderTarget, priority); _lightAccumulator = lightAccumulator; } override protected function initializeSettings(settings : ShaderSettings) : void { super.initializeSettings(settings); if (!_lightAccumulator) { settings.blending = BlendingDestination.SOURCE_COLOR | BlendingSource.ZERO; settings.depthTest = DepthTest.LESS | DepthTest.EQUAL; } } override protected function getVertexPosition() : SFloat { return _screenPos = super.getVertexPosition(); } override protected function getPixelColor() : SFloat { var diffuse : SFloat = super.getPixelColor(); if (_lightAccumulator) { var uv : SFloat = interpolate(_screenPos); uv = divide(uv.xy, uv.w); uv = multiply(add(float2(uv.x, negate(uv.y)), 1), .5); var lighting : SFloat = sampleTexture(getTexture(_lightAccumulator), uv); diffuse = float4(multiply(diffuse.rgb, lighting.rgb), diffuse.a); } return diffuse; } } }
package aerys.minko.render.material.phong.multipass { import aerys.minko.render.RenderTarget; import aerys.minko.render.material.basic.BasicShader; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.ShaderSettings; import aerys.minko.type.enum.BlendingDestination; import aerys.minko.type.enum.BlendingSource; import aerys.minko.type.enum.DepthTest; public class PhongEmissiveShader extends BasicShader { private var _lightAccumulator : ITextureResource; private var _screenPos : SFloat; public function PhongEmissiveShader(lightAccumulator : ITextureResource, renderTarget : RenderTarget = null, priority : Number = 0.0) { super(renderTarget, priority); _lightAccumulator = lightAccumulator; } override protected function initializeSettings(settings : ShaderSettings) : void { super.initializeSettings(settings); if (!_lightAccumulator) { settings.blending = BlendingDestination.SOURCE_COLOR | BlendingSource.ZERO; settings.depthTest = DepthTest.LESS | DepthTest.EQUAL; } } override protected function getVertexPosition() : SFloat { return _screenPos = super.getVertexPosition(); } override protected function getPixelColor() : SFloat { var diffuse : SFloat = super.getPixelColor(); if (_lightAccumulator) { var uv : SFloat = interpolate(_screenPos); uv = divide(uv.xy, uv.w); uv = multiply(add(float2(uv.x, negate(uv.y)), 1), .5); var lighting : SFloat = sampleTexture(getTexture(_lightAccumulator), uv); diffuse = float4(multiply(diffuse.rgb, lighting.rgb), diffuse.a); } return diffuse; } } }
remove useless import
remove useless import
ActionScript
mit
aerys/minko-as3
ad7e24eb67894f1497ef32a81ef35471baccf840
actionscript/src/com/freshplanet/ane/AirCapabilities/AirCapabilities.as
actionscript/src/com/freshplanet/ane/AirCapabilities/AirCapabilities.as
/* * Copyright 2017 FreshPlanet * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.freshplanet.ane.AirCapabilities { import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesLowMemoryEvent; import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesOpenURLEvent; import flash.display.BitmapData; import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirCapabilities extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// /** * Is the ANE supported on the current platform */ static public function get isSupported():Boolean { return (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0) || Capabilities.manufacturer.indexOf("Android") > -1; } /** * If <code>true</code>, logs will be displayed at the ActionScript and native level. */ public function setLogging(value:Boolean):void { _doLogging = value; if (isSupported) _extContext.call("setLogging", value); } public function get nativeLogger():ILogger { return _logger; } /** * AirCapabilities instance */ static public function get instance():AirCapabilities { return _instance != null ? _instance : new AirCapabilities() } /** * Is SMS available * @return */ public function hasSmsEnabled():Boolean { if (isSupported) return _extContext.call("hasSMS"); return false; } /** * Is Twitter available * @return */ public function hasTwitterEnabled():Boolean { if (isSupported) return _extContext.call("hasTwitter"); return false; } /** * Sends an SMS message * @param message to send * @param recipient phonenumber */ public function sendMsgWithSms(message:String, recipient:String = null):void { if (isSupported) _extContext.call("sendWithSms", message, recipient); } /** * Sends a Twitter message * @param message */ public function sendMsgWithTwitter(message:String):void { if (isSupported) _extContext.call("sendWithTwitter", message); } /** * Redirect user to Rating page * @param appId * @param appName */ public function redirecToRating(appId:String, appName:String):void { if (isSupported) _extContext.call("redirectToRating", appId, appName); } /** * Model of the device * @return */ public function getDeviceModel():String { if (isSupported) return _extContext.call("getDeviceModel") as String; return ""; } /** * Name of the machine * @return */ public function getMachineName():String { if (isSupported) return _extContext.call("getMachineName") as String; return ""; } /** * Opens the referral link URL * @param url */ public function processReferralLink(url:String):void { if (isSupported) _extContext.call("processReferralLink", url); } /** * Opens Facebook page * @param pageId id of the facebook page */ public function redirectToPageId(pageId:String):void { if (isSupported) _extContext.call("redirectToPageId", pageId); } /** * Opens Twitter account * @param twitterAccount */ public function redirectToTwitterAccount(twitterAccount:String):void { if (isSupported) _extContext.call("redirectToTwitterAccount", twitterAccount); } /** * Is posting pictures on Twitter enabled * @return */ public function canPostPictureOnTwitter():Boolean { if (isSupported) return _extContext.call("canPostPictureOnTwitter"); return false; } /** * Post new picture on Twitter * @param message * @param bitmapData */ public function postPictureOnTwitter(message:String, bitmapData:BitmapData):void { if (isSupported) _extContext.call("postPictureOnTwitter", message, bitmapData); } /** * Is Instagram enabled * @return */ public function hasInstagramEnabled():Boolean { if (isSupported) return _extContext.call("hasInstagramEnabled"); return false; } /** * Post new picture on Instagram * @param message * @param bitmapData * @param x * @param y * @param width * @param height */ public function postPictureOnInstagram(message:String, bitmapData:BitmapData, x:int, y:int, width:int, height:int):void { if (isSupported) _extContext.call("postPictureOnInstagram", message, bitmapData, x, y, width, height); } /** * Open an application (if installed on the Device) or send the player to the appstore. iOS Only * @param schemes List of schemes (String) that the application accepts. Examples : @"sms://", @"twit://". You can find schemes in http://handleopenurl.com/ * @param appStoreURL (optional) Link to the AppStore page for the Application for the player to download. URL can be generated via Apple's linkmaker (itunes.apple.com/linkmaker?) */ public function openExternalApplication(schemes:Array, appStoreURL:String = null):void { if (isSupported && Capabilities.manufacturer.indexOf("Android") == -1) _extContext.call("openExternalApplication", schemes, appStoreURL); } /** * Is opening URLs available * @param url * @return */ public function canOpenURL(url:String):Boolean { return isSupported ? _extContext.call("canOpenURL", url) as Boolean : false; } /** * Open URL * @param url */ public function openURL(url:String):void { if (canOpenURL(url)) _extContext.call("openURL", url); } /** * Opens modal app store. Available on iOS only * @param appStoreId id of the app to open a modal view to (do not include the "id" at the beginning of the number) */ public function openModalAppStoreIOS(appStoreId:String):void { if (Capabilities.manufacturer.indexOf("iOS") > -1) _extContext.call("openModalAppStore", appStoreId); } /** * Version of the operating system * @return */ public function getOSVersion():String { if (isSupported) return _extContext.call("getOSVersion") as String; return ""; } /** * @return current amount of RAM being used in bytes */ public function getCurrentMem():Number { if (!isSupported) return -1; var ret:Object = _extContext.call("getCurrentMem"); if (ret is Error) throw ret; else return ret ? ret as Number : 0; } /** * @return amount of RAM used by the VM */ public function getCurrentVirtualMem():Number { if(!isSupported) return -1; if (Capabilities.manufacturer.indexOf("iOS") == -1) return -1; var ret:Object = _extContext.call("getCurrentVirtualMem"); if (ret is Error) throw ret; else return ret ? ret as Number : 0; } /** * @return is requesting review available. Available on iOS only */ public function canRequestReview():Boolean { if (!isSupported) return false; if (Capabilities.manufacturer.indexOf("iOS") == -1) return false; return _extContext.call("canRequestReview"); } /** * Request AppStore review. Available on iOS only */ public function requestReview():void { if (!canRequestReview()) return; _extContext.call("requestReview"); } /** * Generate haptic feedback - iOS only */ public function generateHapticFeedback(feedbackType:AirCapabilitiesHapticFeedbackType):void { if (Capabilities.manufacturer.indexOf("iOS") < 0) return; if(!feedbackType) return _extContext.call("generateHapticFeedback", feedbackType.value); } public function getNativeScale():Number { if (Capabilities.manufacturer.indexOf("iOS") < 0) return 1; return _extContext.call("getNativeScale"); } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// static private const EXTENSION_ID:String = "com.freshplanet.ane.AirCapabilities"; static private var _instance:AirCapabilities = null; private var _extContext:ExtensionContext = null; private var _doLogging:Boolean = false; private var _logger:ILogger; /** * "private" singleton constructor */ public function AirCapabilities() { super(); if (_instance) throw new Error("singleton class, use .instance"); _extContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null); _extContext.addEventListener(StatusEvent.STATUS, _handleStatusEvent); if (isSupported) _logger = new NativeLogger(_extContext); else _logger = new DefaultLogger(); _instance = this; } private function _handleStatusEvent(event:StatusEvent):void { if (event.code == "log") _doLogging && trace("[AirCapabilities] " + event.level); else if (event.code == "OPEN_URL") this.dispatchEvent(new AirCapabilitiesOpenURLEvent(AirCapabilitiesOpenURLEvent.OPEN_URL_SUCCESS, event.level)); else if (event.code == AirCapabilitiesLowMemoryEvent.LOW_MEMORY_WARNING) { var memory:Number = Number(event.level); this.dispatchEvent(new AirCapabilitiesLowMemoryEvent(event.code, memory)); } else this.dispatchEvent(event); } } }
/* * Copyright 2017 FreshPlanet * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.freshplanet.ane.AirCapabilities { import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesLowMemoryEvent; import com.freshplanet.ane.AirCapabilities.events.AirCapabilitiesOpenURLEvent; import flash.display.BitmapData; import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirCapabilities extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// /** * Is the ANE supported on the current platform */ static public function get isSupported():Boolean { return (Capabilities.manufacturer.indexOf("iOS") > -1 && Capabilities.os.indexOf("x86_64") < 0 && Capabilities.os.indexOf("i386") < 0) || Capabilities.manufacturer.indexOf("Android") > -1; } /** * If <code>true</code>, logs will be displayed at the ActionScript and native level. */ public function setLogging(value:Boolean):void { _doLogging = value; if (isSupported) _extContext.call("setLogging", value); } public function get nativeLogger():ILogger { return _logger; } /** * AirCapabilities instance */ static public function get instance():AirCapabilities { return _instance != null ? _instance : new AirCapabilities() } /** * Is SMS available * @return */ public function hasSmsEnabled():Boolean { if (isSupported) return _extContext.call("hasSMS"); return false; } /** * Is Twitter available * @return */ public function hasTwitterEnabled():Boolean { if (isSupported) return _extContext.call("hasTwitter"); return false; } /** * Sends an SMS message * @param message to send * @param recipient phonenumber */ public function sendMsgWithSms(message:String, recipient:String = null):void { if (isSupported) _extContext.call("sendWithSms", message, recipient); } /** * Sends a Twitter message * @param message */ public function sendMsgWithTwitter(message:String):void { if (isSupported) _extContext.call("sendWithTwitter", message); } /** * Redirect user to Rating page * @param appId * @param appName */ public function redirecToRating(appId:String, appName:String):void { if (isSupported) _extContext.call("redirectToRating", appId, appName); } /** * Model of the device * @return */ public function getDeviceModel():String { if (isSupported) return _extContext.call("getDeviceModel") as String; return ""; } /** * Name of the machine * @return */ public function getMachineName():String { if (isSupported) return _extContext.call("getMachineName") as String; return ""; } /** * Opens the referral link URL * @param url */ public function processReferralLink(url:String):void { if (isSupported) _extContext.call("processReferralLink", url); } /** * Opens Facebook page * @param pageId id of the facebook page */ public function redirectToPageId(pageId:String):void { if (isSupported) _extContext.call("redirectToPageId", pageId); } /** * Opens Twitter account * @param twitterAccount */ public function redirectToTwitterAccount(twitterAccount:String):void { if (isSupported) _extContext.call("redirectToTwitterAccount", twitterAccount); } /** * Is posting pictures on Twitter enabled * @return */ public function canPostPictureOnTwitter():Boolean { if (isSupported) return _extContext.call("canPostPictureOnTwitter"); return false; } /** * Post new picture on Twitter * @param message * @param bitmapData */ public function postPictureOnTwitter(message:String, bitmapData:BitmapData):void { if (isSupported) _extContext.call("postPictureOnTwitter", message, bitmapData); } /** * Is Instagram enabled * @return */ public function hasInstagramEnabled():Boolean { if (isSupported) return _extContext.call("hasInstagramEnabled"); return false; } /** * Post new picture on Instagram * @param message * @param bitmapData * @param x * @param y * @param width * @param height */ public function postPictureOnInstagram(message:String, bitmapData:BitmapData, x:int, y:int, width:int, height:int):void { if (isSupported) _extContext.call("postPictureOnInstagram", message, bitmapData, x, y, width, height); } /** * Open an application (if installed on the Device) or send the player to the appstore. iOS Only * @param schemes List of schemes (String) that the application accepts. Examples : @"sms://", @"twit://". You can find schemes in http://handleopenurl.com/ * @param appStoreURL (optional) Link to the AppStore page for the Application for the player to download. URL can be generated via Apple's linkmaker (itunes.apple.com/linkmaker?) */ public function openExternalApplication(schemes:Array, appStoreURL:String = null):void { if (isSupported && Capabilities.manufacturer.indexOf("Android") == -1) _extContext.call("openExternalApplication", schemes, appStoreURL); } /** * Is opening URLs available * @param url * @return */ public function canOpenURL(url:String):Boolean { return isSupported ? _extContext.call("canOpenURL", url) as Boolean : false; } /** * Open URL * @param url */ public function openURL(url:String):void { if (canOpenURL(url)) _extContext.call("openURL", url); } /** * Opens modal app store. Available on iOS only * @param appStoreId id of the app to open a modal view to (do not include the "id" at the beginning of the number) */ public function openModalAppStoreIOS(appStoreId:String):void { if (Capabilities.manufacturer.indexOf("iOS") > -1) _extContext.call("openModalAppStore", appStoreId); } /** * Version of the operating system * @return */ public function getOSVersion():String { if (isSupported) return _extContext.call("getOSVersion") as String; return ""; } /** * @return current amount of RAM being used in bytes */ public function getCurrentMem():Number { if (!isSupported) return -1; var ret:Object = _extContext.call("getCurrentMem"); if (ret is Error) throw ret; else return ret ? ret as Number : 0; } /** * @return amount of RAM used by the VM */ public function getCurrentVirtualMem():Number { if(!isSupported) return -1; if (Capabilities.manufacturer.indexOf("iOS") == -1) return -1; var ret:Object = _extContext.call("getCurrentVirtualMem"); if (ret is Error) throw ret; else return ret ? ret as Number : 0; } /** * @return is requesting review available. Available on iOS only */ public function canRequestReview():Boolean { if (!isSupported) return false; if (Capabilities.manufacturer.indexOf("iOS") == -1) return false; return _extContext.call("canRequestReview"); } /** * Request AppStore review. Available on iOS only */ public function requestReview():void { if (!canRequestReview()) return; _extContext.call("requestReview"); } /** * Generate haptic feedback - iOS only */ public function generateHapticFeedback(feedbackType:AirCapabilitiesHapticFeedbackType):void { if (Capabilities.manufacturer.indexOf("iOS") < 0) return; if(!feedbackType) return _extContext.call("generateHapticFeedback", feedbackType.value); } public function getNativeScale():Number { if (Capabilities.manufacturer.indexOf("iOS") < 0) return 1; return _extContext.call("getNativeScale") as Number; } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// static private const EXTENSION_ID:String = "com.freshplanet.ane.AirCapabilities"; static private var _instance:AirCapabilities = null; private var _extContext:ExtensionContext = null; private var _doLogging:Boolean = false; private var _logger:ILogger; /** * "private" singleton constructor */ public function AirCapabilities() { super(); if (_instance) throw new Error("singleton class, use .instance"); _extContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null); _extContext.addEventListener(StatusEvent.STATUS, _handleStatusEvent); if (isSupported) _logger = new NativeLogger(_extContext); else _logger = new DefaultLogger(); _instance = this; } private function _handleStatusEvent(event:StatusEvent):void { if (event.code == "log") _doLogging && trace("[AirCapabilities] " + event.level); else if (event.code == "OPEN_URL") this.dispatchEvent(new AirCapabilitiesOpenURLEvent(AirCapabilitiesOpenURLEvent.OPEN_URL_SUCCESS, event.level)); else if (event.code == AirCapabilitiesLowMemoryEvent.LOW_MEMORY_WARNING) { var memory:Number = Number(event.level); this.dispatchEvent(new AirCapabilitiesLowMemoryEvent(event.code, memory)); } else this.dispatchEvent(event); } } }
fix build issue
fix build issue
ActionScript
apache-2.0
freshplanet/ANE-AirCapabilities,freshplanet/ANE-AirCapabilities,freshplanet/ANE-AirCapabilities
ff2de9cd705d2cd0b10524477923d2151e6c053e
src/aerys/minko/type/MouseManager.as
src/aerys/minko/type/MouseManager.as
package aerys.minko.type { import flash.events.IEventDispatcher; import flash.events.MouseEvent; import flash.ui.Mouse; public final class MouseManager { private var _x : Number = 0.; private var _y : Number = 0.; private var _deltaX : Number = 0.; private var _deltaY : Number = 0.; private var _deltaDistance : Number = 0.; private var _leftButtonDown : Boolean = false; private var _middleButtonDown : Boolean = false; private var _rightButtonDown : Boolean = false; private var _mouseDown : Signal = new Signal("mouseDown"); private var _mouseUp : Signal = new Signal("mouseUp"); private var _cursors : Vector.<String> = new <String>[]; public function get x() : Number { return _x; } public function get y() : Number { return _y; } public function get deltaX() : Number { return _deltaX; } public function get deltaY() : Number { return _deltaY; } public function get deltaDistance() : Number { return _deltaDistance; } public function get leftButtonDown() : Boolean { return _leftButtonDown; } public function get middleButtonDown() : Boolean { return _middleButtonDown; } public function get rightButtonDown() : Boolean { return _rightButtonDown; } public function get cursor() : String { return Mouse.cursor; } public function get mouseDown() : Signal { return _mouseDown; } public function get mouseUp() : Signal { return _mouseUp; } public function bind(dispatcher : IEventDispatcher) : void { dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); dispatcher.addEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler); dispatcher.addEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler); if (MouseEvent.RIGHT_CLICK != null) { dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler); dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler); } if (MouseEvent.MIDDLE_CLICK != null) { dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler); dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler); } } public function unbind(dispatcher : IEventDispatcher) : void { dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); dispatcher.removeEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler); dispatcher.removeEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler); if (MouseEvent.RIGHT_CLICK != null) { dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler); dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler); } if (MouseEvent.MIDDLE_CLICK != null) { dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler); dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler); } } private function mouseMoveHandler(event : MouseEvent) : void { var localX : Number = event.localX; var localY : Number = event.localY; _deltaX = localX - _x; _deltaY = localY - _y; _deltaDistance = Math.sqrt(_deltaX * deltaX + deltaY * deltaY); _x = event.localX; _y = event.localY; } private function mouseLeftDownHandler(event : MouseEvent) : void { _leftButtonDown = true; _mouseDown.execute(); } private function mouseLeftUpHandler(event : MouseEvent) : void { _leftButtonDown = false; _mouseUp.execute(); } private function mouseMiddleDownHandler(event : MouseEvent) : void { _middleButtonDown = true; } private function mouseMiddleUpHandler(event : MouseEvent) : void { _middleButtonDown = false; } private function mouseRightDownHandler(event : MouseEvent) : void { _rightButtonDown = true; } private function mouseRightUpHandler(event : MouseEvent) : void { _rightButtonDown = false; } public function pushCursor(cursor : String) : MouseManager { _cursors.push(Mouse.cursor); Mouse.cursor = cursor; return this; } public function popCursor() : MouseManager { Mouse.cursor = _cursors.pop(); return this; } } }
package aerys.minko.type { import flash.events.IEventDispatcher; import flash.events.MouseEvent; import flash.ui.Mouse; public final class MouseManager { private var _x : Number = 0.; private var _y : Number = 0.; private var _deltaX : Number = 0.; private var _deltaY : Number = 0.; private var _deltaDistance : Number = 0.; private var _leftButtonDown : Boolean = false; private var _middleButtonDown : Boolean = false; private var _rightButtonDown : Boolean = false; private var _mouseDown : Signal = new Signal("mouseDown"); private var _mouseUp : Signal = new Signal("mouseUp"); private var _cursors : Vector.<String> = new <String>[]; public function get x() : Number { return _x; } public function get y() : Number { return _y; } public function get deltaX() : Number { return _deltaX; } public function get deltaY() : Number { return _deltaY; } public function get deltaDistance() : Number { return _deltaDistance; } public function get leftButtonDown() : Boolean { return _leftButtonDown; } public function get middleButtonDown() : Boolean { return _middleButtonDown; } public function get rightButtonDown() : Boolean { return _rightButtonDown; } public function get cursor() : String { return Mouse.cursor; } public function get mouseDown() : Signal { return _mouseDown; } public function get mouseUp() : Signal { return _mouseUp; } public function bind(dispatcher : IEventDispatcher) : void { dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); dispatcher.addEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler); dispatcher.addEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler); if (MouseEvent.RIGHT_CLICK != null) { dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler); dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler); } if (MouseEvent.MIDDLE_CLICK != null) { dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler); dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler); } } public function unbind(dispatcher : IEventDispatcher) : void { dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); dispatcher.removeEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler); dispatcher.removeEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler); if (MouseEvent.RIGHT_CLICK != null) { dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler); dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler); } if (MouseEvent.MIDDLE_CLICK != null) { dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler); dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler); } } private function mouseMoveHandler(event : MouseEvent) : void { var localX : Number = event.localX; var localY : Number = event.localY; _deltaX = localX - _x; _deltaY = localY - _y; _deltaDistance = Math.sqrt(_deltaX * deltaX + deltaY * deltaY); _x = event.localX; _y = event.localY; } private function mouseLeftDownHandler(event : MouseEvent) : void { _leftButtonDown = true; _mouseDown.execute(); } private function mouseLeftUpHandler(event : MouseEvent) : void { _leftButtonDown = false; _mouseUp.execute(); } private function mouseMiddleDownHandler(event : MouseEvent) : void { _middleButtonDown = true; } private function mouseMiddleUpHandler(event : MouseEvent) : void { _middleButtonDown = false; } private function mouseRightDownHandler(event : MouseEvent) : void { _rightButtonDown = true; } private function mouseRightUpHandler(event : MouseEvent) : void { _rightButtonDown = false; } public function pushCursor(cursor : String) : MouseManager { _cursors.push(Mouse.cursor); Mouse.cursor = cursor; return this; } public function popCursor() : MouseManager { if (_cursors.length) Mouse.cursor = _cursors.pop(); return this; } } }
fix MouseManager.popCursor() to avoid null pointer exception when the cursor stack is empty
fix MouseManager.popCursor() to avoid null pointer exception when the cursor stack is empty
ActionScript
mit
aerys/minko-as3
3d0629a6ebc416dbd474e9d52f901c7cddd2d35d
Source/Stage3D/Away3D/Libraries/Away3D/src/away3d/materials/methods/AlphaMaskMethod.as
Source/Stage3D/Away3D/Libraries/Away3D/src/away3d/materials/methods/AlphaMaskMethod.as
package away3d.materials.methods { import away3d.arcane; import away3d.core.managers.Stage3DProxy; import away3d.materials.compilation.ShaderRegisterCache; import away3d.materials.compilation.ShaderRegisterElement; import away3d.textures.Texture2DBase; use namespace arcane; /** * AlphaMaskMethod allows the use of an additional texture to specify the alpha value of the material. When used * with the secondary uv set, it allows for a tiled main texture with independently varying alpha (useful for water * etc). */ public class AlphaMaskMethod extends EffectMethodBase { private var _texture:Texture2DBase; private var _useSecondaryUV:Boolean; /** * Creates a new AlphaMaskMethod object * @param texture The texture to use as the alpha mask. * @param useSecondaryUV Indicated whether or not the secondary uv set for the mask. This allows mapping alpha independently. */ public function AlphaMaskMethod(texture:Texture2DBase, useSecondaryUV:Boolean = false) { super(); _texture = texture; _useSecondaryUV = useSecondaryUV; } /** * @inheritDoc */ override arcane function initVO(vo:MethodVO):void { vo.needsSecondaryUV = _useSecondaryUV; vo.needsUV = !_useSecondaryUV; } /** * Indicated whether or not the secondary uv set for the mask. This allows mapping alpha independently, for * instance to tile the main texture and normal map while providing untiled alpha, for example to define the * transparency over a tiled water surface. */ public function get useSecondaryUV():Boolean { return _useSecondaryUV; } public function set useSecondaryUV(value:Boolean):void { if (_useSecondaryUV == value) return; _useSecondaryUV = value; invalidateShaderProgram(); } /** * The texture to use as the alpha mask. */ public function get texture():Texture2DBase { return _texture; } public function set texture(value:Texture2DBase):void { _texture = value; } /** * @inheritDoc */ arcane override function activate(vo:MethodVO, stage3DProxy:Stage3DProxy):void { stage3DProxy._context3D.setTextureAt(vo.texturesIndex, _texture.getTextureForStage3D(stage3DProxy)); } /** * @inheritDoc */ arcane override function getFragmentCode(vo:MethodVO, regCache:ShaderRegisterCache, targetReg:ShaderRegisterElement):String { var textureReg:ShaderRegisterElement = regCache.getFreeTextureReg(); var temp:ShaderRegisterElement = regCache.getFreeFragmentVectorTemp(); var uvReg:ShaderRegisterElement = _useSecondaryUV? _sharedRegisters.secondaryUVVarying : _sharedRegisters.uvVarying; vo.texturesIndex = textureReg.index; return getTex2DSampleCode(vo, temp, textureReg, _texture, uvReg) + "mul " + targetReg + ", " + targetReg + ", " + temp + ".x\n"; } } }
package away3d.materials.methods { import away3d.arcane; import away3d.core.managers.Stage3DProxy; import away3d.materials.compilation.ShaderRegisterCache; import away3d.materials.compilation.ShaderRegisterElement; import away3d.textures.Texture2DBase; use namespace arcane; /** * AlphaMaskMethod allows the use of an additional texture to specify the alpha value of the material. When used * with the secondary uv set, it allows for a tiled main texture with independently varying alpha (useful for water * etc). */ public class AlphaMaskMethod extends EffectMethodBase { private var _texture:Texture2DBase; private var _useSecondaryUV:Boolean; /** * Creates a new AlphaMaskMethod object * @param texture The texture to use as the alpha mask. * @param useSecondaryUV Indicated whether or not the secondary uv set for the mask. This allows mapping alpha independently. */ public function AlphaMaskMethod(texture:Texture2DBase, useSecondaryUV:Boolean = false) { super(); _texture = texture; _useSecondaryUV = useSecondaryUV; } /** * @inheritDoc */ override arcane function initVO(vo:MethodVO):void { vo.needsSecondaryUV = _useSecondaryUV; vo.needsUV = !_useSecondaryUV; } /** * Indicated whether or not the secondary uv set for the mask. This allows mapping alpha independently, for * instance to tile the main texture and normal map while providing untiled alpha, for example to define the * transparency over a tiled water surface. */ public function get useSecondaryUV():Boolean { return _useSecondaryUV; } public function set useSecondaryUV(value:Boolean):void { if (_useSecondaryUV == value) return; _useSecondaryUV = value; invalidateShaderProgram(); } /** * The texture to use as the alpha mask. */ public function get texture():Texture2DBase { return _texture; } public function set texture(value:Texture2DBase):void { _texture = value; } /** * @inheritDoc */ arcane override function activate(vo:MethodVO, stage3DProxy:Stage3DProxy):void { stage3DProxy._context3D.setTextureAt(vo.texturesIndex, _texture.getTextureForStage3D(stage3DProxy)); } /** * @inheritDoc */ arcane override function getFragmentCode(vo:MethodVO, regCache:ShaderRegisterCache, targetReg:ShaderRegisterElement):String { var textureReg:ShaderRegisterElement = regCache.getFreeTextureReg(); var temp:ShaderRegisterElement = regCache.getFreeFragmentVectorTemp(); var uvReg:ShaderRegisterElement = _useSecondaryUV? _sharedRegisters.secondaryUVVarying : _sharedRegisters.uvVarying; vo.texturesIndex = textureReg.index; return getTex2DSampleCode(vo, temp, textureReg, _texture, uvReg) + "mul " + targetReg + ".w" + ", " + targetReg + ".w" + ", " + temp + ".x\n"; } } }
fix alpha mask shader
fix alpha mask shader
ActionScript
mit
sunag/sea3d,sunag/sea3d,igor-uzberg/sea3d,igor-uzberg/sea3d,igor-uzberg/sea3d,igor-uzberg/sea3d,sunag/sea3d,igor-uzberg/sea3d,sunag/sea3d,sunag/sea3d,sunag/sea3d
0c8707079a23997ef7da8135a980af26efba2c53
src/flash/tandem/core/Application.as
src/flash/tandem/core/Application.as
//////////////////////////////////////////////////////////////////////////////// // // tandem. explore your world. // Copyright (c) 2007–2008 Daniel Gasienica ([email protected]) // // tandem is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // tandem is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with tandem. If not, see <http://www.gnu.org/licenses/>. // //////////////////////////////////////////////////////////////////////////////// package tandem.core { import caurina.transitions.Tweener; import caurina.transitions.properties.ColorShortcuts; import com.adobe.webapis.flickr.FlickrService; import com.adobe.webapis.flickr.PagedPhotoList; import com.adobe.webapis.flickr.User; import com.adobe.webapis.flickr.events.FlickrResultEvent; import flash.display.DisplayObject; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.system.Security; import tandem.events.TandemEvent; import tandem.model.ApplicationModel; import tandem.ui.GlobalNavigation; import tandem.ui.GlobalNavigationComponent; import tandem.ui.KeyboardNavigationButton; import tandem.ui.KeyboardNavigationButtonComponent; import tandem.ui.MemoryIndicator; import tandem.ui.MemoryIndicatorComponent; import tandem.ui.NotificationOverlay; import tandem.ui.NotificationOverlayComponent; import tandem.ui.Timeline; import tandem.ui.ZoomNavigator; import tandem.ui.ZoomViewport; import tandem.ui.views.StreamView; public class Application extends Sprite { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. */ public function Application() { addEventListener( Event.ADDED_TO_STAGE, addedToStageHandler, false, 0, true ) } //-------------------------------------------------------------------------- // // Class Constants // //-------------------------------------------------------------------------- private const DEFAULT_USER_ADDRESS : String = "gasi" private const DEFAULT_USER_ID : String = "72389028@N00" private const DEFAULT_MINIMUM_ZOOM : Number = 0.25//0.5 private const DEFAULT_MAXIMUM_ZOOM : Number = 180 private const NUM_FARMS = 10 //-------------------------------------------------------------------------- // // Children // //-------------------------------------------------------------------------- private var globalNavigation : GlobalNavigation private var memoryIndicator : MemoryIndicator private var notificationOverlay : NotificationOverlay private var keyboardNavigationButton : KeyboardNavigationButton private var timeline : Timeline private var viewport : ZoomViewport private var navigator : ZoomNavigator private var view : DisplayObject private var initialized : Boolean = false //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var model : ApplicationModel = ApplicationModel.getInstance() private var completed : Boolean = false private var numPhotos : int = 363 private var page : int = 1 private var pageSize : int = 500 private var extras : String = "date_taken, original_format" //-------------------------------------------------------------------------- // // Event Handler: Stage // //-------------------------------------------------------------------------- private function addedToStageHandler( event : Event ) : void { // Code in constructor is interpreted by // AVM, therefore move processing-intensive code // outside, so it can be processed by the JIT compiler initialize() } //-------------------------------------------------------------------------- // // Methods: Initialization // //-------------------------------------------------------------------------- private function initialize() : void { stage.align = StageAlign.TOP_LEFT stage.scaleMode = StageScaleMode.NO_SCALE initializeLibraries() initializeSecurity() registerListeners() createChildren() updateDisplayList() model.service = new FlickrService( model.API_KEY ) model.service.addEventListener( FlickrResultEvent.PEOPLE_GET_PUBLIC_PHOTOS, getPublicPhotosHandler ) } private function initializeSecurity() : void { // TODO: Smells bad… =( Security.loadPolicyFile( "http://static.flickr.com/crossdomain.xml" ) for (var i:int = 0; i < NUM_FARMS; i++) { Security.loadPolicyFile("http://farm" + i + ".static.flickr.com/crossdomain.xml") } Security.loadPolicyFile( "http://l.yimg.com/crossdomain.xml" ) } private function initializeLibraries() : void { // Tweener ColorShortcuts.init() } private function registerListeners() : void { stage.addEventListener( Event.RESIZE, resizeHandler ) addEventListener( TandemEvent.APPLICATION_COMPLETE, applicationCompleteHandler ) SWFAddress.addEventListener( SWFAddressEvent.CHANGE, swfAddressChangeHandler ) } //-------------------------------------------------------------------------- // // User Interface // //-------------------------------------------------------------------------- private function createChildren() : void { createTimeline() createGlobalNavigation() createMemoryIndicator() createNotificationOverlay() createKeyboardNavigationButton() } private function createViewport() : void { completed = false model.photos = [] if( view ) removeChild( view ) if( navigator ) removeChild( navigator ) // view initialized = false view = new StreamView() view.alpha = 0 // container viewport = new ZoomViewport() viewport.minZoom = DEFAULT_MINIMUM_ZOOM viewport.maxZoom = DEFAULT_MAXIMUM_ZOOM viewport.content = view // navigator navigator = new ZoomNavigator() navigator.model = viewport navigator.alpha = 0 // add children to display list addChildAt( viewport, 0 ) addChildAt( view, 1 ) addChildAt( navigator, 2 ) // fade in notification overlay Tweener.addTween( notificationOverlay, { alpha: 1, time: 1 } ) // call service model.service.people.getPublicPhotos( model.user.nsid, extras, Math.min( pageSize, numPhotos ), page ) // initial layout updateDisplayList() } private function createTimeline() : void { //timeline = new TimelineComponent() //addChild( timeline ) } private function createGlobalNavigation() : void { globalNavigation = new GlobalNavigationComponent() addChild( globalNavigation ) } private function createMemoryIndicator() : void { memoryIndicator = new MemoryIndicatorComponent() addChild( memoryIndicator ) } private function createNotificationOverlay() : void { notificationOverlay = new NotificationOverlayComponent() notificationOverlay.alpha = 0 addChild( notificationOverlay ) // fade in notification overlay Tweener.addTween( notificationOverlay, { alpha: 1, time: 1.5, delay: 2 } ) } private function createKeyboardNavigationButton() : void { keyboardNavigationButton = new KeyboardNavigationButtonComponent() keyboardNavigationButton.alpha = 0 addChild( keyboardNavigationButton ) Tweener.addTween( keyboardNavigationButton, { alpha: 1, time: 1.5, delay: 1 } ) } //-------------------------------------------------------------------------- // // SWFAdress // //-------------------------------------------------------------------------- private function swfAddressChangeHandler( event : SWFAddressEvent ) : void { var user : String var action : String = SWFAddress.getPathNames()[ 0 ] var flickrNSIDPattern : RegExp = /[0-9]*@N[0-9]*/ if( action == "photos" ) { // Long URL, e.g. http://flickr.com/photos/gasi // or http://flickr.com/photos/72389028@N00 user = SWFAddress.getPathNames()[ 1 ] } else { // Short URL, e.g. http://flickr.com/gasi user = SWFAddress.getPathNames()[ 0 ] } if( user == null ) { // Default user SWFAddress.setValue( "photos/" + DEFAULT_USER_ADDRESS + "/" ) } else if( flickrNSIDPattern.test( user ) ) { // Look up Flickr NSID, e.g. 72389028@N00 model.service.people.getInfo( user ) model.service.addEventListener( FlickrResultEvent.PEOPLE_GET_INFO, getInfoHandler ) } else { // Look up Flickr URL model.service.urls.lookupUser( "http://flickr.com/photos/" + user + "/" ) model.service.addEventListener( FlickrResultEvent.URLS_LOOKUP_USER, lookupUserHandler ) } } //-------------------------------------------------------------------------- // // Event Handlers: Application // //-------------------------------------------------------------------------- private function resizeHandler( event : Event ) : void { updateDisplayList() } private function applicationCompleteHandler( event : Event ) : void { // fade in view Tweener.addTween( view, { alpha: 1, time: 5 } ) // fade in navigator Tweener.addTween( navigator, { alpha: 1, time: 2, delay: 2 } ) // fade out notification Tweener.addTween( notificationOverlay, { alpha: 0, time: 0.8, delay: 1.8 } ) updateDisplayList() } //-------------------------------------------------------------------------- // // Event Handlers: Service // //-------------------------------------------------------------------------- private function getPublicPhotosHandler( event : FlickrResultEvent ) : void { if( event.success ) { var result : PagedPhotoList = PagedPhotoList( event.data.photos ) // add result data to view if( view is StreamView ) { result.photos.forEach( function( item : *, ...ignored ) : void { model.photos.push( item ) StreamView( view ).addItem( item ) } ) } // we're done if( model.photos.length >= Math.min( numPhotos, result.total ) && !completed ) { completed = true } // fetch more data if( result.page < result.pages && !completed ) { page++ model.service.people.getPublicPhotos( model.user.nsid, extras, pageSize, page ) } if( !initialized ) { initialized = true dispatchEvent( new TandemEvent( TandemEvent.APPLICATION_COMPLETE ) ) } } } private function lookupUserHandler( event : FlickrResultEvent ) : void { if( event.success ) { model.user = User( event.data.user ) createViewport() SWFAddress.setTitle( "tandem — " + model.user.username + " (" + model.user.nsid + ")" ) } else { // Default SWFAddress.setValue( "photos/" + DEFAULT_USER_ADDRESS + "/" ) } } private function getInfoHandler( event : FlickrResultEvent ) : void { if( event.success ) { model.user = User( event.data.user ) createViewport() SWFAddress.setTitle( "tandem — " + model.user.username + " (" + model.user.nsid + ")" ) } else { // Default SWFAddress.setValue( "photos/" + DEFAULT_USER_ADDRESS + "/" ) } } //-------------------------------------------------------------------------- // // Methods: Layout // //-------------------------------------------------------------------------- private function updateDisplayList() : void { // Navigation if( globalNavigation ) { globalNavigation.x = 0 globalNavigation.y = 0 } // Viewport if( viewport ) { viewport.x = 0 viewport.y = 0 viewport.width = stage.stageWidth viewport.height = stage.stageHeight } // Navigator if( navigator ) { navigator.x = stage.stageWidth - navigator.width - 12 navigator.y = globalNavigation ? globalNavigation.height + 12 : 12 } // Timeline if( timeline ) { timeline.width = stage.stageWidth timeline.y = stage.stageHeight - timeline.height } // Memory Indicator if( memoryIndicator ) { memoryIndicator.x = stage.stageWidth - memoryIndicator.width - 10 memoryIndicator.y = stage.stageHeight - memoryIndicator.height - 10 } // Notification Overlay if( notificationOverlay ) { notificationOverlay.x = ( stage.stageWidth - notificationOverlay.width ) / 2 notificationOverlay.y = ( stage.stageHeight - notificationOverlay.height ) / 2 } // Keyboard Navigation Button if( keyboardNavigationButton ) { keyboardNavigationButton.x = ( stage.stageWidth - keyboardNavigationButton.width ) / 2 keyboardNavigationButton.y = stage.stageHeight - keyboardNavigationButton.height - 10 } } } }
//////////////////////////////////////////////////////////////////////////////// // // tandem. explore your world. // Copyright (c) 2007–2008 Daniel Gasienica ([email protected]) // // tandem is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // tandem is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with tandem. If not, see <http://www.gnu.org/licenses/>. // //////////////////////////////////////////////////////////////////////////////// package tandem.core { import caurina.transitions.Tweener; import caurina.transitions.properties.ColorShortcuts; import com.adobe.webapis.flickr.FlickrService; import com.adobe.webapis.flickr.PagedPhotoList; import com.adobe.webapis.flickr.User; import com.adobe.webapis.flickr.events.FlickrResultEvent; import flash.display.DisplayObject; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.system.Security; import tandem.events.TandemEvent; import tandem.model.ApplicationModel; import tandem.ui.GlobalNavigation; import tandem.ui.GlobalNavigationComponent; import tandem.ui.KeyboardNavigationButton; import tandem.ui.KeyboardNavigationButtonComponent; import tandem.ui.MemoryIndicator; import tandem.ui.MemoryIndicatorComponent; import tandem.ui.NotificationOverlay; import tandem.ui.NotificationOverlayComponent; import tandem.ui.Timeline; import tandem.ui.ZoomNavigator; import tandem.ui.ZoomViewport; import tandem.ui.views.StreamView; public class Application extends Sprite { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. */ public function Application() { addEventListener( Event.ADDED_TO_STAGE, addedToStageHandler, false, 0, true ) } //-------------------------------------------------------------------------- // // Class Constants // //-------------------------------------------------------------------------- private const DEFAULT_USER_ADDRESS : String = "gasi" private const DEFAULT_USER_ID : String = "72389028@N00" private const DEFAULT_MINIMUM_ZOOM : Number = 0.25//0.5 private const DEFAULT_MAXIMUM_ZOOM : Number = 180 private const NUM_FARMS:int = 10 //-------------------------------------------------------------------------- // // Children // //-------------------------------------------------------------------------- private var globalNavigation : GlobalNavigation private var memoryIndicator : MemoryIndicator private var notificationOverlay : NotificationOverlay private var keyboardNavigationButton : KeyboardNavigationButton private var timeline : Timeline private var viewport : ZoomViewport private var navigator : ZoomNavigator private var view : DisplayObject private var initialized : Boolean = false //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var model : ApplicationModel = ApplicationModel.getInstance() private var completed : Boolean = false private var numPhotos : int = 363 private var page : int = 1 private var pageSize : int = 500 private var extras : String = "date_taken, original_format" //-------------------------------------------------------------------------- // // Event Handler: Stage // //-------------------------------------------------------------------------- private function addedToStageHandler( event : Event ) : void { // Code in constructor is interpreted by // AVM, therefore move processing-intensive code // outside, so it can be processed by the JIT compiler initialize() } //-------------------------------------------------------------------------- // // Methods: Initialization // //-------------------------------------------------------------------------- private function initialize() : void { stage.align = StageAlign.TOP_LEFT stage.scaleMode = StageScaleMode.NO_SCALE initializeLibraries() initializeSecurity() registerListeners() createChildren() updateDisplayList() model.service = new FlickrService( model.API_KEY ) model.service.addEventListener( FlickrResultEvent.PEOPLE_GET_PUBLIC_PHOTOS, getPublicPhotosHandler ) } private function initializeSecurity() : void { // TODO: Smells bad… =( Security.loadPolicyFile( "http://static.flickr.com/crossdomain.xml" ) for (var i:int = 0; i < NUM_FARMS; i++) { Security.loadPolicyFile("http://farm" + i + ".static.flickr.com/crossdomain.xml") } Security.loadPolicyFile( "http://l.yimg.com/crossdomain.xml" ) } private function initializeLibraries() : void { // Tweener ColorShortcuts.init() } private function registerListeners() : void { stage.addEventListener( Event.RESIZE, resizeHandler ) addEventListener( TandemEvent.APPLICATION_COMPLETE, applicationCompleteHandler ) SWFAddress.addEventListener( SWFAddressEvent.CHANGE, swfAddressChangeHandler ) } //-------------------------------------------------------------------------- // // User Interface // //-------------------------------------------------------------------------- private function createChildren() : void { createTimeline() createGlobalNavigation() createMemoryIndicator() createNotificationOverlay() createKeyboardNavigationButton() } private function createViewport() : void { completed = false model.photos = [] if( view ) removeChild( view ) if( navigator ) removeChild( navigator ) // view initialized = false view = new StreamView() view.alpha = 0 // container viewport = new ZoomViewport() viewport.minZoom = DEFAULT_MINIMUM_ZOOM viewport.maxZoom = DEFAULT_MAXIMUM_ZOOM viewport.content = view // navigator navigator = new ZoomNavigator() navigator.model = viewport navigator.alpha = 0 // add children to display list addChildAt( viewport, 0 ) addChildAt( view, 1 ) addChildAt( navigator, 2 ) // fade in notification overlay Tweener.addTween( notificationOverlay, { alpha: 1, time: 1 } ) // call service model.service.people.getPublicPhotos( model.user.nsid, extras, Math.min( pageSize, numPhotos ), page ) // initial layout updateDisplayList() } private function createTimeline() : void { //timeline = new TimelineComponent() //addChild( timeline ) } private function createGlobalNavigation() : void { globalNavigation = new GlobalNavigationComponent() addChild( globalNavigation ) } private function createMemoryIndicator() : void { memoryIndicator = new MemoryIndicatorComponent() addChild( memoryIndicator ) } private function createNotificationOverlay() : void { notificationOverlay = new NotificationOverlayComponent() notificationOverlay.alpha = 0 addChild( notificationOverlay ) // fade in notification overlay Tweener.addTween( notificationOverlay, { alpha: 1, time: 1.5, delay: 2 } ) } private function createKeyboardNavigationButton() : void { keyboardNavigationButton = new KeyboardNavigationButtonComponent() keyboardNavigationButton.alpha = 0 addChild( keyboardNavigationButton ) Tweener.addTween( keyboardNavigationButton, { alpha: 1, time: 1.5, delay: 1 } ) } //-------------------------------------------------------------------------- // // SWFAdress // //-------------------------------------------------------------------------- private function swfAddressChangeHandler( event : SWFAddressEvent ) : void { var user : String var action : String = SWFAddress.getPathNames()[ 0 ] var flickrNSIDPattern : RegExp = /[0-9]*@N[0-9]*/ if( action == "photos" ) { // Long URL, e.g. http://flickr.com/photos/gasi // or http://flickr.com/photos/72389028@N00 user = SWFAddress.getPathNames()[ 1 ] } else { // Short URL, e.g. http://flickr.com/gasi user = SWFAddress.getPathNames()[ 0 ] } if( user == null ) { // Default user SWFAddress.setValue( "photos/" + DEFAULT_USER_ADDRESS + "/" ) } else if( flickrNSIDPattern.test( user ) ) { // Look up Flickr NSID, e.g. 72389028@N00 model.service.people.getInfo( user ) model.service.addEventListener( FlickrResultEvent.PEOPLE_GET_INFO, getInfoHandler ) } else { // Look up Flickr URL model.service.urls.lookupUser( "http://flickr.com/photos/" + user + "/" ) model.service.addEventListener( FlickrResultEvent.URLS_LOOKUP_USER, lookupUserHandler ) } } //-------------------------------------------------------------------------- // // Event Handlers: Application // //-------------------------------------------------------------------------- private function resizeHandler( event : Event ) : void { updateDisplayList() } private function applicationCompleteHandler( event : Event ) : void { // fade in view Tweener.addTween( view, { alpha: 1, time: 5 } ) // fade in navigator Tweener.addTween( navigator, { alpha: 1, time: 2, delay: 2 } ) // fade out notification Tweener.addTween( notificationOverlay, { alpha: 0, time: 0.8, delay: 1.8 } ) updateDisplayList() } //-------------------------------------------------------------------------- // // Event Handlers: Service // //-------------------------------------------------------------------------- private function getPublicPhotosHandler( event : FlickrResultEvent ) : void { if( event.success ) { var result : PagedPhotoList = PagedPhotoList( event.data.photos ) // add result data to view if( view is StreamView ) { result.photos.forEach( function( item : *, ...ignored ) : void { model.photos.push( item ) StreamView( view ).addItem( item ) } ) } // we're done if( model.photos.length >= Math.min( numPhotos, result.total ) && !completed ) { completed = true } // fetch more data if( result.page < result.pages && !completed ) { page++ model.service.people.getPublicPhotos( model.user.nsid, extras, pageSize, page ) } if( !initialized ) { initialized = true dispatchEvent( new TandemEvent( TandemEvent.APPLICATION_COMPLETE ) ) } } } private function lookupUserHandler( event : FlickrResultEvent ) : void { if( event.success ) { model.user = User( event.data.user ) createViewport() SWFAddress.setTitle( "tandem — " + model.user.username + " (" + model.user.nsid + ")" ) } else { // Default SWFAddress.setValue( "photos/" + DEFAULT_USER_ADDRESS + "/" ) } } private function getInfoHandler( event : FlickrResultEvent ) : void { if( event.success ) { model.user = User( event.data.user ) createViewport() SWFAddress.setTitle( "tandem — " + model.user.username + " (" + model.user.nsid + ")" ) } else { // Default SWFAddress.setValue( "photos/" + DEFAULT_USER_ADDRESS + "/" ) } } //-------------------------------------------------------------------------- // // Methods: Layout // //-------------------------------------------------------------------------- private function updateDisplayList() : void { // Navigation if( globalNavigation ) { globalNavigation.x = 0 globalNavigation.y = 0 } // Viewport if( viewport ) { viewport.x = 0 viewport.y = 0 viewport.width = stage.stageWidth viewport.height = stage.stageHeight } // Navigator if( navigator ) { navigator.x = stage.stageWidth - navigator.width - 12 navigator.y = globalNavigation ? globalNavigation.height + 12 : 12 } // Timeline if( timeline ) { timeline.width = stage.stageWidth timeline.y = stage.stageHeight - timeline.height } // Memory Indicator if( memoryIndicator ) { memoryIndicator.x = stage.stageWidth - memoryIndicator.width - 10 memoryIndicator.y = stage.stageHeight - memoryIndicator.height - 10 } // Notification Overlay if( notificationOverlay ) { notificationOverlay.x = ( stage.stageWidth - notificationOverlay.width ) / 2 notificationOverlay.y = ( stage.stageHeight - notificationOverlay.height ) / 2 } // Keyboard Navigation Button if( keyboardNavigationButton ) { keyboardNavigationButton.x = ( stage.stageWidth - keyboardNavigationButton.width ) / 2 keyboardNavigationButton.y = stage.stageHeight - keyboardNavigationButton.height - 10 } } } }
Add missing type.
Add missing type.
ActionScript
agpl-3.0
openzoom/tandem
2423aa830e95f60483656aea8d3cb4ec088b0e7c
src/org/hola/JSURLStream.as
src/org/hola/JSURLStream.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.hola { import flash.events.*; import flash.external.ExternalInterface; import org.hola.ZExternalInterface; import flash.net.URLRequest; import flash.net.URLStream; import flash.net.URLRequestHeader; import flash.net.URLRequestMethod; import flash.utils.ByteArray; import flash.utils.getTimer; import flash.utils.Timer; import org.hola.ZErr; import org.hola.Base64; import org.hola.WorkerUtils; import org.hola.HEvent; import org.hola.HSettings; public dynamic class JSURLStream extends URLStream { private static var js_api_inited : Boolean = false; private static var req_count : Number = 0; private static var reqs : Object = {}; private var _connected : Boolean; private var _resource : ByteArray = new ByteArray(); private var _curr_data : Object; private var _hola_managed : Boolean = false; private var _req_id : String; private var _self_load : Boolean = false; private var _events : Object; private var _size : Number; public function JSURLStream(){ _hola_managed = HSettings.enabled && ZExternalInterface.avail(); addEventListener(Event.OPEN, onopen); super(); if (!_hola_managed || js_api_inited) return; // Connect calls to JS. ZErr.log('JSURLStream init api'); ExternalInterface.marshallExceptions = true; ExternalInterface.addCallback('hola_onFragmentData', hola_onFragmentData); js_api_inited = true; } protected function _trigger(cb : String, data : Object) : void { if (!_hola_managed && !_self_load) { // XXX arik: need ZErr.throw ZErr.log('invalid trigger'); throw new Error('invalid trigger'); } ExternalInterface.call('window.hola_'+cb, {objectID: ExternalInterface.objectID, data: data}); } override public function get connected() : Boolean { if (!_hola_managed) return super.connected; return _connected; } override public function get bytesAvailable() : uint { if (!_hola_managed) return super.bytesAvailable; return _resource.bytesAvailable; } override public function readByte() : int { if (!_hola_managed) return super.readByte(); return _resource.readByte(); } override public function readUnsignedShort() : uint { if (!_hola_managed) return super.readUnsignedShort(); return _resource.readUnsignedShort(); } override public function readBytes(bytes : ByteArray, offset : uint = 0, length : uint = 0) : void { if (!_hola_managed) return super.readBytes(bytes, offset, length); _resource.readBytes(bytes, offset, length); } override public function close() : void { if (_hola_managed || _self_load) { if (reqs[_req_id]) _trigger('abortFragment', {req_id: _req_id}); WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg); } if (super.connected) super.close(); _connected = false; } override public function load(request : URLRequest) : void { // XXX arik: cleanup previous if hola mode changed _hola_managed = HSettings.enabled && ZExternalInterface.avail(); req_count++; _req_id = 'req'+req_count; if (!_hola_managed) return super.load(request); WorkerUtils.addEventListener(HEvent.WORKER_MESSAGE, onmsg); reqs[_req_id] = this; _resource = new ByteArray(); _trigger('requestFragment', {url: request.url, req_id: _req_id}); this.dispatchEvent(new Event(Event.OPEN)); } private function onopen(e : Event) : void { _connected = true; } private function onerror(e : ErrorEvent) : void { _delete(); if (!_events.error) return; _trigger('onRequestEvent', {req_id: _req_id, event: 'error', error: e.text, text: e.toString()}); } private function onprogress(e : ProgressEvent) : void { _size = e.bytesTotal; if (!_events.progress) return; _trigger('onRequestEvent', {req_id: _req_id, event: 'progress', loaded: e.bytesLoaded, total: e.bytesTotal, text: e.toString()}); } private function onstatus(e : HTTPStatusEvent) : void { if (!_events.status) return; // XXX bahaa: get redirected/responseURL/responseHeaders _trigger('onRequestEvent', {req_id: _req_id, event: 'status', status: e.status, text: e.toString()}); } private function oncomplete(e : Event) : void { _delete(); if (!_events.complete) return; _trigger('onRequestEvent', {req_id: _req_id, event: 'complete', size: _size, text: e.toString()}); } private function decode(str : String) : void { if (!str) return on_decoded_data(null); if (!HSettings.use_worker) return on_decoded_data(Base64.decode_str(str)); var data : ByteArray = new ByteArray(); data.shareable = true; data.writeUTFBytes(str); WorkerUtils.send({cmd: "b64.decode", id: _req_id}); WorkerUtils.send(data); } private function onmsg(e : HEvent) : void { var msg : Object = e.data; if (!_req_id || _req_id!=msg.id || msg.cmd!="b64.decode") return; on_decoded_data(WorkerUtils.recv()); } private function on_decoded_data(data : ByteArray) : void { if (data) { data.position = 0; if (_resource) { var prev : uint = _resource.position; data.readBytes(_resource, _resource.length); _resource.position = prev; } else _resource = data; // XXX arik: get finalLength from js var finalLength : uint = _resource.length; dispatchEvent(new ProgressEvent( ProgressEvent.PROGRESS, false, false, _resource.length, finalLength)); } // XXX arik: dispatch httpStatus/httpResponseStatus if (_curr_data.status) resourceLoadingSuccess(); } private function self_load(o : Object) : void { _self_load = true; _hola_managed = false; _events = o.events||{}; addEventListener(IOErrorEvent.IO_ERROR, onerror); addEventListener(SecurityErrorEvent.SECURITY_ERROR, onerror); addEventListener(ProgressEvent.PROGRESS, onprogress); addEventListener(HTTPStatusEvent.HTTP_STATUS, onstatus); addEventListener(Event.COMPLETE, oncomplete); var req : URLRequest = new URLRequest(o.url); req.method = o.method=="POST" ? URLRequestMethod.POST : URLRequestMethod.GET; // this doesn't seem to work. simply ignored var headers : Object = o.headers||{}; for (var k : String in headers) req.requestHeaders.push(new URLRequestHeader(k, headers[k])); super.load(req); } private function on_fragment_data(o : Object) : void { _curr_data = o; if (o.self_load) return self_load(o); if (o.error) return resourceLoadingError(); decode(o.data); } protected static function hola_onFragmentData(o : Object) : void{ var stream : JSURLStream; try { if (!(stream = reqs[o.req_id])) throw new Error('req_id not found '+o.req_id); stream.on_fragment_data(o); } catch(err : Error){ ZErr.log('Error in hola_onFragmentData', ''+err, ''+err.getStackTrace()); if (stream) stream.resourceLoadingError(); throw err; } } private function _delete() : void { delete reqs[_req_id]; } protected function resourceLoadingError() : void { _delete(); dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR)); } protected function resourceLoadingSuccess() : void { _delete(); dispatchEvent(new Event(Event.COMPLETE)); } } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.hola { import flash.events.*; import flash.external.ExternalInterface; import org.hola.ZExternalInterface; import flash.net.URLRequest; import flash.net.URLStream; import flash.net.URLRequestHeader; import flash.net.URLRequestMethod; import flash.utils.ByteArray; import flash.utils.getTimer; import flash.utils.Timer; import org.hola.ZErr; import org.hola.Base64; import org.hola.WorkerUtils; import org.hola.HEvent; import org.hola.HSettings; public dynamic class JSURLStream extends URLStream { private static var js_api_inited : Boolean = false; private static var req_count : Number = 0; private static var reqs : Object = {}; private var _connected : Boolean; private var _resource : ByteArray = new ByteArray(); private var _curr_data : Object; private var _hola_managed : Boolean = false; private var _req_id : String; private var _self_load : Boolean = false; private var _events : Object; private var _size : Number; public function JSURLStream(){ _hola_managed = HSettings.enabled && ZExternalInterface.avail(); addEventListener(Event.OPEN, onopen); super(); if (!_hola_managed || js_api_inited) return; // Connect calls to JS. ZErr.log('JSURLStream init api'); ExternalInterface.marshallExceptions = true; ExternalInterface.addCallback('hola_onFragmentData', hola_onFragmentData); js_api_inited = true; } protected function _trigger(cb : String, data : Object) : void { if (!_hola_managed && !_self_load) { // XXX arik: need ZErr.throw ZErr.log('invalid trigger'); throw new Error('invalid trigger'); } ExternalInterface.call('window.hola_'+cb, {objectID: ExternalInterface.objectID, data: data}); } override public function get connected() : Boolean { if (!_hola_managed) return super.connected; return _connected; } override public function get bytesAvailable() : uint { if (!_hola_managed) return super.bytesAvailable; return _resource.bytesAvailable; } override public function readByte() : int { if (!_hola_managed) return super.readByte(); return _resource.readByte(); } override public function readUnsignedShort() : uint { if (!_hola_managed) return super.readUnsignedShort(); return _resource.readUnsignedShort(); } override public function readBytes(bytes : ByteArray, offset : uint = 0, length : uint = 0) : void { if (!_hola_managed) return super.readBytes(bytes, offset, length); _resource.readBytes(bytes, offset, length); } override public function close() : void { if (_hola_managed || _self_load) { if (reqs[_req_id]) { delete reqs[_req_id]; _trigger('abortFragment', {req_id: _req_id}); } WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg); } if (super.connected) super.close(); _connected = false; } override public function load(request : URLRequest) : void { if (_hola_managed || _self_load) { if (reqs[_req_id]) { delete reqs[_req_id]; _trigger('abortFragment', {req_id: _req_id}); } WorkerUtils.removeEventListener(HEvent.WORKER_MESSAGE, onmsg); } _hola_managed = HSettings.enabled && ZExternalInterface.avail(); req_count++; _req_id = 'req'+req_count; if (!_hola_managed) return super.load(request); WorkerUtils.addEventListener(HEvent.WORKER_MESSAGE, onmsg); reqs[_req_id] = this; _resource = new ByteArray(); _trigger('requestFragment', {url: request.url, req_id: _req_id}); this.dispatchEvent(new Event(Event.OPEN)); } private function onopen(e : Event) : void { _connected = true; } private function onerror(e : ErrorEvent) : void { _delete(); if (!_events.error) return; _trigger('onRequestEvent', {req_id: _req_id, event: 'error', error: e.text, text: e.toString()}); } private function onprogress(e : ProgressEvent) : void { _size = e.bytesTotal; if (!_events.progress) return; _trigger('onRequestEvent', {req_id: _req_id, event: 'progress', loaded: e.bytesLoaded, total: e.bytesTotal, text: e.toString()}); } private function onstatus(e : HTTPStatusEvent) : void { if (!_events.status) return; // XXX bahaa: get redirected/responseURL/responseHeaders _trigger('onRequestEvent', {req_id: _req_id, event: 'status', status: e.status, text: e.toString()}); } private function oncomplete(e : Event) : void { _delete(); if (!_events.complete) return; _trigger('onRequestEvent', {req_id: _req_id, event: 'complete', size: _size, text: e.toString()}); } private function decode(str : String) : void { if (!str) return on_decoded_data(null); if (!HSettings.use_worker) return on_decoded_data(Base64.decode_str(str)); var data : ByteArray = new ByteArray(); data.shareable = true; data.writeUTFBytes(str); WorkerUtils.send({cmd: "b64.decode", id: _req_id}); WorkerUtils.send(data); } private function onmsg(e : HEvent) : void { var msg : Object = e.data; if (!_req_id || _req_id!=msg.id || msg.cmd!="b64.decode") return; on_decoded_data(WorkerUtils.recv()); } private function on_decoded_data(data : ByteArray) : void { if (data) { data.position = 0; if (_resource) { var prev : uint = _resource.position; data.readBytes(_resource, _resource.length); _resource.position = prev; } else _resource = data; // XXX arik: get finalLength from js var finalLength : uint = _resource.length; dispatchEvent(new ProgressEvent( ProgressEvent.PROGRESS, false, false, _resource.length, finalLength)); } // XXX arik: dispatch httpStatus/httpResponseStatus if (_curr_data.status) resourceLoadingSuccess(); } private function self_load(o : Object) : void { _self_load = true; _hola_managed = false; _events = o.events||{}; addEventListener(IOErrorEvent.IO_ERROR, onerror); addEventListener(SecurityErrorEvent.SECURITY_ERROR, onerror); addEventListener(ProgressEvent.PROGRESS, onprogress); addEventListener(HTTPStatusEvent.HTTP_STATUS, onstatus); addEventListener(Event.COMPLETE, oncomplete); var req : URLRequest = new URLRequest(o.url); req.method = o.method=="POST" ? URLRequestMethod.POST : URLRequestMethod.GET; // this doesn't seem to work. simply ignored var headers : Object = o.headers||{}; for (var k : String in headers) req.requestHeaders.push(new URLRequestHeader(k, headers[k])); super.load(req); } private function on_fragment_data(o : Object) : void { _curr_data = o; if (o.self_load) return self_load(o); if (o.error) return resourceLoadingError(); decode(o.data); } protected static function hola_onFragmentData(o : Object) : void{ var stream : JSURLStream; try { if (!(stream = reqs[o.req_id])) throw new Error('req_id not found '+o.req_id); stream.on_fragment_data(o); } catch(err : Error){ ZErr.log('Error in hola_onFragmentData', ''+err, ''+err.getStackTrace()); if (stream) stream.resourceLoadingError(); throw err; } } private function _delete() : void { delete reqs[_req_id]; } protected function resourceLoadingError() : void { _delete(); dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR)); } protected function resourceLoadingSuccess() : void { _delete(); dispatchEvent(new Event(Event.COMPLETE)); } } }
abort requet on load
abort requet on load
ActionScript
mpl-2.0
hola/flashls,hola/flashls
05cbbd62e0e18ffe9447a02790d5412d33e40c4e
src/TestRunner.as
src/TestRunner.as
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package { import library.ASTUce.Runner; import com.google.analytics.AllTests; import flash.display.Sprite; /* note: Run the Google Analytics unit tests */ [SWF(width="400", height="400", backgroundColor='0xffffff', frameRate='24', pageTitle='testrunner', scriptRecursionLimit='1000', scriptTimeLimit='60')] [ExcludeClass] public class TestRunner extends Sprite { public function TestRunner() { Runner.main( com.google.analytics.AllTests.suite( ) ); } } }
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package { import library.ASTUce.Runner; import com.google.analytics.AllTests; import flash.display.Sprite; /* note: Run the Google Analytics unit tests */ [SWF(width="400", height="400", backgroundColor='0xffffff', frameRate='24', pageTitle='testrunner', scriptRecursionLimit='1000', scriptTimeLimit='60')] [ExcludeClass] public class TestRunner extends Sprite { public function TestRunner() { Runner.main( com.google.analytics.AllTests.suite( ) ); } } }
update comment
update comment
ActionScript
apache-2.0
mrthuanvn/gaforflash,Vigmar/gaforflash,DimaBaliakin/gaforflash,Miyaru/gaforflash,drflash/gaforflash,Miyaru/gaforflash,soumavachakraborty/gaforflash,mrthuanvn/gaforflash,jeremy-wischusen/gaforflash,jeremy-wischusen/gaforflash,drflash/gaforflash,dli-iclinic/gaforflash,soumavachakraborty/gaforflash,dli-iclinic/gaforflash,jisobkim/gaforflash,DimaBaliakin/gaforflash,Vigmar/gaforflash,jisobkim/gaforflash
ee920f18c9f25555b4e401f2e669f3a393134363
as3/com/netease/protobuf/ReadUtils.as
as3/com/netease/protobuf/ReadUtils.as
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // Copyright (c) 2012 , Yang Bo. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.errors.* import flash.utils.* /** * @private */ public final class ReadUtils { public static function skip(input:IDataInput, wireType:uint):void { switch (wireType) { case WireType.VARINT: while (input.readUnsignedByte() > 0x80) {} break case WireType.FIXED_64_BIT: input.readInt() input.readInt() break case WireType.LENGTH_DELIMITED: for (var i:uint = read$TYPE_UINT32(input); i != 0; i--) { input.readByte() } break case WireType.FIXED_32_BIT: input.readInt() break default: throw new IOError("Invalid wire type: " + wireType) } } public static function read$TYPE_DOUBLE(input:IDataInput):Number { return input.readDouble() } public static function read$TYPE_FLOAT(input:IDataInput):Number { return input.readFloat() } public static function read$TYPE_INT64(input:IDataInput):Int64 { const result:Int64 = new Int64 var b:uint var i:uint = 0 for (;; i += 7) { b = input.readUnsignedByte() if (i == 28) { break } else { if (b >= 0x80) { result.low |= ((b & 0x7f) << i) } else { result.low |= (b << i) return result } } } if (b >= 0x80) { b &= 0x7f result.low |= (b << i) result.high = b >>> 4 } else { result.low |= (b << i) result.high = b >>> 4 return result } for (i = 3;; i += 7) { b = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result.high |= ((b & 0x7f) << i) } else { result.high |= (b << i) break } } } return result } public static function read$TYPE_UINT64(input:IDataInput):UInt64 { const result:UInt64 = new UInt64 var b:uint var i:uint = 0 for (;; i += 7) { b = input.readUnsignedByte() if (i == 28) { break } else { if (b >= 0x80) { result.low |= ((b & 0x7f) << i) } else { result.low |= (b << i) return result } } } if (b >= 0x80) { b &= 0x7f result.low |= (b << i) result.high = b >>> 4 } else { result.low |= (b << i) result.high = b >>> 4 return result } for (i = 3;; i += 7) { b = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result.high |= ((b & 0x7f) << i) } else { result.high |= (b << i) break } } } return result } public static function read$TYPE_INT32(input:IDataInput):int { return int(read$TYPE_UINT32(input)) } public static function read$TYPE_FIXED64(input:IDataInput):UInt64 { const result:UInt64 = new UInt64 result.low = input.readUnsignedInt() result.high = input.readUnsignedInt() return result } public static function read$TYPE_FIXED32(input:IDataInput):uint { return input.readUnsignedInt() } public static function read$TYPE_BOOL(input:IDataInput):Boolean { return read$TYPE_UINT32(input) != 0 } public static function read$TYPE_STRING(input:IDataInput):String { const length:uint = read$TYPE_UINT32(input) return input.readUTFBytes(length) } public static function read$TYPE_BYTES(input:IDataInput):ByteArray { const result:ByteArray = new ByteArray const length:uint = read$TYPE_UINT32(input) if (length > 0) { input.readBytes(result, 0, length) } return result } public static function read$TYPE_UINT32(input:IDataInput):uint { var result:uint = 0 for (var i:uint = 0;; i += 7) { const b:uint = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result |= ((b & 0x7f) << i) } else { result |= (b << i) break } } else { while (input.readUnsignedByte() >= 0x80) {} break } } return result } public static function read$TYPE_ENUM(input:IDataInput):int { return read$TYPE_INT32(input) } public static function read$TYPE_SFIXED32(input:IDataInput):int { return input.readInt() } public static function read$TYPE_SFIXED64(input:IDataInput):Int64 { const result:Int64 = new Int64 result.low = input.readUnsignedInt() result.high = input.readInt() return result } public static function read$TYPE_SINT32(input:IDataInput):int { return ZigZag.decode32(read$TYPE_UINT32(input)) } public static function read$TYPE_SINT64(input:IDataInput):Int64 { const result:Int64 = read$TYPE_INT64(input) const low:uint = result.low const high:uint = result.high result.low = ZigZag.decode64low(low, high) result.high = ZigZag.decode64high(low, high) return result } public static function read$TYPE_MESSAGE(input:IDataInput, message:Message):Message { const length:uint = read$TYPE_UINT32(input) if (input.bytesAvailable < length) { throw new IOError("Invalid message length: " + length) } const bytesAfterSlice:uint = input.bytesAvailable - length message.used_by_generated_code::readFromSlice(input, bytesAfterSlice) if (input.bytesAvailable != bytesAfterSlice) { throw new IOError("Invalid nested message") } return message } public static function readPackedRepeated(input:IDataInput, readFuntion:Function, value:Array):void { const length:uint = read$TYPE_UINT32(input) if (input.bytesAvailable < length) { throw new IOError("Invalid message length: " + length) } const bytesAfterSlice:uint = input.bytesAvailable - length while (input.bytesAvailable > bytesAfterSlice) { value.push(readFuntion(input)) } if (input.bytesAvailable != bytesAfterSlice) { throw new IOError("Invalid packed repeated data") } } } }
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // Copyright (c) 2012 , Yang Bo. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.errors.* import flash.utils.* /** * @private */ public final class ReadUtils { public static function skip(input:IDataInput, wireType:uint):void { switch (wireType) { case WireType.VARINT: while (input.readUnsignedByte() >= 0x80) {} break case WireType.FIXED_64_BIT: input.readInt() input.readInt() break case WireType.LENGTH_DELIMITED: for (var i:uint = read$TYPE_UINT32(input); i != 0; i--) { input.readByte() } break case WireType.FIXED_32_BIT: input.readInt() break default: throw new IOError("Invalid wire type: " + wireType) } } public static function read$TYPE_DOUBLE(input:IDataInput):Number { return input.readDouble() } public static function read$TYPE_FLOAT(input:IDataInput):Number { return input.readFloat() } public static function read$TYPE_INT64(input:IDataInput):Int64 { const result:Int64 = new Int64 var b:uint var i:uint = 0 for (;; i += 7) { b = input.readUnsignedByte() if (i == 28) { break } else { if (b >= 0x80) { result.low |= ((b & 0x7f) << i) } else { result.low |= (b << i) return result } } } if (b >= 0x80) { b &= 0x7f result.low |= (b << i) result.high = b >>> 4 } else { result.low |= (b << i) result.high = b >>> 4 return result } for (i = 3;; i += 7) { b = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result.high |= ((b & 0x7f) << i) } else { result.high |= (b << i) break } } } return result } public static function read$TYPE_UINT64(input:IDataInput):UInt64 { const result:UInt64 = new UInt64 var b:uint var i:uint = 0 for (;; i += 7) { b = input.readUnsignedByte() if (i == 28) { break } else { if (b >= 0x80) { result.low |= ((b & 0x7f) << i) } else { result.low |= (b << i) return result } } } if (b >= 0x80) { b &= 0x7f result.low |= (b << i) result.high = b >>> 4 } else { result.low |= (b << i) result.high = b >>> 4 return result } for (i = 3;; i += 7) { b = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result.high |= ((b & 0x7f) << i) } else { result.high |= (b << i) break } } } return result } public static function read$TYPE_INT32(input:IDataInput):int { return int(read$TYPE_UINT32(input)) } public static function read$TYPE_FIXED64(input:IDataInput):UInt64 { const result:UInt64 = new UInt64 result.low = input.readUnsignedInt() result.high = input.readUnsignedInt() return result } public static function read$TYPE_FIXED32(input:IDataInput):uint { return input.readUnsignedInt() } public static function read$TYPE_BOOL(input:IDataInput):Boolean { return read$TYPE_UINT32(input) != 0 } public static function read$TYPE_STRING(input:IDataInput):String { const length:uint = read$TYPE_UINT32(input) return input.readUTFBytes(length) } public static function read$TYPE_BYTES(input:IDataInput):ByteArray { const result:ByteArray = new ByteArray const length:uint = read$TYPE_UINT32(input) if (length > 0) { input.readBytes(result, 0, length) } return result } public static function read$TYPE_UINT32(input:IDataInput):uint { var result:uint = 0 for (var i:uint = 0;; i += 7) { const b:uint = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result |= ((b & 0x7f) << i) } else { result |= (b << i) break } } else { while (input.readUnsignedByte() >= 0x80) {} break } } return result } public static function read$TYPE_ENUM(input:IDataInput):int { return read$TYPE_INT32(input) } public static function read$TYPE_SFIXED32(input:IDataInput):int { return input.readInt() } public static function read$TYPE_SFIXED64(input:IDataInput):Int64 { const result:Int64 = new Int64 result.low = input.readUnsignedInt() result.high = input.readInt() return result } public static function read$TYPE_SINT32(input:IDataInput):int { return ZigZag.decode32(read$TYPE_UINT32(input)) } public static function read$TYPE_SINT64(input:IDataInput):Int64 { const result:Int64 = read$TYPE_INT64(input) const low:uint = result.low const high:uint = result.high result.low = ZigZag.decode64low(low, high) result.high = ZigZag.decode64high(low, high) return result } public static function read$TYPE_MESSAGE(input:IDataInput, message:Message):Message { const length:uint = read$TYPE_UINT32(input) if (input.bytesAvailable < length) { throw new IOError("Invalid message length: " + length) } const bytesAfterSlice:uint = input.bytesAvailable - length message.used_by_generated_code::readFromSlice(input, bytesAfterSlice) if (input.bytesAvailable != bytesAfterSlice) { throw new IOError("Invalid nested message") } return message } public static function readPackedRepeated(input:IDataInput, readFuntion:Function, value:Array):void { const length:uint = read$TYPE_UINT32(input) if (input.bytesAvailable < length) { throw new IOError("Invalid message length: " + length) } const bytesAfterSlice:uint = input.bytesAvailable - length while (input.bytesAvailable > bytesAfterSlice) { value.push(readFuntion(input)) } if (input.bytesAvailable != bytesAfterSlice) { throw new IOError("Invalid packed repeated data") } } } }
Fix #35
Fix #35
ActionScript
bsd-2-clause
tavenzhang/protoc-gen-as3,Atry/protoc-gen-as3,bennysuh/protoc-gen-as3,mustang2247/protoc-gen-as3,qykings/protoc-gen-as3,wiln/protoc-gen-as3,polar1225/protoc-gen-as3,zhuqiuping/protoc-gen-as3,terrynoya/terrynoya-protoc-gen-as3,bypp/protoc-gen-as3,lzw216/protoc-gen-as3,cui-liqiang/protoc-gen-as3,airsiao/protoc-gen-as3
c7925b37dfeb039c4e64009481003695bd1c47d0
src/com/merlinds/miracle_tool/viewer/ViewerView.as
src/com/merlinds/miracle_tool/viewer/ViewerView.as
/** * User: MerlinDS * Date: 18.07.2014 * Time: 17:42 */ package com.merlinds.miracle_tool.viewer { import com.bit101.components.List; import com.bit101.components.Window; import com.merlinds.debug.log; import com.merlinds.miracle.Miracle; import com.merlinds.miracle.animations.Animation; import com.merlinds.miracle.display.MiracleImage; import com.merlinds.miracle.utils.Asset; import com.merlinds.miracle.utils.MafReader; import com.merlinds.miracle_tool.models.AppModel; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; [SWF(backgroundColor="0x333333", frameRate=60)] public class ViewerView extends Sprite { private var _model:AppModel; private var _assets:Vector.<Asset>; private var _window:Window; private var _name:String; public function ViewerView(model:AppModel = null) { super(); _model = model; if(_model == null){ _model = new AppModel(); } this.addEventListener(Event.ADDED_TO_STAGE, this.initialize); } //============================================================================== //{region PUBLIC METHODS //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS private function initialize(event:Event):void { this.removeEventListener(event.type, this.initialize); this.stage.scaleMode = StageScaleMode.NO_SCALE; this.stage.align = StageAlign.TOP_LEFT; Miracle.start(this.stage, this.createHandler, true); } private function choseAnimation():void { //find animation asset and add all of animations to chose list var n:int = _assets.length; for(var i:int = 0; i < n; i++){ var asset:Asset = _assets[i]; if(asset.type == Asset.TIMELINE_TYPE){ //parse output _window = new Window(this, 0, 0, "Chose mesh"); var list:List = new List(_window, 0, 0, this.getAnimations(asset.output)); _window.x = this.stage.stageWidth - _window.width; list.addEventListener(Event.SELECT, this.selectAnimationHandler); } } } [Inline] private function getAnimations(bytes:ByteArray):Array { var result:Array = []; var reader:MafReader = new MafReader(); reader.execute(bytes); var animations:Vector.<Animation> = reader.animations; for each(var animation:Animation in animations){ result.push(animation.name); } return result; } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS private function createHandler(animation:Boolean = false):void { //TODO: Show view if it exit if(animation || _model.viewerInput == null){ _model.viewerInput = _model.lastFileDirection; _model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler); _model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite" + "file that you want to view"); } } private function selectFileHandler(event:Event):void { _model.viewerInput.removeEventListener(event.type, this.selectFileHandler); _model.lastFileDirection = _model.viewerInput.parent; var byteArray:ByteArray = new ByteArray(); var stream:FileStream = new FileStream(); stream.open(_model.viewerInput, FileMode.READ); stream.readBytes(byteArray); stream.close(); //parse if(_assets == null)_assets = new <Asset>[]; var asset:Asset = new Asset(_model.viewerInput.name, byteArray); if(asset.type == Asset.TIMELINE_TYPE){ _name = asset.name; } _assets.push(asset); // var name:String = asset.name; if(_assets.length > 1){ this.choseAnimation(); Miracle.createScene(_assets, 1); Miracle.currentScene.createImage(_name) .addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage); Miracle.resume(); }else{ this.createHandler(true); } } private function selectAnimationHandler(event:Event):void { var list:List = event.target as List; //add animation to miracle var name:String = list.selectedItem.toString(); log(this, "selectAnimationHandler", name); } private function imageAddedToStage(event:Event):void { var target:MiracleImage = event.target as MiracleImage; target.moveTO( this.stage.stageWidth - target.width >> 1, this.stage.stageHeight - target.height >> 1 ); } //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS //} endregion GETTERS/SETTERS ================================================== } }
/** * User: MerlinDS * Date: 18.07.2014 * Time: 17:42 */ package com.merlinds.miracle_tool.viewer { import com.bit101.components.List; import com.bit101.components.Window; import com.merlinds.debug.log; import com.merlinds.miracle.Miracle; import com.merlinds.miracle.animations.Animation; import com.merlinds.miracle.display.MiracleDisplayObject; import com.merlinds.miracle.display.MiracleImage; import com.merlinds.miracle.utils.Asset; import com.merlinds.miracle.utils.MafReader; import com.merlinds.miracle_tool.models.AppModel; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; [SWF(backgroundColor="0x333333", frameRate=60)] public class ViewerView extends Sprite { private var _model:AppModel; private var _assets:Vector.<Asset>; private var _window:Window; private var _name:String; public function ViewerView(model:AppModel = null) { super(); _model = model; if(_model == null){ _model = new AppModel(); } this.addEventListener(Event.ADDED_TO_STAGE, this.initialize); } //============================================================================== //{region PUBLIC METHODS //} endregion PUBLIC METHODS =================================================== //============================================================================== //{region PRIVATE\PROTECTED METHODS private function initialize(event:Event):void { this.removeEventListener(event.type, this.initialize); this.stage.scaleMode = StageScaleMode.NO_SCALE; this.stage.align = StageAlign.TOP_LEFT; Miracle.start(this.stage, this.createHandler, true); } private function choseAnimation():void { //find animation asset and add all of animations to chose list var n:int = _assets.length; for(var i:int = 0; i < n; i++){ var asset:Asset = _assets[i]; if(asset.type == Asset.TIMELINE_TYPE){ //parse output _window = new Window(this, 0, 0, "Chose mesh"); var list:List = new List(_window, 0, 0, this.getAnimations(asset.output)); _window.x = this.stage.stageWidth - _window.width; list.addEventListener(Event.SELECT, this.selectAnimationHandler); } } } [Inline] private function getAnimations(bytes:ByteArray):Array { var result:Array = []; var reader:MafReader = new MafReader(); reader.execute(bytes); var animations:Vector.<Animation> = reader.animations; for each(var animation:Animation in animations){ result.push(animation.name); } return result; } //} endregion PRIVATE\PROTECTED METHODS ======================================== //============================================================================== //{region EVENTS HANDLERS private function createHandler(animation:Boolean = false):void { //TODO: Show view if it exit if(animation || _model.viewerInput == null){ _model.viewerInput = _model.lastFileDirection; _model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler); _model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite" + "file that you want to view"); } } private function selectFileHandler(event:Event):void { _model.viewerInput.removeEventListener(event.type, this.selectFileHandler); _model.lastFileDirection = _model.viewerInput.parent; var byteArray:ByteArray = new ByteArray(); var stream:FileStream = new FileStream(); stream.open(_model.viewerInput, FileMode.READ); stream.readBytes(byteArray); stream.close(); //parse if(_assets == null)_assets = new <Asset>[]; var asset:Asset = new Asset(_model.viewerInput.name, byteArray); if(asset.type == Asset.TIMELINE_TYPE){ _name = asset.name; } _assets.push(asset); // var name:String = asset.name; if(_assets.length > 1){ this.choseAnimation(); Miracle.createScene(_assets, 1); Miracle.resume(); }else{ this.createHandler(true); } } private function selectAnimationHandler(event:Event):void { var list:List = event.target as List; //add animation to miracle var animation:String = list.selectedItem.toString(); log(this, "selectAnimationHandler", animation); Miracle.currentScene.createAnimation(_name, animation) .addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage); } private function imageAddedToStage(event:Event):void { var target:MiracleDisplayObject = event.target as MiracleDisplayObject; target.moveTO( this.stage.stageWidth - target.width >> 1, this.stage.stageHeight - target.height >> 1 ); } //} endregion EVENTS HANDLERS ================================================== //============================================================================== //{region GETTERS/SETTERS //} endregion GETTERS/SETTERS ================================================== } }
Add animation instance and fix viewer for this
Add animation instance and fix viewer for this
ActionScript
mit
MerlinDS/miracle_tool
26f88a1adc0bf5ef50a2f8da6d044c5c25d2cf80
HLSPlugin/src/com/kaltura/hls/m2ts/NALUProcessor.as
HLSPlugin/src/com/kaltura/hls/m2ts/NALUProcessor.as
package com.kaltura.hls.m2ts { import flash.utils.ByteArray; import flash.net.ObjectEncoding; import flash.utils.ByteArray; import flash.utils.Endian; import flash.utils.IDataInput; import flash.utils.IDataOutput; /** * NALU processing utilities. */ public class NALUProcessor { private static var ppsList:Vector.<ByteArray> = new Vector.<ByteArray>; private static var spsList:Vector.<ByteArray> = new Vector.<ByteArray>; private static function sortSPS(a:ByteArray, b:ByteArray):int { var ourEg:ExpGolomb = new ExpGolomb(a); ourEg.readBits(28); var Id_a:int = ourEg.readUE(); ourEg = new ExpGolomb(b); ourEg.readBits(28); var Id_b:int = ourEg.readUE(); return Id_a - Id_b; } private static function sortPPS(a:ByteArray, b:ByteArray):int { var ourEg:ExpGolomb = new ExpGolomb(a); ourEg.readBits(8); var Id_a:int = ourEg.readUE(); ourEg = new ExpGolomb(b); ourEg.readBits(8); var Id_b:int = ourEg.readUE(); return Id_a - Id_b; } /** * Actually perform serialization of the AVCC. */ private static function serializeAVCC():ByteArray { // Some sanity checking, easier than special casing loops. if(ppsList == null) ppsList = new Vector.<ByteArray>(); if(spsList == null) spsList = new Vector.<ByteArray>(); if(ppsList.length == 0 || spsList.length == 0) return null; var avcc:ByteArray = new ByteArray(); var cursor:uint = 0; avcc[cursor++] = 0x00; // stream ID avcc[cursor++] = 0x00; avcc[cursor++] = 0x00; avcc[cursor++] = 0x01; // version avcc[cursor++] = spsList[0][1]; // profile avcc[cursor++] = spsList[0][2]; // compatiblity avcc[cursor++] = spsList[0][3]; // level avcc[cursor++] = 0xFC | 3; // nalu marker length size - 1, we're using 4 byte ints. avcc[cursor++] = 0xE0 | spsList.length; // reserved bit + SPS count spsList.sort(sortSPS); for(var i:int=0; i<spsList.length; i++) { // Debug dump the SPS var spsLength:uint = spsList[i].length; //trace("SPS #" + i + " profile " + spsList[i][1] + " " + Hex.fromArray(spsList[i], true)); var eg:ExpGolomb = new ExpGolomb(spsList[i]); // constraint_set[0-5]_flag, u(1), reserved_zero_2bits u(2), level_idc u(8) eg.readBits(16); //trace("Saw id " + eg.readUE()); avcc.position = cursor; spsList[i].position = 0; avcc.writeShort(spsLength); avcc.writeBytes(spsList[i], 0, spsLength); cursor += spsLength + 2; } avcc[cursor++] = ppsList.length; // PPS count. ppsList.sort(sortPPS); for(i=0; i<ppsList.length; i++) { var ppsLength:uint = ppsList[i].length; //trace("PPS length #" + i + " is " + ppsLength + " " + Hex.fromArray(ppsList[i], true)); avcc.position = cursor; ppsList[i].position = 0; avcc.writeShort(ppsLength); avcc.writeBytes(ppsList[i], 0, ppsLength); cursor += ppsLength + 2; } return avcc; } /** * Update our internal list of SPS entries, merging as needed. */ private static function setAVCSPS(bytes:ByteArray, cursor:uint, length:uint):void { var sps:ByteArray = new ByteArray(); sps.writeBytes(bytes, cursor, length); var ourEg:ExpGolomb = new ExpGolomb(sps); ourEg.readBits(16); var ourId:int = ourEg.readUE(); // If not present in list add it! var found:Boolean = false; for(var i:int=0; i<spsList.length; i++) { // If it matches our ID, replace it. var eg:ExpGolomb = new ExpGolomb(spsList[i]); eg.readBits(16); var foundId:int = eg.readUE(); if(foundId == ourId) { //trace("Got SPS match for " + foundId + "!"); spsList[i] = sps; return; } if(spsList[i].length != length) continue; // If identical don't append to list. for(var j:int=0; j<spsList[i].length && j<sps.length; j++) if(spsList[i][j] != sps[j]) continue; found = true; break; } // Maybe we do have to add it! if(!found) spsList.push(sps); } /** * Update our internal list of PPS entries, merging as needed. */ private static function setAVCPPS(bytes:ByteArray, cursor:uint, length:uint):void { var pps:ByteArray = new ByteArray; pps.writeBytes(bytes, cursor, length); var ourEg:ExpGolomb = new ExpGolomb(pps); var ourId:int = ourEg.readUE(); // If not present in list add it! var found:Boolean = false; for(var i:int=0; i<ppsList.length; i++) { // If it matches our ID, replace it. var eg:ExpGolomb = new ExpGolomb(ppsList[i]); var foundId:int = eg.readUE(); if(foundId == ourId) { //trace("Got PPS match for " + foundId + "!"); ppsList[i] = pps; return; } if(ppsList[i].length != length) continue; // If identical don't append to list. for(var j:int=0; j<ppsList[i].length && j<pps.length; j++) if(ppsList[i][j] != pps[j]) continue; found = true; break; } // Maybe we do have to add it! if(!found) ppsList.push(pps); } /** * Given a buffer containing NALUs, walk through them and call callback * with the extends of each. It's given in order the buffer, start, and * length of each found NALU. */ public static function walkNALUs(bytes:ByteArray, cursor:int, callback:Function, flushing:Boolean = false):void { var originalStart:int = int(cursor); var start:int = int(cursor); var end:int; var naluLength:uint; start = NALU.scan(bytes, start, false); while(start >= 0) { end = NALU.scan(bytes, start, true); if(end >= 0) { naluLength = end - start; } else if(flushing) { naluLength = bytes.length - start; } else { break; } callback(bytes, uint(start), naluLength); cursor = start + naluLength; start = NALU.scan(bytes, cursor, false); } } /** * NALUs use 0x000001 to indicate start codes. However, data may need * to contain this code. In this case an 0x03 is inserted to break up * the start code pattern. This function strips such bytes. */ public static function stripEmulationBytes(buffer:ByteArray, cursor:uint, length:uint):ByteArray { var tmp:ByteArray = new ByteArray(); for(var i:int=cursor; i<cursor+length; i++) { if(buffer[i] == 0x03 && (i-cursor) >= 3) { if(buffer[i-1] == 0x00 && buffer[i-2] == 0x00) { //trace("SKIPPING EMULATION BYTE @ " + i); continue; } } tmp.writeByte(buffer[i]); } return tmp; } private static function extractAVCCInner(bytes:ByteArray, cursor:uint, length:uint):void { // If we need to piggyback a callback, do it now. if(activeCallback != null) activeCallback(bytes, cursor, length); // What's the type? var naluType:uint = bytes[cursor] & 0x1f; if(naluType == 7) { // Handle SPS var spsStripped:ByteArray = stripEmulationBytes(bytes, cursor, length); setAVCSPS(spsStripped, 0, spsStripped.length) } else if(naluType == 8) { // Handle PPS var ppsStripped:ByteArray = stripEmulationBytes(bytes, cursor, length); setAVCPPS(ppsStripped, 0, ppsStripped.length) } } private static var activeCallback:Function = null; public static function startAVCCExtraction():void { spsList = new Vector.<ByteArray>(); ppsList = new Vector.<ByteArray>(); } public static function pushAVCData(unit:NALU):void { // Go through each buffer and find all the SPS/PPS info. activeCallback = null; walkNALUs(unit.buffer, 0, extractAVCCInner, true) } /** * Scan a set of NALUs and come up with an AVCC record. */ public static function extractAVCC(unit:NALU, perNaluCallback:Function):ByteArray { // Go through each buffer and find all the SPS/PPS info. if(unit) { activeCallback = perNaluCallback; walkNALUs(unit.buffer, 0, extractAVCCInner, true) activeCallback = null; } // Generate and return the AVCC. return serializeAVCC(); } } }
package com.kaltura.hls.m2ts { import flash.utils.ByteArray; import flash.net.ObjectEncoding; import flash.utils.ByteArray; import flash.utils.Endian; import flash.utils.IDataInput; import flash.utils.IDataOutput; //import com.hurlant.util.Hex; /** * NALU processing utilities. */ public class NALUProcessor { private static var ppsList:Vector.<ByteArray> = new Vector.<ByteArray>; private static var spsList:Vector.<ByteArray> = new Vector.<ByteArray>; private static function sortSPS(a:ByteArray, b:ByteArray):int { var ourEg:ExpGolomb = new ExpGolomb(a); ourEg.readBits(8); ourEg.readBits(24); var Id_a:int = ourEg.readUE(); ourEg = new ExpGolomb(b); ourEg.readBits(8); ourEg.readBits(24); var Id_b:int = ourEg.readUE(); return Id_a - Id_b; } private static function sortPPS(a:ByteArray, b:ByteArray):int { var ourEg:ExpGolomb = new ExpGolomb(a); ourEg.readBits(8); var Id_a:int = ourEg.readUE(); ourEg = new ExpGolomb(b); ourEg.readBits(8); var Id_b:int = ourEg.readUE(); return Id_a - Id_b; } /** * Actually perform serialization of the AVCC. */ private static function serializeAVCC():ByteArray { // Some sanity checking, easier than special casing loops. if(ppsList == null) ppsList = new Vector.<ByteArray>(); if(spsList == null) spsList = new Vector.<ByteArray>(); if(ppsList.length == 0 || spsList.length == 0) return null; var avcc:ByteArray = new ByteArray(); var cursor:uint = 0; avcc[cursor++] = 0x00; // stream ID avcc[cursor++] = 0x00; avcc[cursor++] = 0x00; avcc[cursor++] = 0x01; // version avcc[cursor++] = spsList[0][1]; // profile avcc[cursor++] = spsList[0][2]; // compatiblity avcc[cursor++] = spsList[0][3]; // level avcc[cursor++] = 0xFC | 3; // nalu marker length size - 1, we're using 4 byte ints. avcc[cursor++] = 0xE0 | spsList.length; // reserved bit + SPS count spsList.sort(sortSPS); for(var i:int=0; i<spsList.length; i++) { // Debug dump the SPS var spsLength:uint = spsList[i].length; //trace("SPS #" + i + " profile=" + spsList[i][1] + " " + Hex.fromArray(spsList[i], true)); var eg:ExpGolomb = new ExpGolomb(spsList[i]); // constraint_set[0-5]_flag, u(1), reserved_zero_2bits u(2), level_idc u(8) eg.readBits(8); eg.readBits(24); //trace("Saw id " + eg.readUE()); avcc.position = cursor; spsList[i].position = 0; avcc.writeShort(spsLength); avcc.writeBytes(spsList[i], 0, spsLength); cursor += spsLength + 2; } avcc[cursor++] = ppsList.length; // PPS count. ppsList.sort(sortPPS); for(i=0; i<ppsList.length; i++) { var ppsLength:uint = ppsList[i].length; //trace("PPS length #" + i + " is " + ppsLength + " " + Hex.fromArray(ppsList[i], true)); eg = new ExpGolomb(ppsList[i]); // constraint_set[0-5]_flag, u(1), reserved_zero_2bits u(2), level_idc u(8) eg.readBits(8); //trace("Saw id " + eg.readUE()); avcc.position = cursor; ppsList[i].position = 0; avcc.writeShort(ppsLength); avcc.writeBytes(ppsList[i], 0, ppsLength); cursor += ppsLength + 2; } return avcc; } /** * Update our internal list of SPS entries, merging as needed. */ private static function setAVCSPS(bytes:ByteArray, cursor:uint, length:uint):void { var sps:ByteArray = new ByteArray(); sps.writeBytes(bytes, cursor, length); var ourEg:ExpGolomb = new ExpGolomb(sps); ourEg.readBits(8); ourEg.readBits(24); var ourId:int = ourEg.readUE(); // If not present in list add it! for(var i:int=0; i<spsList.length; i++) { // If it matches our ID, replace it. var eg:ExpGolomb = new ExpGolomb(spsList[i]); eg.readBits(8); eg.readBits(24); var foundId:int = eg.readUE(); if(foundId != ourId) continue; //trace("Got SPS match for " + foundId + "!"); spsList[i] = sps; return; } // Maybe we do have to add it! spsList.push(sps); } /** * Update our internal list of PPS entries, merging as needed. */ private static function setAVCPPS(bytes:ByteArray, cursor:uint, length:uint):void { var pps:ByteArray = new ByteArray; pps.writeBytes(bytes, cursor, length); var ourEg:ExpGolomb = new ExpGolomb(pps); ourEg.readBits(8); var ourId:int = ourEg.readUE(); // If not present in list add it! for(var i:int=0; i<ppsList.length; i++) { // If it matches our ID, replace it. var eg:ExpGolomb = new ExpGolomb(ppsList[i]); eg.readBits(8); var foundId:int = eg.readUE(); if(foundId != ourId) continue; //trace("Got PPS match for " + foundId + "!"); ppsList[i] = pps; return; } // Maybe we do have to add it! ppsList.push(pps); } /** * Given a buffer containing NALUs, walk through them and call callback * with the extends of each. It's given in order the buffer, start, and * length of each found NALU. */ public static function walkNALUs(bytes:ByteArray, cursor:int, callback:Function, flushing:Boolean = false):void { var originalStart:int = int(cursor); var start:int = int(cursor); var end:int; var naluLength:uint; start = NALU.scan(bytes, start, false); while(start >= 0) { end = NALU.scan(bytes, start, true); if(end >= 0) { naluLength = end - start; } else if(flushing) { naluLength = bytes.length - start; } else { break; } callback(bytes, uint(start), naluLength); cursor = start + naluLength; start = NALU.scan(bytes, cursor, false); } } /** * NALUs use 0x000001 to indicate start codes. However, data may need * to contain this code. In this case an 0x03 is inserted to break up * the start code pattern. This function strips such bytes. */ public static function stripEmulationBytes(buffer:ByteArray, cursor:uint, length:uint):ByteArray { var tmp:ByteArray = new ByteArray(); for(var i:int=cursor; i<cursor+length; i++) { if(buffer[i] == 0x03 && (i-cursor) >= 3) { if(buffer[i-1] == 0x00 && buffer[i-2] == 0x00) { //trace("SKIPPING EMULATION BYTE @ " + i); continue; } } tmp.writeByte(buffer[i]); } return tmp; } private static function extractAVCCInner(bytes:ByteArray, cursor:uint, length:uint):void { // If we need to piggyback a callback, do it now. if(activeCallback != null) activeCallback(bytes, cursor, length); // What's the type? var naluType:uint = bytes[cursor] & 0x1f; if(naluType == 7) { // Handle SPS var spsStripped:ByteArray = stripEmulationBytes(bytes, cursor, length); setAVCSPS(spsStripped, 0, spsStripped.length) } else if(naluType == 8) { // Handle PPS var ppsStripped:ByteArray = stripEmulationBytes(bytes, cursor, length); setAVCPPS(ppsStripped, 0, ppsStripped.length) } } private static var activeCallback:Function = null; public static function startAVCCExtraction():void { spsList = new Vector.<ByteArray>(); ppsList = new Vector.<ByteArray>(); } public static function pushAVCData(unit:NALU):void { // Go through each buffer and find all the SPS/PPS info. activeCallback = null; walkNALUs(unit.buffer, 0, extractAVCCInner, true) } /** * Scan a set of NALUs and come up with an AVCC record. */ public static function extractAVCC(unit:NALU, perNaluCallback:Function):ByteArray { // Go through each buffer and find all the SPS/PPS info. if(unit) { activeCallback = perNaluCallback; walkNALUs(unit.buffer, 0, extractAVCCInner, true) activeCallback = null; } // Generate and return the AVCC. return serializeAVCC(); } } }
Fix SPS/PPS parsing.
Fix SPS/PPS parsing.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
d980e07950e7d0720259a5e0f295198d5cc84c31
com/segonquart/menuColourIdiomes.as
com/segonquart/menuColourIdiomes.as
import mx.transitions.easing.*; import com.mosesSupposes.fuse.*; class menuColouridiomes extends MovieClip { public var cat, es, en ,fr:MovieClip; public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr"); function menuColourIdiomes ():Void { this.onRollOver = this.mOver; this.onRollOut = this.mOut; this.onRelease =this.mOver; } private function mOver() { arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc"); } private function mOut() { arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc"); } }
import mx.transitions.easing.*; import com.mosesSupposes.fuse.*; class menuColouridiomes extends MovieClip { public var cat, es, en ,fr:MovieClip; public var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr"); function menuColourIdiomes ():Void { this.onRollOver = this.mOver; this.onRollOut = this.mOut; this.onRelease =this.mOver; } private function mOver() { var i:Number; for (var i = 0; i < arrayLang_arr.length; i++) { arrayLang_arr[i].colorTo("#95C60D", 0.3, "easeOutCirc"); ] } private function mOut() { var i:Number; for (var i = 0; i < arrayLang_arr.length; i++) { arrayLang_arr[i].colorTo("#010101", 0.3, "easeInCirc"); } } }
Update menuColourIdiomes.as
Update menuColourIdiomes.as
ActionScript
bsd-3-clause
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
5072abbe32dc63e5267d80377fca2a309f2dc505
src/com/esri/builder/controllers/supportClasses/LocalConnectionDelegate.as
src/com/esri/builder/controllers/supportClasses/LocalConnectionDelegate.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.controllers.supportClasses { import flash.net.LocalConnection; import mx.logging.ILogger; import mx.logging.Log; public final class LocalConnectionDelegate { private static const LOG:ILogger = Log.getLogger('com.esri.builder.controllers.supportClasses.LocalConnectionDelegate'); private static const CNAME:String = '_flexViewer'; private var m_localConnection:LocalConnection; private function get localConnection():LocalConnection { if (m_localConnection === null) { if (Log.isDebug()) { LOG.debug("Acquiring local connection"); } m_localConnection = new LocalConnection(); } return m_localConnection; } public function setTitles(title:String, subtitle:String):void { if (Log.isDebug()) { LOG.debug("Sending titles changes: title {0} - subtitle {1}", title, subtitle); } localConnection.send(CNAME, 'setTitles', title, subtitle); } public function setLogo(value:String):void { if (Log.isDebug()) { LOG.debug("Sending logo changes {0}", value); } localConnection.send(CNAME, 'setLogo', value); } public function setTextColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending text color changes {0}", value); } localConnection.send(CNAME, 'setTextColor', value); } public function setBackgroundColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending background color changes {0}", value); } localConnection.send(CNAME, 'setBackgroundColor', value); } public function setRolloverColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending rollover color changes {0}", value); } localConnection.send(CNAME, 'setRolloverColor', value); } public function setSelectionColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending selection color changes {0}", value); } localConnection.send(CNAME, 'setSelectionColor', value); } public function setTitleColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending title color changes {0}", value); } localConnection.send(CNAME, 'setTitleColor', value); } public function setLocale(localeChain:String):void { if (Log.isDebug()) { LOG.debug("Sending locale changes {0}", localeChain); } localConnection.send(CNAME, 'setLocale', localeChain); } public function setFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending font name changes {0}", value); } localConnection.send(CNAME, 'setFontName', value); } public function setAppTitleFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending app title font name changes {0}", value); } localConnection.send(CNAME, 'setAppTitleFontName', value); } public function setSubTitleFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending subtitle font name changes {0}", value); } localConnection.send(CNAME, 'setSubTitleFontName', value); } public function setAlpha(value:Number):void { if (Log.isDebug()) { LOG.debug("Sending alpha changes {0}", value); } localConnection.send(CNAME, 'setAlpha', value); } public function setPredefinedStyles(value:Object):void { if (Log.isDebug()) { LOG.debug("Sending predefined changes {0}", value); } localConnection.send(CNAME, 'setPredefinedStyles', value); } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.controllers.supportClasses { import flash.events.StatusEvent; import flash.net.LocalConnection; import mx.logging.ILogger; import mx.logging.Log; public final class LocalConnectionDelegate { private static const LOG:ILogger = Log.getLogger('com.esri.builder.controllers.supportClasses.LocalConnectionDelegate'); private static const CNAME:String = '_flexViewer'; private var m_localConnection:LocalConnection; private function get localConnection():LocalConnection { if (m_localConnection === null) { if (Log.isDebug()) { LOG.debug("Acquiring local connection"); } m_localConnection = new LocalConnection(); m_localConnection.addEventListener(StatusEvent.STATUS, localConnection_statusHandler); } return m_localConnection; } private function localConnection_statusHandler(event:StatusEvent):void { if (event.level == "error") { if (Log.isDebug()) { LOG.debug("Call failed: {0}", event.toString()); } } } public function setTitles(title:String, subtitle:String):void { if (Log.isDebug()) { LOG.debug("Sending titles changes: title {0} - subtitle {1}", title, subtitle); } callViewerMethod('setTitles', title, subtitle); } private function callViewerMethod(methodName:String, ... values):void { try { //use Function#apply to avoid passing rest argument as Array localConnection.send.apply(null, [ CNAME, methodName ].concat(values)); } catch (error:Error) { if (Log.isDebug()) { LOG.debug("Call to Viewer method {0} failed: {1}", methodName, error); } } } public function setLogo(value:String):void { if (Log.isDebug()) { LOG.debug("Sending logo changes {0}", value); } callViewerMethod('setLogo', value); } public function setTextColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending text color changes {0}", value); } callViewerMethod('setTextColor', value); } public function setBackgroundColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending background color changes {0}", value); } callViewerMethod('setBackgroundColor', value); } public function setRolloverColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending rollover color changes {0}", value); } callViewerMethod('setRolloverColor', value); } public function setSelectionColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending selection color changes {0}", value); } callViewerMethod('setSelectionColor', value); } public function setTitleColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending title color changes {0}", value); } callViewerMethod('setTitleColor', value); } public function setLocale(localeChain:String):void { if (Log.isDebug()) { LOG.debug("Sending locale changes {0}", localeChain); } callViewerMethod('setLocale', localeChain); } public function setFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending font name changes {0}", value); } callViewerMethod('setFontName', value); } public function setAppTitleFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending app title font name changes {0}", value); } callViewerMethod('setAppTitleFontName', value); } public function setSubTitleFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending subtitle font name changes {0}", value); } callViewerMethod('setSubTitleFontName', value); } public function setAlpha(value:Number):void { if (Log.isDebug()) { LOG.debug("Sending alpha changes {0}", value); } callViewerMethod('setAlpha', value); } public function setPredefinedStyles(value:Object):void { if (Log.isDebug()) { LOG.debug("Sending predefined changes {0}", value); } callViewerMethod('setPredefinedStyles', value); } } }
Handle Viewer connection message failures.
Handle Viewer connection message failures.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
cecbcf43933d5e7774861734227a12eef31e26a4
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/LayoutChangeNotifier.as
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/LayoutChangeNotifier.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads.layouts { import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; /** * The LayoutChangeNotifier notifies layouts when a property * it is watching changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class LayoutChangeNotifier implements IBead { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function LayoutChangeNotifier() { } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; } private var _value:* = undefined; /** * The number of tiles to fit horizontally into the layout. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set watchedProperty(value:Object):void { if (_value !== value) { _value = value; IEventDispatcher(_strand).dispatchEvent(new Event("layoutNeeded")); } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads.layouts { import org.apache.flex.core.IBead; import org.apache.flex.core.IBeadView; import org.apache.flex.core.IStrand; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; /** * The LayoutChangeNotifier notifies layouts when a property * it is watching changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class LayoutChangeNotifier implements IBead { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function LayoutChangeNotifier() { } private var _strand:IStrand; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; } private var _value:* = undefined; /** * The number of tiles to fit horizontally into the layout. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set watchedProperty(value:Object):void { if (_value !== value) { _value = value; IBeadView(_strand).host.dispatchEvent(new Event("layoutNeeded")); } } } }
use host
use host
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
d2bbaab02e18b59285a50aa9bad6a65693c037b2
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/ImageView.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/beads/ImageView.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads { import flash.display.Bitmap; import flash.display.Loader; import flash.display.LoaderInfo; import flash.net.URLRequest; import org.apache.flex.core.BeadViewBase; import org.apache.flex.core.IBeadView; import org.apache.flex.core.IImageModel; import org.apache.flex.core.IStrand; import org.apache.flex.core.UIBase; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; /** * The ImageView class creates the visual elements of the org.apache.flex.html.Image component. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ImageView extends BeadViewBase implements IBeadView { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ImageView() { } private var bitmap:Bitmap; private var loader:Loader; private var _model:IImageModel; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; IEventDispatcher(_strand).addEventListener("widthChanged",handleSizeChange); IEventDispatcher(_strand).addEventListener("heightChanged",handleSizeChange); _model = value.getBeadByType(IImageModel) as IImageModel; _model.addEventListener("urlChanged",handleUrlChange); handleUrlChange(null); } /** * @private */ private function handleUrlChange(event:Event):void { if (_model.source) { loader = new Loader(); loader.contentLoaderInfo.addEventListener("complete",onComplete); loader.load(new URLRequest(_model.source)); } } /** * @private */ private function onComplete(event:Object):void { var host:UIBase = UIBase(_strand); if (bitmap) { host.removeChild(bitmap); } bitmap = Bitmap(LoaderInfo(event.target).content); host.addChild(bitmap); if (isNaN(host.explicitWidth) && isNaN(host.percentWidth)) host.dispatchEvent(new Event("widthChanged")); if (isNaN(host.explicitHeight) && isNaN(host.percentHeight)) host.dispatchEvent(new Event("heightChanged")); } /** * @private */ private function handleSizeChange(event:Object):void { var host:UIBase = UIBase(_strand); if (bitmap) { if (!isNaN(host.explicitWidth) || !isNaN(host.percentWidth)) bitmap.width = UIBase(_strand).width; if (!isNaN(host.explicitHeight) || !isNaN(host.percentHeight)) bitmap.height = UIBase(_strand).height; } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.beads { import flash.display.Bitmap; import flash.display.Loader; import flash.display.LoaderInfo; import flash.net.URLRequest; import org.apache.flex.core.BeadViewBase; import org.apache.flex.core.IBeadView; import org.apache.flex.core.IImageModel; import org.apache.flex.core.IStrand; import org.apache.flex.core.UIBase; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; /** * The ImageView class creates the visual elements of the org.apache.flex.html.Image component. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ImageView extends BeadViewBase implements IBeadView { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ImageView() { } private var bitmap:Bitmap; private var loader:Loader; private var _model:IImageModel; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set strand(value:IStrand):void { super.strand = value; IEventDispatcher(_strand).addEventListener("widthChanged",handleSizeChange); IEventDispatcher(_strand).addEventListener("heightChanged",handleSizeChange); _model = value.getBeadByType(IImageModel) as IImageModel; _model.addEventListener("urlChanged",handleUrlChange); handleUrlChange(null); } /** * @private */ private function handleUrlChange(event:Event):void { if (_model.source) { loader = new Loader(); loader.contentLoaderInfo.addEventListener("complete",onComplete); loader.load(new URLRequest(_model.source)); } } /** * @private */ private function onComplete(event:Object):void { var host:UIBase = UIBase(_strand); if (bitmap) { host.removeChild(bitmap); } bitmap = Bitmap(LoaderInfo(event.target).content); host.addChild(bitmap); if (isNaN(host.explicitWidth) && isNaN(host.percentWidth)) host.dispatchEvent(new Event("widthChanged")); else bitmap.width = UIBase(_strand).width; if (isNaN(host.explicitHeight) && isNaN(host.percentHeight)) host.dispatchEvent(new Event("heightChanged")); else bitmap.height = UIBase(_strand).height; } /** * @private */ private function handleSizeChange(event:Object):void { var host:UIBase = UIBase(_strand); if (bitmap) { if (!isNaN(host.explicitWidth) || !isNaN(host.percentWidth)) bitmap.width = UIBase(_strand).width; if (!isNaN(host.explicitHeight) || !isNaN(host.percentHeight)) bitmap.height = UIBase(_strand).height; } } } }
set size on bitmap if needed
set size on bitmap if needed
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
8386957cbc4f4856963795ac2c74dc2977e5ac52
src/as/com/threerings/util/Controller.as
src/as/com/threerings/util/Controller.as
package com.threerings.util { import flash.events.IEventDispatcher; import com.threerings.mx.events.CommandEvent; public class Controller { /** * Set the panel being controlled. */ protected function setControlledPanel (panel :IEventDispatcher) :void { if (_panel != null) { _panel.removeEventListener( CommandEvent.TYPE, handleCommandEvent); } _panel = panel; if (_panel != null) { _panel.addEventListener( CommandEvent.TYPE, handleCommandEvent); } } /** * Post an action so that it can be handled by this controller or * another controller above it in the display list. */ public final function postAction (cmd :String, arg :Object = null) :void { CommandEvent.dispatch(_panel, cmd, arg); } /** * Handle an action that was generated by our panel or some child. * * @return true if the specified action was handled, false otherwise. * * When creating your own controller, override this function and return * true for any command handled, and call super for any unknown commands. */ public function handleAction (cmd :String, arg :Object) :Boolean { // fall back to a method named the cmd try { var fn :Function = (this["handle" + cmd] as Function); if (fn != null) { try { fn(arg); } catch (e :Error) { var log :Log = Log.getLog(this); log.warning("Error handling controller " + "command [error=" + e + ", cmd=" + cmd + ", arg=" + arg + "]."); log.logStackTrace(e); } // we "handled" the event, even if it threw an error return true; } } catch (e :Error) { // suppress, and fall through } return false; // not handled } /** * Private function to handle the controller event and call * handleAction. */ private function handleCommandEvent (event :CommandEvent) :void { if (handleAction(event.command, event.arg)) { // if we handle the event, stop it from moving outward to another // controller event.preventDefault(); event.stopImmediatePropagation(); } } /** The panel currently being controlled. */ private var _panel :IEventDispatcher; } }
package com.threerings.util { import flash.events.IEventDispatcher; import com.threerings.mx.events.CommandEvent; public class Controller { /** * Set the panel being controlled. */ protected function setControlledPanel (panel :IEventDispatcher) :void { if (_panel != null) { _panel.removeEventListener( CommandEvent.TYPE, handleCommandEvent); } _panel = panel; if (_panel != null) { _panel.addEventListener( CommandEvent.TYPE, handleCommandEvent); } } /** * Post an action so that it can be handled by this controller or * another controller above it in the display list. */ public final function postAction (cmd :String, arg :Object = null) :void { CommandEvent.dispatch(_panel, cmd, arg); } /** * Handle an action that was generated by our panel or some child. * * @return true if the specified action was handled, false otherwise. * * When creating your own controller, override this function and return * true for any command handled, and call super for any unknown commands. */ public function handleAction (cmd :String, arg :Object) :Boolean { // fall back to a method named the cmd try { var fn :Function = (this["handle" + cmd] as Function); if (fn != null) { try { try { // try calling it with the arg fn(arg); } catch (ae :ArgumentError) { if (arg == null) { // try calling it without the arg fn(); } else { throw ae; } } } catch (e :Error) { var log :Log = Log.getLog(this); log.warning("Error handling controller " + "command [error=" + e + ", cmd=" + cmd + ", arg=" + arg + "]."); log.logStackTrace(e); } // we "handled" the event, even if it threw an error return true; } } catch (e :Error) { // suppress, and fall through } return false; // not handled } /** * Private function to handle the controller event and call * handleAction. */ private function handleCommandEvent (event :CommandEvent) :void { if (handleAction(event.command, event.arg)) { // if we handle the event, stop it from moving outward to another // controller event.preventDefault(); event.stopImmediatePropagation(); } } /** The panel currently being controlled. */ private var _panel :IEventDispatcher; } }
Allow the handleCOMMAND functions to have no arg if the command's arg is null.
Allow the handleCOMMAND functions to have no arg if the command's arg is null. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4347 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
981d3892ea4d3d41af03c49e0df980738ba57930
src/milkshape/media/flash/src/cc/milkshape/grid/process/SquareProcessController.as
src/milkshape/media/flash/src/cc/milkshape/grid/process/SquareProcessController.as
package cc.milkshape.grid.process { import cc.milkshape.gateway.Gateway; import cc.milkshape.gateway.GatewayController; import cc.milkshape.grid.GridModel; import cc.milkshape.grid.process.events.SquareProcessEvent; import cc.milkshape.grid.process.files.SquareProcessFileDownload; import cc.milkshape.grid.process.files.SquareProcessFileUpload; import flash.events.Event; import flash.net.Responder; import flash.utils.ByteArray; public class SquareProcessController extends GatewayController { private var _fileDownload:SquareProcessFileDownload; private var _fileUpload:SquareProcessFileUpload; public function SquareProcessController() { _fileDownload = new SquareProcessFileDownload(); _fileDownload.addEventListener(Event.COMPLETE, _templateDownloaded); _fileUpload = new SquareProcessFileUpload(); } public function book(posX:int, posY:int, issueSlug:String):void { _responder = new Responder(_book, _onFault); Gateway.getInstance().call("square.book", _responder, posY, posX, issueSlug); } private function _book(result:Object):void { if(result){ _fileDownload.setURI(result.template_url); dispatchEvent(new SquareProcessEvent(SquareProcessEvent.BOOKED)); } } public function release(posX:int, posY:int, issueSlug:String):void { _responder = new Responder(_released, _onFault); Gateway.getInstance().call("square.release", _responder, posY, posX, issueSlug); } private function _released(result:Object):void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.CANCELED)); } public function loadTemplate(posX:int, posY:int, issueSlug:String):void { _responder = new Responder(_template, _onFault); Gateway.getInstance().call("square.template", _responder, posY, posX, issueSlug); } public function template():void { _fileDownload.downloadTpl(); } private function _templateDownloaded(e:Event):void { trace("template downloaded"); } private function _template(result:Object):void { _fileDownload.setURI(result as String); dispatchEvent(new SquareProcessEvent(SquareProcessEvent.DOWNLOAD)); } public function fill(posX:int, posY:int, issueSlug:String):void { _fileUpload.addEventListener(Event.COMPLETE, function(e:Event):void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.UPLOADING)); var data:ByteArray = new ByteArray(); _fileUpload.data.readBytes(data, 0, _fileUpload.data.length); _responder = new Responder(_uploaded, _onFault); Gateway.getInstance().call("square.fill", _responder, posY, posX, issueSlug, data); trace("test"); dispatchEvent(new SquareProcessEvent(SquareProcessEvent.UPLOADING2)); } ); _fileUpload.browseTpl(); } public function _uploaded(result:Object):void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.SUCCESS)); } public function reload():void { trace('reload issue'); } public function show():void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.SHOW)); } public function hide():void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.HIDE)); } } }
package cc.milkshape.grid.process { import cc.milkshape.gateway.Gateway; import cc.milkshape.gateway.GatewayController; import cc.milkshape.grid.GridModel; import cc.milkshape.grid.process.events.SquareProcessEvent; import cc.milkshape.grid.process.files.SquareProcessFileDownload; import cc.milkshape.grid.process.files.SquareProcessFileUpload; import flash.events.Event; import flash.net.Responder; import flash.utils.ByteArray; public class SquareProcessController extends GatewayController { private var _fileDownload:SquareProcessFileDownload; private var _fileUpload:SquareProcessFileUpload; public function SquareProcessController() { _fileDownload = new SquareProcessFileDownload(); _fileDownload.addEventListener(Event.COMPLETE, _templateDownloaded); _fileUpload = new SquareProcessFileUpload(); } public function book(posX:int, posY:int, issueSlug:String):void { _responder = new Responder(_book, _onFault); Gateway.getInstance().call("square.book", _responder, posX, posY, issueSlug); } private function _book(result:Object):void { if(result){ _fileDownload.setURI(result.template_url); dispatchEvent(new SquareProcessEvent(SquareProcessEvent.BOOKED)); } } public function release(posX:int, posY:int, issueSlug:String):void { _responder = new Responder(_released, _onFault); Gateway.getInstance().call("square.release", _responder, posX, posY, issueSlug); } private function _released(result:Object):void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.CANCELED)); } public function loadTemplate(posX:int, posY:int, issueSlug:String):void { _responder = new Responder(_template, _onFault); Gateway.getInstance().call("square.template", _responder, posX, posY, issueSlug); } public function template():void { _fileDownload.downloadTpl(); } private function _templateDownloaded(e:Event):void { trace("template downloaded"); } private function _template(result:Object):void { _fileDownload.setURI(result as String); dispatchEvent(new SquareProcessEvent(SquareProcessEvent.DOWNLOAD)); } public function fill(posX:int, posY:int, issueSlug:String):void { _fileUpload.addEventListener(Event.COMPLETE, function(e:Event):void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.UPLOADING)); var data:ByteArray = new ByteArray(); _fileUpload.data.readBytes(data, 0, _fileUpload.data.length); _responder = new Responder(_uploaded, _onFault); Gateway.getInstance().call("square.fill", _responder, posX, posY, issueSlug, data); trace("test"); dispatchEvent(new SquareProcessEvent(SquareProcessEvent.UPLOADING2)); } ); _fileUpload.browseTpl(); } public function _uploaded(result:Object):void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.SUCCESS)); } public function reload():void { trace('reload issue'); } public function show():void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.SHOW)); } public function hide():void { dispatchEvent(new SquareProcessEvent(SquareProcessEvent.HIDE)); } } }
fix upload process
fix upload process
ActionScript
mit
thoas/i386,thoas/i386,thoas/i386,thoas/i386
f4e3f0c01ba1e59d040d083cd34da5bb26b7addc
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
package aerys.minko.scene.controller.mesh { import aerys.minko.ns.minko_math; import aerys.minko.render.geometry.Geometry; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.FrustumCulling; import aerys.minko.type.math.BoundingBox; import aerys.minko.type.math.BoundingSphere; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * The MeshVisibilityController watches the Mesh and the active Camera of a Scene * to determine whether the object is actually inside the view frustum or not. * * @author Jean-Marc Le Roux * */ public final class MeshVisibilityController extends AbstractController { use namespace minko_math; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const STATE_UNDEFINED : uint = 0; private static const STATE_INSIDE : uint = 1; private static const STATE_OUTSIDE : uint = 2; private var _mesh : Mesh; private var _state : uint; private var _lastTest : int; private var _boundingBox : BoundingBox; private var _boundingSphere : BoundingSphere; private var _frustumCulling : uint; private var _insideFrustum : Boolean; private var _computedVisibility : Boolean; public function get frustumCulling() : uint { return _frustumCulling; } public function set frustumCulling(value : uint) : void { _frustumCulling = value; testCulling(); } public function get insideFrustum() : Boolean { return _insideFrustum; } public function get computedVisibility() : Boolean { return _frustumCulling == FrustumCulling.DISABLED || _computedVisibility; } public function MeshVisibilityController() { super(Mesh); initialize(); } private function initialize() : void { _boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE); _boundingSphere = new BoundingSphere(Vector4.ZERO, 0.); _state = STATE_UNDEFINED; targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : MeshVisibilityController, target : Mesh) : void { if (_mesh != null) throw new Error(); _mesh = target; target.added.add(addedHandler); target.removed.add(removedHandler); if (target.root is Scene) addedHandler(target, target.root as Scene); } private function targetRemovedHandler(ctrl : MeshVisibilityController, target : Mesh) : void { _mesh = null; target.added.remove(addedHandler); target.removed.remove(removedHandler); if (target.root is Scene) removedHandler(target, target.root as Scene); } private function addedHandler(mesh : Mesh, ancestor : Group) : void { var scene : Scene = mesh.scene; if (!scene) return ; scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler); meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform()); mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler); mesh.visibilityChanged.add(visiblityChangedHandler); mesh.parent.computedVisibilityChanged.add(visiblityChangedHandler); mesh.removed.add(meshRemovedHandler); } private function meshRemovedHandler(mesh : Mesh, ancestor : Group) : void { if (!mesh.parent) ancestor.computedVisibilityChanged.remove(visiblityChangedHandler); } private function removedHandler(mesh : Mesh, ancestor : Group) : void { var scene : Scene = ancestor.scene; if (!scene) return ; scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler); mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler); mesh.visibilityChanged.remove(visiblityChangedHandler); mesh.removed.remove(meshRemovedHandler); if (mesh.parent) mesh.parent.computedVisibilityChanged.remove(visiblityChangedHandler); } private function visiblityChangedHandler(node : ISceneNode, visibility : Boolean) : void { _computedVisibility = _mesh.visible && _mesh.parent.computedVisibility && _insideFrustum; _mesh.computedVisibilityChanged.execute(_mesh, _computedVisibility); } private function worldToScreenChangedHandler(bindings : DataBindings, propertyName : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { testCulling(); } private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void { var geom : Geometry = _mesh.geometry; var culling : uint = _frustumCulling; if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED) return ; if (culling & FrustumCulling.BOX) transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices); if (culling & FrustumCulling.SPHERE) { var center : Vector4 = transform.transformVector(geom.boundingSphere.center); var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE); var radius : Number = geom.boundingSphere.radius * Math.max( Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z) ); _boundingSphere.update(center, radius); } testCulling(); } private function testCulling() : void { var culling : uint = _frustumCulling; if (culling != FrustumCulling.DISABLED && _mesh && _mesh.geometry.boundingBox && _mesh.visible) { var camera : AbstractCamera = (_mesh.root as Scene).activeCamera; if (!camera) return ; _lastTest = camera.frustum.testBoundingVolume( _boundingSphere, _boundingBox, null, culling, _lastTest ); var inside : Boolean = _lastTest == -1; if (inside && _state != STATE_INSIDE) { _insideFrustum = true; _computedVisibility = _mesh.parent.computedVisibility && _mesh.visible; _mesh.computedVisibilityChanged.execute(_mesh, computedVisibility); _state = STATE_INSIDE; } else if (!inside && _state != STATE_OUTSIDE) { _insideFrustum = false; _computedVisibility = false; _mesh.computedVisibilityChanged.execute(_mesh, false); _state = STATE_OUTSIDE; } } } override public function clone() : AbstractController { return new MeshVisibilityController();; } } }
package aerys.minko.scene.controller.mesh { import aerys.minko.ns.minko_math; import aerys.minko.render.geometry.Geometry; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.FrustumCulling; import aerys.minko.type.math.BoundingBox; import aerys.minko.type.math.BoundingSphere; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; /** * The MeshVisibilityController watches the Mesh and the active Camera of a Scene * to determine whether the object is actually inside the view frustum or not. * * @author Jean-Marc Le Roux * */ public final class MeshVisibilityController extends AbstractController { use namespace minko_math; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const STATE_UNDEFINED : uint = 0; private static const STATE_INSIDE : uint = 1; private static const STATE_OUTSIDE : uint = 2; private var _mesh : Mesh; private var _state : uint; private var _lastTest : int; private var _boundingBox : BoundingBox; private var _boundingSphere : BoundingSphere; private var _frustumCulling : uint; private var _insideFrustum : Boolean; private var _computedVisibility : Boolean; public function get frustumCulling() : uint { return _frustumCulling; } public function set frustumCulling(value : uint) : void { _frustumCulling = value; testCulling(); } public function get insideFrustum() : Boolean { return _insideFrustum; } public function get computedVisibility() : Boolean { return _frustumCulling == FrustumCulling.DISABLED || _computedVisibility; } public function MeshVisibilityController() { super(Mesh); initialize(); } private function initialize() : void { _boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE); _boundingSphere = new BoundingSphere(Vector4.ZERO, 0.); _state = STATE_UNDEFINED; targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : MeshVisibilityController, target : Mesh) : void { if (_mesh != null) throw new Error(); _mesh = target; target.added.add(addedHandler); target.removed.add(removedHandler); if (target.root is Scene) addedHandler(target, target.root as Scene); } private function targetRemovedHandler(ctrl : MeshVisibilityController, target : Mesh) : void { _mesh = null; target.added.remove(addedHandler); target.removed.remove(removedHandler); if (target.root is Scene) removedHandler(target, target.root as Scene); } private function addedHandler(mesh : Mesh, ancestor : Group) : void { var scene : Scene = mesh.scene; if (!scene) return ; scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler); meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform()); mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler); mesh.visibilityChanged.add(visiblityChangedHandler); mesh.parent.computedVisibilityChanged.add(visiblityChangedHandler); mesh.removed.add(meshRemovedHandler); } private function meshRemovedHandler(mesh : Mesh, ancestor : Group) : void { if (!mesh.parent) ancestor.computedVisibilityChanged.remove(visiblityChangedHandler); } private function removedHandler(mesh : Mesh, ancestor : Group) : void { var scene : Scene = ancestor.scene; if (!scene) return ; scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler); mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler); mesh.visibilityChanged.remove(visiblityChangedHandler); mesh.removed.remove(meshRemovedHandler); if (mesh.parent) mesh.parent.computedVisibilityChanged.remove(visiblityChangedHandler); } private function visiblityChangedHandler(node : ISceneNode, visibility : Boolean) : void { _computedVisibility = _mesh.visible && _mesh.parent.computedVisibility && (_frustumCulling == FrustumCulling.DISABLED || _insideFrustum); _mesh.computedVisibilityChanged.execute(_mesh, _computedVisibility); } private function worldToScreenChangedHandler(bindings : DataBindings, propertyName : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { testCulling(); } private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void { var geom : Geometry = _mesh.geometry; var culling : uint = _frustumCulling; if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED) return ; if (culling & FrustumCulling.BOX) transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices); if (culling & FrustumCulling.SPHERE) { var center : Vector4 = transform.transformVector(geom.boundingSphere.center); var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE); var radius : Number = geom.boundingSphere.radius * Math.max( Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z) ); _boundingSphere.update(center, radius); } testCulling(); } private function testCulling() : void { var culling : uint = _frustumCulling; if (culling != FrustumCulling.DISABLED && _mesh && _mesh.geometry.boundingBox && _mesh.visible) { var camera : AbstractCamera = (_mesh.root as Scene).activeCamera; if (!camera) return ; _lastTest = camera.frustum.testBoundingVolume( _boundingSphere, _boundingBox, null, culling, _lastTest ); var inside : Boolean = _lastTest == -1; if (inside && _state != STATE_INSIDE) { _insideFrustum = true; _computedVisibility = _mesh.parent.computedVisibility && _mesh.visible; _mesh.computedVisibilityChanged.execute(_mesh, computedVisibility); _state = STATE_INSIDE; } else if (!inside && _state != STATE_OUTSIDE) { _insideFrustum = false; _computedVisibility = false; _mesh.computedVisibilityChanged.execute(_mesh, false); _state = STATE_OUTSIDE; } } } override public function clone() : AbstractController { return new MeshVisibilityController();; } } }
fix wrong computation for _computedVisibility because _insideFrustum is always false when frustum culling is disabled
fix wrong computation for _computedVisibility because _insideFrustum is always false when frustum culling is disabled
ActionScript
mit
aerys/minko-as3
1b49aa6a248faa7a13e3a367b576f2548c468aa5
src/aerys/minko/scene/node/AbstractSceneNode.as
src/aerys/minko/scene/node/AbstractSceneNode.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.data.TransformDataProvider; import aerys.minko.type.Signal; import aerys.minko.type.clone.CloneOptions; import aerys.minko.type.clone.ControllerCloneAction; import aerys.minko.type.math.Matrix4x4; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { private static var _id : uint; private var _name : String; private var _root : ISceneNode; private var _parent : Group; private var _visible : Boolean; private var _computedVisibility : Boolean; private var _transform : Matrix4x4; private var _localToWorld : Matrix4x4; private var _worldToLocal : Matrix4x4; private var _controllers : Vector.<AbstractController>; private var _added : Signal; private var _removed : Signal; private var _addedToScene : Signal; private var _removedFromScene : Signal; private var _controllerAdded : Signal; private var _controllerRemoved : Signal; private var _visibilityChanged : Signal; private var _computedVisibilityChanged : Signal; final public function get x() : Number { return _transform.translationX; } final public function set x(value : Number) : void { _transform.translationX = value; } final public function get y() : Number { return _transform.translationX; } final public function set y(value : Number) : void { _transform.translationY = value; } final public function get z() : Number { return _transform.translationX; } final public function set z(value : Number) : void { _transform.translationZ = value; } final public function get rotationX() : Number { return _transform.rotationX; } final public function set rotationX(value : Number) : void { _transform.rotationX = value; } final public function get rotationY() : Number { return _transform.rotationY; } final public function set rotationY(value : Number) : void { _transform.rotationY = value; } final public function get rotationZ() : Number { return _transform.rotationZ; } final public function set rotationZ(value : Number) : void { _transform.rotationZ = value; } final public function get scaleX() : Number { return _transform.scaleX; } final public function set scaleX(value : Number) : void { _transform.scaleX = value; } final public function get scaleY() : Number { return _transform.scaleX; } final public function set scaleY(value : Number) : void { _transform.scaleY = value; } final public function get scaleZ() : Number { return _transform.scaleZ; } final public function set scaleZ(value : Number) : void { _transform.scaleZ = value; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } final public function get parent() : Group { return _parent; } final public function set parent(value : Group) : void { if (value == _parent) return ; // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice(oldParent.getChildIndex(this), 1); parent._numChildren--; _parent = null; _removed.execute(this, oldParent); oldParent.descendantRemoved.execute(oldParent, this); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _added.execute(this, _parent); _parent.descendantAdded.execute(_parent, this); } } final public function get scene() : Scene { return _root as Scene; } final public function get root() : ISceneNode { return _root; } public function get visible() : Boolean { return _visible; } public function set visible(value : Boolean) : void { if (value != _visible) { _visible = value; _visibilityChanged.execute(this, value); updateComputedVisibility(); } } public function get computedVisibility() : Boolean { return _computedVisibility; } final public function get transform() : Matrix4x4 { return _transform; } final public function get localToWorld() : Matrix4x4 { return _localToWorld; } final public function get worldToLocal() : Matrix4x4 { return _worldToLocal; } final public function get added() : Signal { return _added; } final public function get removed() : Signal { return _removed; } final public function get addedToScene() : Signal { return _addedToScene; } final public function get removedFromScene() : Signal { return _removedFromScene; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } public function get visibilityChanged() : Signal { return _visibilityChanged; } public function get computedVisibilityChanged() : Signal { return _computedVisibilityChanged; } public function AbstractSceneNode() { initialize(); } private function initialize() : void { _name = getDefaultSceneName(this); _visible = true; _computedVisibility = true; _transform = new Matrix4x4(); _localToWorld = new Matrix4x4(); _worldToLocal = new Matrix4x4(); _controllers = new <AbstractController>[]; _added = new Signal('AbstractSceneNode.added'); _removed = new Signal('AbstractSceneNode.removed'); _addedToScene = new Signal('AbstractSceneNode.addedToScene'); _removedFromScene = new Signal('AbstractSceneNode.removedFromScene'); _controllerAdded = new Signal('AbstractSceneNode.controllerAdded'); _controllerRemoved = new Signal('AbstractSceneNode.controllerRemoved'); _visibilityChanged = new Signal('AbstractSceneNode.visibilityChanged'); _computedVisibilityChanged = new Signal('AbstractSceneNode.computedVisibilityChanged'); updateRoot(); _added.add(addedHandler); _removed.add(removedHandler); _addedToScene.add(addedToSceneHandler); _removedFromScene.add(removedFromSceneHandler); addController(new TransformController()); } protected function addedHandler(child : ISceneNode, ancestor : Group) : void { // if ancestor == parent then the node was just added as a direct child of ancestor if (ancestor == _parent) { _parent.computedVisibilityChanged.add(parentComputedVisibilityChangedHandler); parentComputedVisibilityChangedHandler(_parent, _parent.computedVisibility); } updateRoot(); } protected function removedHandler(child : ISceneNode, ancestor : Group) : void { // if parent is not set anymore, ancestor is not the direct parent of child anymore if (!_parent) { ancestor.computedVisibilityChanged.remove(parentComputedVisibilityChangedHandler); _computedVisibility = false; } updateRoot(); } private function updateRoot() : void { var newRoot : ISceneNode = _parent ? _parent.root : this; var oldRoot : ISceneNode = _root; if (newRoot != oldRoot) { _root = newRoot; if (oldRoot is Scene) _removedFromScene.execute(this, oldRoot); if (newRoot is Scene) _addedToScene.execute(this, newRoot); } } protected function parentComputedVisibilityChangedHandler(parent : Group, visibility : Boolean) : void { updateComputedVisibility(); } private function updateComputedVisibility() : void { var newComputedVisibility : Boolean = _visible && (!_parent || _parent.computedVisibility); if (newComputedVisibility != computedVisibility) { _computedVisibility = newComputedVisibility; _computedVisibilityChanged.execute(this, newComputedVisibility); } } protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; var controllerId : int = _controllers.indexOf(controller); if (controllerId < 0) throw new Error('The controller is not on the node.'); _controllers[controllerId] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } minko_scene function cloneNode() : AbstractSceneNode { throw new Error('Must be overriden'); } public final function clone(cloneOptions : CloneOptions = null) : ISceneNode { cloneOptions ||= CloneOptions.defaultOptions; // fill up 2 dics with all nodes and controllers var nodeMap : Dictionary = new Dictionary(); var controllerMap : Dictionary = new Dictionary(); listItems(cloneNode(), nodeMap, controllerMap); // clone controllers with respect with instructions cloneControllers(controllerMap, cloneOptions); // rebind all controller dependencies. rebindControllerDependencies(controllerMap, nodeMap, cloneOptions); // add cloned/rebinded/original controllers to clones for (var objNode : Object in nodeMap) { var node : AbstractSceneNode = AbstractSceneNode(objNode); var numControllers : uint = node.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = controllerMap[node.getController(controllerId)]; if (controller != null) nodeMap[node].addController(controller); } } return nodeMap[this]; } private function listItems(clonedRoot : ISceneNode, nodes : Dictionary, controllers : Dictionary) : void { var numControllers : uint = this.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) controllers[getController(controllerId)] = true; nodes[this] = clonedRoot; if (this is Group) { var group : Group = Group(this); var clonedGroup : Group = Group(clonedRoot); var numChildren : uint = group.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId)); var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId)); child.listItems(clonedChild, nodes, controllers); } } } private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (action == ControllerCloneAction.CLONE) controllerMap[controller] = controller.clone(); else if (action == ControllerCloneAction.REASSIGN) controllerMap[controller] = controller; else if (action == ControllerCloneAction.IGNORE) controllerMap[controller] = null; else throw new Error(); } } private function rebindControllerDependencies(controllerMap : Dictionary, nodeMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (controller is IRebindableController && action == ControllerCloneAction.CLONE) IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap); } } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.data.TransformDataProvider; import aerys.minko.type.Signal; import aerys.minko.type.clone.CloneOptions; import aerys.minko.type.clone.ControllerCloneAction; import aerys.minko.type.math.Matrix4x4; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { private static var _id : uint; private var _name : String; private var _root : ISceneNode; private var _parent : Group; private var _visible : Boolean; private var _computedVisibility : Boolean; private var _transform : Matrix4x4; private var _localToWorld : Matrix4x4; private var _worldToLocal : Matrix4x4; private var _controllers : Vector.<AbstractController>; private var _added : Signal; private var _removed : Signal; private var _addedToScene : Signal; private var _removedFromScene : Signal; private var _controllerAdded : Signal; private var _controllerRemoved : Signal; private var _visibilityChanged : Signal; private var _computedVisibilityChanged : Signal; final public function get x() : Number { return _transform.translationX; } final public function set x(value : Number) : void { _transform.translationX = value; } final public function get y() : Number { return _transform.translationX; } final public function set y(value : Number) : void { _transform.translationY = value; } final public function get z() : Number { return _transform.translationX; } final public function set z(value : Number) : void { _transform.translationZ = value; } final public function get rotationX() : Number { return _transform.rotationX; } final public function set rotationX(value : Number) : void { _transform.rotationX = value; } final public function get rotationY() : Number { return _transform.rotationY; } final public function set rotationY(value : Number) : void { _transform.rotationY = value; } final public function get rotationZ() : Number { return _transform.rotationZ; } final public function set rotationZ(value : Number) : void { _transform.rotationZ = value; } final public function get scaleX() : Number { return _transform.scaleX; } final public function set scaleX(value : Number) : void { _transform.scaleX = value; } final public function get scaleY() : Number { return _transform.scaleY; } final public function set scaleY(value : Number) : void { _transform.scaleY = value; } final public function get scaleZ() : Number { return _transform.scaleZ; } final public function set scaleZ(value : Number) : void { _transform.scaleZ = value; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } final public function get parent() : Group { return _parent; } final public function set parent(value : Group) : void { if (value == _parent) return ; // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice(oldParent.getChildIndex(this), 1); parent._numChildren--; _parent = null; _removed.execute(this, oldParent); oldParent.descendantRemoved.execute(oldParent, this); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _added.execute(this, _parent); _parent.descendantAdded.execute(_parent, this); } } final public function get scene() : Scene { return _root as Scene; } final public function get root() : ISceneNode { return _root; } public function get visible() : Boolean { return _visible; } public function set visible(value : Boolean) : void { if (value != _visible) { _visible = value; _visibilityChanged.execute(this, value); updateComputedVisibility(); } } public function get computedVisibility() : Boolean { return _computedVisibility; } final public function get transform() : Matrix4x4 { return _transform; } final public function get localToWorld() : Matrix4x4 { return _localToWorld; } final public function get worldToLocal() : Matrix4x4 { return _worldToLocal; } final public function get added() : Signal { return _added; } final public function get removed() : Signal { return _removed; } final public function get addedToScene() : Signal { return _addedToScene; } final public function get removedFromScene() : Signal { return _removedFromScene; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } public function get visibilityChanged() : Signal { return _visibilityChanged; } public function get computedVisibilityChanged() : Signal { return _computedVisibilityChanged; } public function AbstractSceneNode() { initialize(); } private function initialize() : void { _name = getDefaultSceneName(this); _visible = true; _computedVisibility = true; _transform = new Matrix4x4(); _localToWorld = new Matrix4x4(); _worldToLocal = new Matrix4x4(); _controllers = new <AbstractController>[]; _added = new Signal('AbstractSceneNode.added'); _removed = new Signal('AbstractSceneNode.removed'); _addedToScene = new Signal('AbstractSceneNode.addedToScene'); _removedFromScene = new Signal('AbstractSceneNode.removedFromScene'); _controllerAdded = new Signal('AbstractSceneNode.controllerAdded'); _controllerRemoved = new Signal('AbstractSceneNode.controllerRemoved'); _visibilityChanged = new Signal('AbstractSceneNode.visibilityChanged'); _computedVisibilityChanged = new Signal('AbstractSceneNode.computedVisibilityChanged'); updateRoot(); _added.add(addedHandler); _removed.add(removedHandler); _addedToScene.add(addedToSceneHandler); _removedFromScene.add(removedFromSceneHandler); addController(new TransformController()); } protected function addedHandler(child : ISceneNode, ancestor : Group) : void { // if ancestor == parent then the node was just added as a direct child of ancestor if (ancestor == _parent) { _parent.computedVisibilityChanged.add(parentComputedVisibilityChangedHandler); parentComputedVisibilityChangedHandler(_parent, _parent.computedVisibility); } updateRoot(); } protected function removedHandler(child : ISceneNode, ancestor : Group) : void { // if parent is not set anymore, ancestor is not the direct parent of child anymore if (!_parent) { ancestor.computedVisibilityChanged.remove(parentComputedVisibilityChangedHandler); _computedVisibility = false; } updateRoot(); } private function updateRoot() : void { var newRoot : ISceneNode = _parent ? _parent.root : this; var oldRoot : ISceneNode = _root; if (newRoot != oldRoot) { _root = newRoot; if (oldRoot is Scene) _removedFromScene.execute(this, oldRoot); if (newRoot is Scene) _addedToScene.execute(this, newRoot); } } protected function parentComputedVisibilityChangedHandler(parent : Group, visibility : Boolean) : void { updateComputedVisibility(); } private function updateComputedVisibility() : void { var newComputedVisibility : Boolean = _visible && (!_parent || _parent.computedVisibility); if (newComputedVisibility != computedVisibility) { _computedVisibility = newComputedVisibility; _computedVisibilityChanged.execute(this, newComputedVisibility); } } protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; var controllerId : int = _controllers.indexOf(controller); if (controllerId < 0) throw new Error('The controller is not on the node.'); _controllers[controllerId] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } minko_scene function cloneNode() : AbstractSceneNode { throw new Error('Must be overriden'); } public final function clone(cloneOptions : CloneOptions = null) : ISceneNode { cloneOptions ||= CloneOptions.defaultOptions; // fill up 2 dics with all nodes and controllers var nodeMap : Dictionary = new Dictionary(); var controllerMap : Dictionary = new Dictionary(); listItems(cloneNode(), nodeMap, controllerMap); // clone controllers with respect with instructions cloneControllers(controllerMap, cloneOptions); // rebind all controller dependencies. rebindControllerDependencies(controllerMap, nodeMap, cloneOptions); // add cloned/rebinded/original controllers to clones for (var objNode : Object in nodeMap) { var node : AbstractSceneNode = AbstractSceneNode(objNode); var numControllers : uint = node.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = controllerMap[node.getController(controllerId)]; if (controller != null) nodeMap[node].addController(controller); } } return nodeMap[this]; } private function listItems(clonedRoot : ISceneNode, nodes : Dictionary, controllers : Dictionary) : void { var numControllers : uint = this.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) controllers[getController(controllerId)] = true; nodes[this] = clonedRoot; if (this is Group) { var group : Group = Group(this); var clonedGroup : Group = Group(clonedRoot); var numChildren : uint = group.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId)); var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId)); child.listItems(clonedChild, nodes, controllers); } } } private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (action == ControllerCloneAction.CLONE) controllerMap[controller] = controller.clone(); else if (action == ControllerCloneAction.REASSIGN) controllerMap[controller] = controller; else if (action == ControllerCloneAction.IGNORE) controllerMap[controller] = null; else throw new Error(); } } private function rebindControllerDependencies(controllerMap : Dictionary, nodeMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (controller is IRebindableController && action == ControllerCloneAction.CLONE) IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap); } } } }
Update src/aerys/minko/scene/node/AbstractSceneNode.as
Update src/aerys/minko/scene/node/AbstractSceneNode.as BUG:scaleY 
ActionScript
mit
aerys/minko-as3
91d4deb5cebd6017ecbab9c6d243c61ed5e6fafb
src/org/mangui/chromeless/ChromelessPlayer.as
src/org/mangui/chromeless/ChromelessPlayer.as
package org.mangui.chromeless { import flash.net.URLStream; import org.mangui.HLS.parsing.Level; import org.mangui.HLS.*; import org.mangui.HLS.utils.*; import flash.display.*; import flash.events.*; import flash.external.ExternalInterface; import flash.geom.Rectangle; import flash.media.Video; import flash.media.SoundTransform; import flash.media.StageVideo; import flash.media.StageVideoAvailability; import flash.utils.setTimeout; public class ChromelessPlayer extends Sprite { /** reference to the framework. **/ private var _hls : HLS; /** Sheet to place on top of the video. **/ private var _sheet : Sprite; /** Reference to the stage video element. **/ private var _stageVideo : StageVideo = null; /** Reference to the video element. **/ private var _video : Video = null; /** Video size **/ private var _videoWidth : Number = 0; private var _videoHeight : Number = 0; /** current media position */ private var _media_position : Number; /** Initialization. **/ public function ChromelessPlayer() : void { // Set stage properties stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); stage.addEventListener(Event.RESIZE, _onStageResize); // Draw sheet for catching clicks _sheet = new Sprite(); _sheet.graphics.beginFill(0x000000, 0); _sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); _sheet.addEventListener(MouseEvent.CLICK, _clickHandler); _sheet.buttonMode = true; addChild(_sheet); // Connect getters to JS. ExternalInterface.addCallback("getLevel", _getLevel); ExternalInterface.addCallback("getLevels", _getLevels); ExternalInterface.addCallback("getMetrics", _getMetrics); ExternalInterface.addCallback("getPosition", _getPosition); ExternalInterface.addCallback("getState", _getState); ExternalInterface.addCallback("getType", _getType); ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength); ExternalInterface.addCallback("getminBufferLength", _getminBufferLength); ExternalInterface.addCallback("getbufferLength", _getbufferLength); ExternalInterface.addCallback("getLogDebug", _getLogDebug); ExternalInterface.addCallback("getLogDebug2", _getLogDebug2); ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache); ExternalInterface.addCallback("getstartFromLowestLevel", _getstartFromLowestLevel); ExternalInterface.addCallback("getJSURLStream", _getJSURLStream); ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion); ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList); ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId); // Connect calls to JS. ExternalInterface.addCallback("playerLoad", _load); ExternalInterface.addCallback("playerPlay", _play); ExternalInterface.addCallback("playerPause", _pause); ExternalInterface.addCallback("playerResume", _resume); ExternalInterface.addCallback("playerSeek", _seek); ExternalInterface.addCallback("playerStop", _stop); ExternalInterface.addCallback("playerVolume", _volume); ExternalInterface.addCallback("playerSetLevel", _setLevel); ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength); ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength); ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache); ExternalInterface.addCallback("playerSetstartFromLowestLevel", _setstartFromLowestLevel); ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug); ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2); ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack); ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream); setTimeout(_pingJavascript, 50); }; /** Notify javascript the framework is ready. **/ private function _pingJavascript() : void { ExternalInterface.call("onHLSReady", ExternalInterface.objectID); }; /** Forward events from the framework. **/ private function _completeHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onComplete"); } }; private function _errorHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onError", event.message); } }; private function _fragmentHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth); } }; private function _manifestHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onManifest", event.levels[0].duration); } }; private function _mediaTimeHandler(event : HLSEvent) : void { if (ExternalInterface.available) { _media_position = event.mediatime.position; ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding); } var videoWidth : Number = _video ? _video.videoWidth : _stageVideo.videoWidth; var videoHeight : Number = _video ? _video.videoHeight : _stageVideo.videoHeight; if (videoWidth && videoHeight) { var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight; if (changed) { _videoHeight = videoHeight; _videoWidth = videoWidth; _resize(); if (ExternalInterface.available) { ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight); } } } }; private function _stateHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onState", event.state); } }; private function _switchHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onSwitch", event.level); } }; private function _audioTracksListChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList()); } } private function _audioTrackChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTrackChange", event.audioTrack); } } /** Javascript getters. **/ private function _getLevel() : Number { return _hls.level; }; private function _getLevels() : Vector.<Level> { return _hls.levels; }; private function _getMetrics() : Object { return _hls.metrics; }; private function _getPosition() : Number { return _hls.position; }; private function _getState() : String { return _hls.state; }; private function _getType() : String { return _hls.type; }; private function _getbufferLength() : Number { return _hls.bufferLength; }; private function _getmaxBufferLength() : Number { return _hls.maxBufferLength; }; private function _getminBufferLength() : Number { return _hls.minBufferLength; }; private function _getflushLiveURLCache() : Boolean { return _hls.flushLiveURLCache; }; private function _getstartFromLowestLevel() : Boolean { return _hls.startFromLowestLevel; }; private function _getLogDebug() : Boolean { return Log.LOG_DEBUG_ENABLED; }; private function _getLogDebug2() : Boolean { return Log.LOG_DEBUG2_ENABLED; }; private function _getJSURLStream() : Boolean { return (_hls.URLstream is JSURLStream); }; private function _getPlayerVersion() : Number { return 2; }; private function _getAudioTrackList() : Array { var list : Array = []; var vec : Vector.<HLSAudioTrack> = _hls.audioTracks; for (var i : Object in vec) { list.push(vec[i]); } return list; }; private function _getAudioTrackId() : Number { return _hls.audioTrack; }; /** Javascript calls. **/ private function _load(url : String) : void { _hls.load(url); }; private function _play() : void { _hls.stream.play(); }; private function _pause() : void { _hls.stream.pause(); }; private function _resume() : void { _hls.stream.resume(); }; private function _seek(position : Number) : void { _hls.stream.seek(position); }; private function _stop() : void { _hls.stream.close(); }; private function _volume(percent : Number) : void { _hls.stream.soundTransform = new SoundTransform(percent / 100); }; private function _setLevel(level : Number) : void { _hls.level = level; if (!isNaN(_media_position)) { _hls.stream.seek(_media_position); } }; private function _setmaxBufferLength(new_len : Number) : void { _hls.maxBufferLength = new_len; }; private function _setminBufferLength(new_len : Number) : void { _hls.minBufferLength = new_len; }; private function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void { _hls.flushLiveURLCache = flushLiveURLCache; }; private function _setstartFromLowestLevel(startFromLowestLevel : Boolean) : void { _hls.startFromLowestLevel = startFromLowestLevel; }; private function _setLogDebug(debug : Boolean) : void { Log.LOG_DEBUG_ENABLED = debug; }; private function _setLogDebug2(debug2 : Boolean) : void { Log.LOG_DEBUG2_ENABLED = debug2; }; private function _setJSURLStream(jsURLstream : Boolean) : void { if (jsURLstream) { _hls.URLstream = JSURLStream as Class; } else { _hls.URLstream = URLStream as Class; } }; private function _setAudioTrack(val : Number) : void { if (val == _hls.audioTrack) return; _hls.audioTrack = val; if (!isNaN(_media_position)) { _hls.stream.seek(_media_position); } }; /** Mouse click handler. **/ private function _clickHandler(event : MouseEvent) : void { if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) { stage.displayState = StageDisplayState.NORMAL; } else { stage.displayState = StageDisplayState.FULL_SCREEN; } }; /** StageVideo detector. **/ private function _onStageVideoState(event : StageVideoAvailabilityEvent) : void { var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE); _hls = new HLS(); _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _hls.addEventListener(HLSEvent.STATE, _stateHandler); _hls.addEventListener(HLSEvent.QUALITY_SWITCH, _switchHandler); _hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange); _hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange); if (available && stage.stageVideos.length > 0) { _stageVideo = stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _stageVideo.attachNetStream(_hls.stream); } else { _video = new Video(stage.stageWidth, stage.stageHeight); addChild(_video); _video.smoothing = true; _video.attachNetStream(_hls.stream); } }; private function _onStageResize(event : Event) : void { stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _sheet.width = stage.stageWidth; _sheet.height = stage.stageHeight; _resize(); }; private function _resize() : void { var rect : Rectangle; rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight); // resize video if (_video) { _video.width = rect.width; _video.height = rect.height; _video.x = rect.x; _video.y = rect.y; } else if (_stageVideo) { _stageVideo.viewPort = rect; } } } }
package org.mangui.chromeless { import flash.net.URLStream; import org.mangui.HLS.parsing.Level; import org.mangui.HLS.*; import org.mangui.HLS.utils.*; import flash.display.*; import flash.events.*; import flash.external.ExternalInterface; import flash.geom.Rectangle; import flash.media.Video; import flash.media.SoundTransform; import flash.media.StageVideo; import flash.media.StageVideoAvailability; import flash.utils.setTimeout; public class ChromelessPlayer extends Sprite { /** reference to the framework. **/ private var _hls : HLS; /** Sheet to place on top of the video. **/ private var _sheet : Sprite; /** Reference to the stage video element. **/ private var _stageVideo : StageVideo = null; /** Reference to the video element. **/ private var _video : Video = null; /** Video size **/ private var _videoWidth : Number = 0; private var _videoHeight : Number = 0; /** current media position */ private var _media_position : Number; /** Initialization. **/ public function ChromelessPlayer() : void { // Set stage properties stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); stage.addEventListener(Event.RESIZE, _onStageResize); // Draw sheet for catching clicks _sheet = new Sprite(); _sheet.graphics.beginFill(0x000000, 0); _sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); _sheet.addEventListener(MouseEvent.CLICK, _clickHandler); _sheet.buttonMode = true; addChild(_sheet); // Connect getters to JS. ExternalInterface.addCallback("getLevel", _getLevel); ExternalInterface.addCallback("getLevels", _getLevels); ExternalInterface.addCallback("getMetrics", _getMetrics); ExternalInterface.addCallback("getPosition", _getPosition); ExternalInterface.addCallback("getState", _getState); ExternalInterface.addCallback("getType", _getType); ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength); ExternalInterface.addCallback("getminBufferLength", _getminBufferLength); ExternalInterface.addCallback("getbufferLength", _getbufferLength); ExternalInterface.addCallback("getLogDebug", _getLogDebug); ExternalInterface.addCallback("getLogDebug2", _getLogDebug2); ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache); ExternalInterface.addCallback("getstartFromLowestLevel", _getstartFromLowestLevel); ExternalInterface.addCallback("getJSURLStream", _getJSURLStream); ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion); ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList); ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId); // Connect calls to JS. ExternalInterface.addCallback("playerLoad", _load); ExternalInterface.addCallback("playerPlay", _play); ExternalInterface.addCallback("playerPause", _pause); ExternalInterface.addCallback("playerResume", _resume); ExternalInterface.addCallback("playerSeek", _seek); ExternalInterface.addCallback("playerStop", _stop); ExternalInterface.addCallback("playerVolume", _volume); ExternalInterface.addCallback("playerSetLevel", _setLevel); ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength); ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength); ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache); ExternalInterface.addCallback("playerSetstartFromLowestLevel", _setstartFromLowestLevel); ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug); ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2); ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack); ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream); setTimeout(_pingJavascript, 50); }; /** Notify javascript the framework is ready. **/ private function _pingJavascript() : void { ExternalInterface.call("onHLSReady", ExternalInterface.objectID); }; /** Forward events from the framework. **/ private function _completeHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onComplete"); } }; private function _errorHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onError", event.message); } }; private function _fragmentHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth); } }; private function _manifestHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onManifest", event.levels[0].duration); } }; private function _mediaTimeHandler(event : HLSEvent) : void { if (ExternalInterface.available) { _media_position = event.mediatime.position; ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding); } var videoWidth : Number = _video ? _video.videoWidth : _stageVideo.videoWidth; var videoHeight : Number = _video ? _video.videoHeight : _stageVideo.videoHeight; if (videoWidth && videoHeight) { var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight; if (changed) { _videoHeight = videoHeight; _videoWidth = videoWidth; _resize(); if (ExternalInterface.available) { ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight); } } } }; private function _stateHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onState", event.state); } }; private function _switchHandler(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onSwitch", event.level); } }; private function _audioTracksListChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList()); } } private function _audioTrackChange(event : HLSEvent) : void { if (ExternalInterface.available) { ExternalInterface.call("onAudioTrackChange", event.audioTrack); } } /** Javascript getters. **/ private function _getLevel() : Number { return _hls.level; }; private function _getLevels() : Vector.<Level> { return _hls.levels; }; private function _getMetrics() : Object { return _hls.metrics; }; private function _getPosition() : Number { return _hls.position; }; private function _getState() : String { return _hls.state; }; private function _getType() : String { return _hls.type; }; private function _getbufferLength() : Number { return _hls.bufferLength; }; private function _getmaxBufferLength() : Number { return _hls.maxBufferLength; }; private function _getminBufferLength() : Number { return _hls.minBufferLength; }; private function _getflushLiveURLCache() : Boolean { return _hls.flushLiveURLCache; }; private function _getstartFromLowestLevel() : Boolean { return _hls.startFromLowestLevel; }; private function _getLogDebug() : Boolean { return Log.LOG_DEBUG_ENABLED; }; private function _getLogDebug2() : Boolean { return Log.LOG_DEBUG2_ENABLED; }; private function _getJSURLStream() : Boolean { return (_hls.URLstream is JSURLStream); }; private function _getPlayerVersion() : Number { return 2; }; private function _getAudioTrackList() : Array { var list : Array = []; var vec : Vector.<HLSAudioTrack> = _hls.audioTracks; for (var i : Object in vec) { list.push(vec[i]); } return list; }; private function _getAudioTrackId() : Number { return _hls.audioTrack; }; /** Javascript calls. **/ private function _load(url : String) : void { _hls.load(url); }; private function _play() : void { _hls.stream.play(); }; private function _pause() : void { _hls.stream.pause(); }; private function _resume() : void { _hls.stream.resume(); }; private function _seek(position : Number) : void { _hls.stream.seek(position); }; private function _stop() : void { _hls.stream.close(); }; private function _volume(percent : Number) : void { _hls.stream.soundTransform = new SoundTransform(percent / 100); }; private function _setLevel(level : Number) : void { _hls.level = level; if (!isNaN(_media_position)) { _hls.stream.seek(_media_position); } }; private function _setmaxBufferLength(new_len : Number) : void { _hls.maxBufferLength = new_len; }; private function _setminBufferLength(new_len : Number) : void { _hls.minBufferLength = new_len; }; private function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void { _hls.flushLiveURLCache = flushLiveURLCache; }; private function _setstartFromLowestLevel(startFromLowestLevel : Boolean) : void { _hls.startFromLowestLevel = startFromLowestLevel; }; private function _setLogDebug(debug : Boolean) : void { Log.LOG_DEBUG_ENABLED = debug; }; private function _setLogDebug2(debug2 : Boolean) : void { Log.LOG_DEBUG2_ENABLED = debug2; }; private function _setJSURLStream(jsURLstream : Boolean) : void { if (jsURLstream) { _hls.URLstream = JSURLStream as Class; } else { _hls.URLstream = URLStream as Class; } }; private function _setAudioTrack(val : Number) : void { if (val == _hls.audioTrack) return; _hls.audioTrack = val; if (!isNaN(_media_position)) { _hls.stream.seek(_media_position); } }; /** Mouse click handler. **/ private function _clickHandler(event : MouseEvent) : void { if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) { stage.displayState = StageDisplayState.NORMAL; } else { stage.displayState = StageDisplayState.FULL_SCREEN; } }; /** StageVideo detector. **/ private function _onStageVideoState(event : StageVideoAvailabilityEvent) : void { var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE); _hls = new HLS(); _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _hls.addEventListener(HLSEvent.STATE, _stateHandler); _hls.addEventListener(HLSEvent.QUALITY_SWITCH, _switchHandler); _hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange); _hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange); if (available && stage.stageVideos.length > 0) { _stageVideo = stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _stageVideo.attachNetStream(_hls.stream); } else { _video = new Video(stage.stageWidth, stage.stageHeight); addChild(_video); _video.smoothing = true; _video.attachNetStream(_hls.stream); } stage.removeEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState); }; private function _onStageResize(event : Event) : void { stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); _sheet.width = stage.stageWidth; _sheet.height = stage.stageHeight; _resize(); }; private function _resize() : void { var rect : Rectangle; rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight); // resize video if (_video) { _video.width = rect.width; _video.height = rect.height; _video.x = rect.x; _video.y = rect.y; } else if (_stageVideo) { _stageVideo.viewPort = rect; } } } }
fix NaN buffer reported when switching in fullscreen mode when switching to FullScreen, sometimes StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY listener is triggered. remove this listener after its first trigger to avoid reinstanciating HLS instance
HLSProviderChromeless.swf: fix NaN buffer reported when switching in fullscreen mode when switching to FullScreen, sometimes StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY listener is triggered. remove this listener after its first trigger to avoid reinstanciating HLS instance
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
d1891e4a6c6eab85c2976745978b0ab7a9938581
KeyGenerator.as
KeyGenerator.as
package dse{ import com.hurlant.crypto.prng.Random; import com.hurlant.crypto.rsa.RSAKey; import com.hurlant.util.Hex; import flash.external.ExternalInterface; import flash.utils.ByteArray; public class KeyGenerator { public static function generateKeys():void{ var exp:String = "10001"; var rsa:RSAKey = RSAKey.generate(1024, exp); ExternalInterface.call("setvalue", "publickey", rsa.n.toString()); ExternalInterface.call("setvalue", "d", rsa.d.toString()); ExternalInterface.call("setvalue", "p", rsa.p.toString()); ExternalInterface.call("setvalue", "q", rsa.q.toString()); ExternalInterface.call("setvalue", "dmp", rsa.dmp1.toString()); ExternalInterface.call("setvalue", "dmq", rsa.dmq1.toString()); ExternalInterface.call("setvalue", "qinv", rsa.coeff.toString()); var r:Random = new Random; var rankey:ByteArray = new ByteArray; var discard:ByteArray = new ByteArray; r.nextBytes(discard, 32); r.nextBytes(rankey, 32); ExternalInterface.call("setvalue", "rk", Hex.fromArray(rankey)); } } }
package dse{ import com.hurlant.crypto.Crypto; import com.hurlant.crypto.hash.IHash; import com.hurlant.crypto.prng.Random; import com.hurlant.crypto.rsa.RSAKey; import com.hurlant.util.Hex; import flash.external.ExternalInterface; import flash.utils.ByteArray; public class KeyGenerator { public static function generateKeys(passphrase:String):void{ var exp:String = "10001"; var rsa:RSAKey = RSAKey.generate(1024, exp); ExternalInterface.call("setvalue", "publickey", rsa.n.toString()); ExternalInterface.call("setvalue", "d", rsa.d.toString()); ExternalInterface.call("setvalue", "p", rsa.p.toString()); ExternalInterface.call("setvalue", "q", rsa.q.toString()); ExternalInterface.call("setvalue", "dmp", rsa.dmp1.toString()); ExternalInterface.call("setvalue", "dmq", rsa.dmq1.toString()); ExternalInterface.call("setvalue", "qinv", rsa.coeff.toString()); var r:Random = new Random; var rankey:ByteArray = new ByteArray; var discard:ByteArray = new ByteArray; //incorporate passphrase into seeding process var hash:IHash = Crypto.getHash("sha256"); var p:ByteArray = hash.hash(Hex.toArray(Hex.fromString(passphrase))); r.autoSeed(); while (p.bytesAvailable>=4) { r.seed(p.readUnsignedInt()); } r.nextBytes(discard, 1024); r.nextBytes(rankey, 32); ExternalInterface.call("setvalue", "rk", Hex.fromArray(rankey)); } } }
improve randomness of random aes key generation by seeding with passphrase hash
improve randomness of random aes key generation by seeding with passphrase hash
ActionScript
mit
snoble/dse
06f82d68fcf627caac03c57e1a6e429b0686c7a6
dolly-framework/src/main/actionscript/dolly/utils/PropertyUtil.as
dolly-framework/src/main/actionscript/dolly/utils/PropertyUtil.as
package dolly.utils { import dolly.core.dolly_internal; import mx.collections.ArrayCollection; import mx.collections.ArrayList; use namespace dolly_internal; public class PropertyUtil { dolly_internal static function copyArray(sourceObj:*, targetObj:*, propertyName:String):void { targetObj[propertyName] = sourceObj[propertyName].slice(); } dolly_internal static function copyArrayList(sourceObj:*, targetObj:*, propertyName:String):void { targetObj[propertyName] = sourceObj[propertyName] ? new ArrayList(sourceObj[propertyName].source) : new ArrayList(); } dolly_internal static function copyArrayCollection(targetObj:*, propertyName:String, sourceProperty:*):void { const arrayCollection:ArrayCollection = (sourceProperty as ArrayCollection); targetObj[propertyName] = arrayCollection.source ? new ArrayCollection(arrayCollection.source.slice()) : new ArrayCollection(); } private static function copyObject(targetObj:*, propertyName:String, sourceProperty:*):void { targetObj[propertyName] = sourceProperty; } public static function copyProperty(sourceObj:*, targetObj:*, propertyName:String):void { const sourceProperty:* = sourceObj[propertyName]; if (sourceProperty is Array) { copyArray(sourceObj, targetObj, propertyName); return; } if (sourceProperty is ArrayList) { copyArrayList(sourceObj, targetObj, propertyName); return; } if (sourceProperty is ArrayCollection) { copyArrayCollection(targetObj, propertyName, sourceProperty); return; } copyObject(targetObj, propertyName, sourceProperty); } public static function cloneProperty(sourceObj:*, targetObj:*, propertyName:String):void { const sourceProperty:* = sourceObj[propertyName]; if (sourceProperty is Array) { copyArray(sourceObj, targetObj, propertyName); return; } if (sourceProperty is ArrayList) { copyArrayList(sourceObj, targetObj, propertyName); return; } if (sourceProperty is ArrayCollection) { copyArrayCollection(targetObj, propertyName, sourceProperty); return; } copyObject(targetObj, propertyName, sourceProperty); } } }
package dolly.utils { import dolly.core.dolly_internal; import mx.collections.ArrayCollection; import mx.collections.ArrayList; use namespace dolly_internal; public class PropertyUtil { dolly_internal static function copyArray(sourceObj:*, targetObj:*, propertyName:String):void { targetObj[propertyName] = sourceObj[propertyName].slice(); } dolly_internal static function copyArrayList(sourceObj:*, targetObj:*, propertyName:String):void { targetObj[propertyName] = sourceObj[propertyName] ? new ArrayList(sourceObj[propertyName].source) : new ArrayList(); } dolly_internal static function copyArrayCollection(sourceObj:*, targetObj:*, propertyName:String):void { const arrayCollection:ArrayCollection = sourceObj[propertyName]; targetObj[propertyName] = arrayCollection.source ? new ArrayCollection(arrayCollection.source.slice()) : new ArrayCollection(); } private static function copyObject(targetObj:*, propertyName:String, sourceProperty:*):void { targetObj[propertyName] = sourceProperty; } public static function copyProperty(sourceObj:*, targetObj:*, propertyName:String):void { const sourceProperty:* = sourceObj[propertyName]; if (sourceProperty is Array) { copyArray(sourceObj, targetObj, propertyName); return; } if (sourceProperty is ArrayList) { copyArrayList(sourceObj, targetObj, propertyName); return; } if (sourceProperty is ArrayCollection) { copyArrayCollection(sourceObj, targetObj, propertyName); return; } copyObject(targetObj, propertyName, sourceProperty); } public static function cloneProperty(sourceObj:*, targetObj:*, propertyName:String):void { const sourceProperty:* = sourceObj[propertyName]; if (sourceProperty is Array) { copyArray(sourceObj, targetObj, propertyName); return; } if (sourceProperty is ArrayList) { copyArrayList(sourceObj, targetObj, propertyName); return; } if (sourceProperty is ArrayCollection) { copyArrayCollection(sourceObj, targetObj, propertyName); return; } copyObject(targetObj, propertyName, sourceProperty); } } }
Change signature of PropertyUtil.copyArrayCollection() method.
Change signature of PropertyUtil.copyArrayCollection() method.
ActionScript
mit
Yarovoy/dolly
de5baab0e1cb4abaac893fb2ae985617763689be
src/aerys/minko/render/geometry/stream/IndexStream.as
src/aerys/minko/render/geometry/stream/IndexStream.as
package aerys.minko.render.geometry.stream { import aerys.minko.ns.minko_stream; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.type.Signal; import flash.utils.ByteArray; import flash.utils.Endian; public final class IndexStream { use namespace minko_stream; minko_stream var _data : ByteArray; minko_stream var _localDispose : Boolean; private var _usage : uint; private var _resource : IndexBuffer3DResource; private var _length : uint; private var _locked : Boolean; private var _changed : Signal; public function get usage() : uint { return _usage; } public function get resource() : IndexBuffer3DResource { return _resource; } public function get length() : uint { return _length; } public function set length(value : uint) : void { _data.length = value << 1; invalidate(); } public function get changed() : Signal { return _changed; } public function IndexStream(usage : uint, data : ByteArray = null, length : uint = 0) { super(); initialize(data, length, usage); } minko_stream function invalidate() : void { _data.position = 0; _length = _data.length >>> 1; if (!_locked) _changed.execute(this); } private function initialize(data : ByteArray, length : uint, usage : uint) : void { _changed = new Signal('IndexStream.changed'); _usage = usage; _resource = new IndexBuffer3DResource(this); _data = new ByteArray(); _data.endian = Endian.LITTLE_ENDIAN; if (data) { if (data.endian != Endian.LITTLE_ENDIAN) throw new Error('Endianness must be Endian.LITTLE_ENDIAN.'); if (length == 0) length = data.bytesAvailable; if (length % 6 != 0) throw new Error(); data.readBytes(_data, 0, length); } else { _data = dummyData(length); } _data.position = 0; invalidate(); } public function get(index : uint) : uint { var value : uint = 0; checkReadUsage(this); _data.position = index << 1; value = _data.readUnsignedShort(); _data.position = 0; return value; } public function set(index : uint, value : uint) : void { checkWriteUsage(this); _data.position = index << 1; _data.writeShort(value); _data.position = 0; invalidate(); } public function deleteTriangle(triangleIndex : uint) : void { checkWriteUsage(this); _data.position = 0; _data.writeBytes(_data, triangleIndex * 12, 12); _data.length -= 12; _data.position = 0; invalidate(); } public function clone(usage : uint = 0) : IndexStream { return new IndexStream(usage || _usage, _data); } public function toString() : String { return _data.toString(); } public function concat(indexStream : IndexStream, firstIndex : uint = 0, count : uint = 0, indexOffset : uint = 0) : IndexStream { checkReadUsage(indexStream); checkWriteUsage(this); pushBytes(indexStream._data, firstIndex, count, indexOffset); indexStream._data.position = 0; return this; } public function pushBytes(bytes : ByteArray, firstIndex : uint = 0, count : uint = 0, indexOffset : uint = 0) : IndexStream { count ||= bytes.length >>> 1; _data.position = _data.length; if (indexOffset == 0) _data.writeBytes(bytes, firstIndex << 1, count << 1); else { bytes.position = firstIndex << 1; for (var i : uint = 0; i < count; ++i) _data.writeShort(bytes.readUnsignedShort() + indexOffset); } _data.position = 0; bytes.position = (firstIndex + count) << 1; invalidate(); return this; } public function pushVector(indices : Vector.<uint>, firstIndex : uint = 0, count : uint = 0, offset : uint = 0) : IndexStream { checkWriteUsage(this); var numIndices : int = _data.length; count ||= indices.length; _data.position = _data.length; for (var i : int = 0; i < count; ++i) _data.writeShort(indices[int(firstIndex + i)] + offset); _data.position = 0; invalidate(); return this; } public function pushTriangle(index1 : uint, index2 : uint, index3 : uint) : IndexStream { return setTriangle(length * 3, index1, index2, index3); } public function setTriangle(triangleIndex : uint, index1 : uint, index2 : uint, index3 : uint) : IndexStream { _data.position = triangleIndex << 1; _data.writeShort(index1); _data.writeShort(index2); _data.writeShort(index3); _data.position = 0; invalidate(); return this; } public function disposeLocalData(waitForUpload : Boolean = true) : void { if (waitForUpload && _length != resource.numIndices) _localDispose = true; else { _data = null; _usage = StreamUsage.STATIC; } } public function dispose() : void { _resource.dispose(); } public function lock() : ByteArray { checkReadUsage(this); _data.position = 0; _locked = true; return _data; } public function unlock(hasChanged : Boolean = true) : void { _data.position = 0; if (hasChanged) invalidate(); } private static function checkReadUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.READ)) throw new Error( 'Unable to read from vertex stream: stream usage is not set to StreamUsage.READ.' ); } private static function checkWriteUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.WRITE)) throw new Error( 'Unable to write in vertex stream: stream usage is not set to StreamUsage.WRITE.' ); } public static function dummyData(size : uint, offset : uint = 0) : ByteArray { var indices : ByteArray = new ByteArray(); indices.endian = Endian.LITTLE_ENDIAN; for (var i : int = 0; i < size; ++i) indices.writeShort(i + offset); indices.position = 0; return indices; } public static function fromVector(usage : uint, data : Vector.<uint>) : IndexStream { var stream : IndexStream = new IndexStream(usage); var numIndices : uint = data.length; for (var i : uint = 0; i < numIndices; ++i) stream._data.writeShort(data[i]); stream._data.position = 0; stream._length = numIndices; return stream; } } }
package aerys.minko.render.geometry.stream { import aerys.minko.ns.minko_stream; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.type.Signal; import flash.utils.ByteArray; import flash.utils.Endian; public final class IndexStream { use namespace minko_stream; minko_stream var _data : ByteArray; minko_stream var _localDispose : Boolean; private var _usage : uint; private var _resource : IndexBuffer3DResource; private var _length : uint; private var _locked : Boolean; private var _changed : Signal; public function get usage() : uint { return _usage; } public function get resource() : IndexBuffer3DResource { return _resource; } public function get length() : uint { return _length; } public function set length(value : uint) : void { _data.length = value << 1; invalidate(); } public function get changed() : Signal { return _changed; } public function IndexStream(usage : uint, data : ByteArray = null, length : uint = 0) { super(); initialize(data, length, usage); } minko_stream function invalidate() : void { _data.position = 0; _length = _data.length >>> 1; if (_length % 3 != 0) throw new Error('Invalid size'); if (!_locked) _changed.execute(this); } private function initialize(data : ByteArray, length : uint, usage : uint) : void { _changed = new Signal('IndexStream.changed'); _usage = usage; _resource = new IndexBuffer3DResource(this); _data = new ByteArray(); _data.endian = Endian.LITTLE_ENDIAN; if (data) { if (data.endian != Endian.LITTLE_ENDIAN) throw new Error('Endianness must be Endian.LITTLE_ENDIAN.'); if (length == 0) length = data.bytesAvailable; if (length % 6 != 0) throw new Error('Invalid size'); data.readBytes(_data, 0, length); } else { _data = dummyData(length); } _data.position = 0; invalidate(); } public function get(index : uint) : uint { var value : uint = 0; checkReadUsage(this); _data.position = index << 1; value = _data.readUnsignedShort(); _data.position = 0; return value; } public function set(index : uint, value : uint) : void { checkWriteUsage(this); _data.position = index << 1; _data.writeShort(value); _data.position = 0; invalidate(); } public function deleteTriangle(triangleIndex : uint) : void { checkWriteUsage(this); _data.position = 0; _data.writeBytes(_data, triangleIndex * 12, 12); _data.length -= 12; _data.position = 0; invalidate(); } public function clone(usage : uint = 0) : IndexStream { return new IndexStream(usage || _usage, _data); } public function toString() : String { return _data.toString(); } public function concat(indexStream : IndexStream, firstIndex : uint = 0, count : uint = 0, indexOffset : uint = 0) : IndexStream { checkReadUsage(indexStream); checkWriteUsage(this); pushBytes(indexStream._data, firstIndex, count, indexOffset); indexStream._data.position = 0; return this; } public function pushBytes(bytes : ByteArray, firstIndex : uint = 0, count : uint = 0, indexOffset : uint = 0) : IndexStream { count ||= bytes.length >>> 1; _data.position = _data.length; if (indexOffset == 0) _data.writeBytes(bytes, firstIndex << 1, count << 1); else { bytes.position = firstIndex << 1; for (var i : uint = 0; i < count; ++i) _data.writeShort(bytes.readUnsignedShort() + indexOffset); } _data.position = 0; bytes.position = (firstIndex + count) << 1; invalidate(); return this; } public function pushVector(indices : Vector.<uint>, firstIndex : uint = 0, count : uint = 0, offset : uint = 0) : IndexStream { checkWriteUsage(this); var numIndices : int = _data.length; count ||= indices.length; _data.position = _data.length; for (var i : int = 0; i < count; ++i) _data.writeShort(indices[int(firstIndex + i)] + offset); _data.position = 0; invalidate(); return this; } public function pushTriangle(index1 : uint, index2 : uint, index3 : uint) : IndexStream { return setTriangle(length * 3, index1, index2, index3); } public function setTriangle(triangleIndex : uint, index1 : uint, index2 : uint, index3 : uint) : IndexStream { _data.position = triangleIndex << 1; _data.writeShort(index1); _data.writeShort(index2); _data.writeShort(index3); _data.position = 0; invalidate(); return this; } public function disposeLocalData(waitForUpload : Boolean = true) : void { if (waitForUpload && _length != resource.numIndices) _localDispose = true; else { _data = null; _usage = StreamUsage.STATIC; } } public function dispose() : void { _resource.dispose(); } public function lock() : ByteArray { checkReadUsage(this); _data.position = 0; _locked = true; return _data; } public function unlock(hasChanged : Boolean = true) : void { _data.position = 0; if (hasChanged) invalidate(); } private static function checkReadUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.READ)) throw new Error( 'Unable to read from vertex stream: stream usage is not set to StreamUsage.READ.' ); } private static function checkWriteUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.WRITE)) throw new Error( 'Unable to write in vertex stream: stream usage is not set to StreamUsage.WRITE.' ); } public static function dummyData(size : uint, offset : uint = 0) : ByteArray { var indices : ByteArray = new ByteArray(); indices.endian = Endian.LITTLE_ENDIAN; for (var i : int = 0; i < size; ++i) indices.writeShort(i + offset); indices.position = 0; return indices; } public static function fromVector(usage : uint, data : Vector.<uint>) : IndexStream { var stream : IndexStream = new IndexStream(usage); var numIndices : uint = data.length; for (var i : uint = 0; i < numIndices; ++i) stream._data.writeShort(data[i]); stream._data.position = 0; stream._length = numIndices; return stream; } } }
check IndexStream.length in IndexStream.invalidate() in order to fail early
check IndexStream.length in IndexStream.invalidate() in order to fail early
ActionScript
mit
aerys/minko-as3
57eb4106f19384977c69f18887d8c7a5f8ec465f
dolly-framework/src/test/resources/dolly/data/CloneableSubclass.as
dolly-framework/src/test/resources/dolly/data/CloneableSubclass.as
package dolly.data { [Cloneable] public class CloneableSubclass extends CloneableClass { private var _writableField2:String; public var property4:String; public var property5:String; public function CloneableSubclass() { super(); } public function get writableField2():String { return _writableField2; } public function set writableField2(value:String):void { _writableField2 = value; } } }
package dolly.data { [Cloneable] public class CloneableSubclass extends CloneableClass { public static var staticProperty1:String; public static var staticProperty2:String; public static var staticProperty3:String; private var _writableField2:String; public var property4:String; public var property5:String; public function CloneableSubclass() { super(); } public function get writableField2():String { return _writableField2; } public function set writableField2(value:String):void { _writableField2 = value; } } }
Add static properties to CloneableSubclass.
Add static properties to CloneableSubclass.
ActionScript
mit
Yarovoy/dolly
5b12abbf701a11354796345c407067391b1367af
src/com/esri/builder/supportClasses/IconFetchEvent.as
src/com/esri/builder/supportClasses/IconFetchEvent.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.supportClasses { import flash.events.Event; public class IconFetchEvent extends Event { public static const FETCH_COMPLETE:String = "FETCH_COMPLETE"; private var _iconPath:String; public function IconFetchEvent(type:String, iconPath:String) { super(type, false, false); _iconPath = iconPath; } public function get iconPath():String { return _iconPath; } override public function clone():Event { return new IconFetchEvent(type, _iconPath); } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.supportClasses { import flash.events.Event; public class IconFetchEvent extends Event { public static const FETCH_COMPLETE:String = "fetchComplete"; private var _iconPath:String; public function IconFetchEvent(type:String, iconPath:String) { super(type, false, false); _iconPath = iconPath; } public function get iconPath():String { return _iconPath; } override public function clone():Event { return new IconFetchEvent(type, _iconPath); } } }
Change IconFetchEvent.COMPLETE value to camel case.
Change IconFetchEvent.COMPLETE value to camel case.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
e35b5842681b9ad356a5d40a14f6a4399f2baf04
src/aerys/minko/type/clone/CloneOptions.as
src/aerys/minko/type/clone/CloneOptions.as
package aerys.minko.type.clone { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.AnimationController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.controller.mesh.VisibilityController; import aerys.minko.scene.controller.mesh.skinning.SkinningController; public class CloneOptions { private var _clonedControllerTypes : Vector.<Class> = new <Class>[]; private var _ignoredControllerTypes : Vector.<Class> = new <Class>[]; private var _reassignedControllerTypes : Vector.<Class> = new <Class>[]; private var _defaultControllerAction : uint = ControllerCloneAction.REASSIGN; public function get defaultControllerAction() : uint { return _defaultControllerAction; } public function set defaultControllerAction(v : uint) : void { if (v != ControllerCloneAction.CLONE && v != ControllerCloneAction.IGNORE && v != ControllerCloneAction.REASSIGN) throw new Error('Unknown action type.'); _defaultControllerAction = v; } public function CloneOptions() { } public static function get defaultOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._clonedControllerTypes.push( AnimationController, SkinningController ); cloneOptions._ignoredControllerTypes.push( VisibilityController, CameraController, TransformController ); cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN; return cloneOptions; } public static function get cloneAllOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._ignoredControllerTypes.push(VisibilityController, CameraController); cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE; return cloneOptions; } public function addControllerAction(controllerClass : Class, action : uint) : void { switch (action) { case ControllerCloneAction.CLONE: _clonedControllerTypes.push(controllerClass); break; case ControllerCloneAction.IGNORE: _ignoredControllerTypes.push(controllerClass); break; case ControllerCloneAction.REASSIGN: _reassignedControllerTypes.push(controllerClass); break; default: throw new Error('Unknown action type.'); } } public function removeControllerAction(controllerClass : Class) : void { throw new Error('Implement me.'); } public function getActionForController(controller : AbstractController) : uint { var numControllersToClone : uint = _clonedControllerTypes.length; var numControllersToIgnore : uint = _ignoredControllerTypes.length; var numControllersToReassign : uint = _reassignedControllerTypes.length; var controllerId : uint; for (controllerId = 0; controllerId < numControllersToClone; ++controllerId) if (controller is _clonedControllerTypes[controllerId]) return ControllerCloneAction.CLONE; for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId) if (controller is _ignoredControllerTypes[controllerId]) return ControllerCloneAction.IGNORE; for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId) if (controller is _reassignedControllerTypes[controllerId]) return ControllerCloneAction.REASSIGN; return _defaultControllerAction; } } }
package aerys.minko.type.clone { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.AnimationController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.controller.mesh.VisibilityController; import aerys.minko.scene.controller.mesh.skinning.SkinningController; public class CloneOptions { private var _clonedControllerTypes : Vector.<Class> = new <Class>[]; private var _ignoredControllerTypes : Vector.<Class> = new <Class>[]; private var _reassignedControllerTypes : Vector.<Class> = new <Class>[]; private var _defaultControllerAction : uint = ControllerCloneAction.REASSIGN; public function get defaultControllerAction() : uint { return _defaultControllerAction; } public function set defaultControllerAction(v : uint) : void { if (v != ControllerCloneAction.CLONE && v != ControllerCloneAction.IGNORE && v != ControllerCloneAction.REASSIGN) throw new Error('Unknown action type.'); _defaultControllerAction = v; } public function CloneOptions() { } public static function get defaultOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._clonedControllerTypes.push( AnimationController, SkinningController ); cloneOptions._ignoredControllerTypes.push( VisibilityController, CameraController, TransformController ); cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN; return cloneOptions; } public static function get cloneAllOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._ignoredControllerTypes.push( VisibilityController, CameraController, TransformController ); cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE; return cloneOptions; } public function addControllerAction(controllerClass : Class, action : uint) : void { switch (action) { case ControllerCloneAction.CLONE: _clonedControllerTypes.push(controllerClass); break; case ControllerCloneAction.IGNORE: _ignoredControllerTypes.push(controllerClass); break; case ControllerCloneAction.REASSIGN: _reassignedControllerTypes.push(controllerClass); break; default: throw new Error('Unknown action type.'); } } public function removeControllerAction(controllerClass : Class) : void { throw new Error('Implement me.'); } public function getActionForController(controller : AbstractController) : uint { var numControllersToClone : uint = _clonedControllerTypes.length; var numControllersToIgnore : uint = _ignoredControllerTypes.length; var numControllersToReassign : uint = _reassignedControllerTypes.length; var controllerId : uint; for (controllerId = 0; controllerId < numControllersToClone; ++controllerId) if (controller is _clonedControllerTypes[controllerId]) return ControllerCloneAction.CLONE; for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId) if (controller is _ignoredControllerTypes[controllerId]) return ControllerCloneAction.IGNORE; for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId) if (controller is _reassignedControllerTypes[controllerId]) return ControllerCloneAction.REASSIGN; return _defaultControllerAction; } } }
fix CloneOptions.cloneAllOptions to exclude the TransformController from the list of controllers to clone
fix CloneOptions.cloneAllOptions to exclude the TransformController from the list of controllers to clone
ActionScript
mit
aerys/minko-as3
fad4ebd088a6f865abc28bab25adbdbb8002a306
src/modules/Print/PrintModel.as
src/modules/Print/PrintModel.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package modules.Print { import com.esri.builder.supportClasses.URLUtil; import com.esri.builder.model.Model; import modules.IWidgetModel; import mx.resources.ResourceManager; [Bindable] public final class PrintModel implements IWidgetModel { public static const DEFAULT_DPI:Number = 96; private var _taskURL:String = Model.instance.printTaskURL; public function get taskURL():String { return _taskURL; } public function set taskURL(value:String):void { _taskURL = URLUtil.encode(value); } private var _dpi:Number = DEFAULT_DPI; public function get dpi():Number { return _dpi; } public function set dpi(value:Number):void { _dpi = isNaN(value) ? DEFAULT_DPI : value; } public var title:String = ResourceManager.getInstance().getString('BuilderStrings', 'print.defaultTitle'); public var subtitle:String = ResourceManager.getInstance().getString('BuilderStrings', 'print.defaultSubtitle'); public var copyright:String = ResourceManager.getInstance().getString('BuilderStrings', 'print.defaultCopyright'); public var author:String = ""; public var useScale:Boolean = true; public var submitLabel:String; public var defaultFormat:String = ""; public var defaultLayoutTemplate:String = ""; public var isTitleVisible:Boolean = true; public var isCopyrightVisible:Boolean = true; public var isAuthorVisible:Boolean = true; public var willUseExportWebMap:Boolean = false; public var useProxy:Boolean; public function importXML(doc:XML):void { if (doc.taskurl[0]) { taskURL = doc.taskurl; willUseExportWebMap = true; } if (doc.title[0]) { title = doc.title; isTitleVisible = (doc.title.@visible[0] != "false"); } if (doc.author[0]) { author = doc.author; isAuthorVisible = (doc.author.@visible[0] != "false"); } if (doc.subtitle[0]) { subtitle = doc.subtitle; } if (doc.copyright[0]) { copyright = doc.copyright; isCopyrightVisible = (doc.copyright.@visible[0] != "false"); } if (doc.usescale[0]) { useScale = (doc.usescale.@visible == 'true'); } if (doc.formats.@defaultvalue[0]) { defaultFormat = doc.formats.@defaultvalue[0]; } if (doc.layouttemplates.@defaultvalue[0]) { defaultLayoutTemplate = doc.layouttemplates.@defaultvalue[0]; } if(doc.useproxy[0] == "true") { useProxy = true; } if (doc.dpi[0]) { dpi = parseFloat(doc.dpi[0]); } } public function exportXML():XML { if (willUseExportWebMap) { return createExportWebMapXML(); } else { return createPrintScreenXML(); } } private function createPrintScreenXML():XML { var configXML:XML = <configuration/>; if (title) { configXML.appendChild(<title>{title}</title>); } if (copyright) { configXML.appendChild(<copyright>{copyright}</copyright>); } if (subtitle) { configXML.appendChild(<subtitle>{subtitle}</subtitle>); } return configXML; } private function createExportWebMapXML():XML { var configXML:XML = <configuration/>; configXML.appendChild(<taskurl>{taskURL}</taskurl>); var titleXML:XML = <title>{title}</title>; titleXML.@visible = isTitleVisible; configXML.appendChild(titleXML); var copyrightXML:XML = <copyright>{copyright}</copyright>; copyrightXML.@visible = isCopyrightVisible; configXML.appendChild(copyrightXML); var authorXML:XML = <author>{author}</author>; authorXML.@visible = isAuthorVisible; configXML.appendChild(authorXML); configXML.appendChild(<dpi>{dpi}</dpi>); if (useScale) { configXML.appendChild(<usescale visible="true"/>); } if (defaultFormat) { configXML.appendChild(<formats defaultvalue={defaultFormat}/>) } if (defaultLayoutTemplate) { configXML.appendChild(<layouttemplates defaultvalue={defaultLayoutTemplate}/>) } if(useProxy) { configXML.appendChild(<useproxy>{useProxy}</useproxy>); } return configXML; } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package modules.Print { import com.esri.builder.model.Model; import com.esri.builder.supportClasses.URLUtil; import modules.IWidgetModel; import mx.resources.ResourceManager; [Bindable] public final class PrintModel implements IWidgetModel { public static const DEFAULT_DPI:Number = 96; private var _taskURL:String = Model.instance.printTaskURL; public function get taskURL():String { return _taskURL; } public function set taskURL(value:String):void { _taskURL = URLUtil.encode(value); } private var _dpi:Number = DEFAULT_DPI; public function get dpi():Number { return _dpi; } public function set dpi(value:Number):void { _dpi = isNaN(value) ? DEFAULT_DPI : value; } public var title:String = ResourceManager.getInstance().getString('BuilderStrings', 'print.defaultTitle'); public var subtitle:String = ResourceManager.getInstance().getString('BuilderStrings', 'print.defaultSubtitle'); public var copyright:String = ResourceManager.getInstance().getString('BuilderStrings', 'print.defaultCopyright'); public var author:String = ""; public var useScale:Boolean = true; public var submitLabel:String; public var defaultFormat:String = ""; public var defaultLayoutTemplate:String = ""; public var isTitleVisible:Boolean = true; public var isCopyrightVisible:Boolean = true; public var isAuthorVisible:Boolean = true; public var willUseExportWebMap:Boolean = false; public var useProxy:Boolean; public function importXML(doc:XML):void { if (doc.taskurl[0]) { taskURL = doc.taskurl; willUseExportWebMap = true; } if (doc.title[0]) { title = doc.title; isTitleVisible = (doc.title.@visible[0] != "false"); } if (doc.author[0]) { author = doc.author; isAuthorVisible = (doc.author.@visible[0] != "false"); } if (doc.subtitle[0]) { subtitle = doc.subtitle; } if (doc.copyright[0]) { copyright = doc.copyright; isCopyrightVisible = (doc.copyright.@visible[0] != "false"); } if (doc.usescale[0]) { useScale = (doc.usescale.@visible == 'true'); } if (doc.formats.@defaultvalue[0]) { defaultFormat = doc.formats.@defaultvalue[0]; } if (doc.layouttemplates.@defaultvalue[0]) { defaultLayoutTemplate = doc.layouttemplates.@defaultvalue[0]; } if (doc.useproxy[0] == "true") { useProxy = true; } if (doc.dpi[0]) { dpi = parseFloat(doc.dpi[0]); } } public function exportXML():XML { if (willUseExportWebMap) { return createExportWebMapXML(); } else { return createPrintScreenXML(); } } private function createPrintScreenXML():XML { var configXML:XML = <configuration/>; if (title) { configXML.appendChild(<title>{title}</title>); } if (copyright) { configXML.appendChild(<copyright>{copyright}</copyright>); } if (subtitle) { configXML.appendChild(<subtitle>{subtitle}</subtitle>); } return configXML; } private function createExportWebMapXML():XML { var configXML:XML = <configuration/>; configXML.appendChild(<taskurl>{taskURL}</taskurl>); var titleXML:XML = <title>{title}</title>; titleXML.@visible = isTitleVisible; configXML.appendChild(titleXML); var copyrightXML:XML = <copyright>{copyright}</copyright>; copyrightXML.@visible = isCopyrightVisible; configXML.appendChild(copyrightXML); var authorXML:XML = <author>{author}</author>; authorXML.@visible = isAuthorVisible; configXML.appendChild(authorXML); configXML.appendChild(<dpi>{dpi}</dpi>); if (useScale) { configXML.appendChild(<usescale visible="true"/>); } if (defaultFormat) { configXML.appendChild(<formats defaultvalue={defaultFormat}/>) } if (defaultLayoutTemplate) { configXML.appendChild(<layouttemplates defaultvalue={defaultLayoutTemplate}/>) } if (useProxy) { configXML.appendChild(<useproxy>{useProxy}</useproxy>); } return configXML; } } }
Apply formatting.
Apply formatting.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
30007f75cd8711a7965d9e238653009c656d5fb0
frameworks/projects/Core/as/src/org/apache/flex/core/Application.as
frameworks/projects/Core/as/src/org/apache/flex/core/Application.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.display.DisplayObject; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageQuality; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.system.ApplicationDomain; import flash.utils.getQualifiedClassName; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.events.MouseEvent; import org.apache.flex.events.utils.MouseEventConverter; import org.apache.flex.utils.MXMLDataInterpreter; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched at startup. Attributes and sub-instances of * the MXML document have been created and assigned. * The component lifecycle is different * than the Flex SDK. There is no creationComplete event. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="initialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="viewChanged", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="applicationComplete", type="org.apache.flex.events.Event")] /** * The Application class is the main class and entry point for a FlexJS * application. This Application class is different than the * Flex SDK's mx:Application or spark:Application in that it does not contain * user interface elements. Those UI elements go in the views. This * Application class expects there to be a main model, a controller, and * an initial view. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Application extends Sprite implements IStrand, IFlexInfo, IParent, IEventDispatcher { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function Application() { super(); if (stage) { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; // should be opt-in //stage.quality = StageQuality.HIGH_16X16_LINEAR; } loaderInfo.addEventListener(flash.events.Event.INIT, initHandler); } /** * The document property is used to provide * a property lookup context for non-display objects. * For Application, it points to itself. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var document:Object = this; private function initHandler(event:flash.events.Event):void { if (model is IBead) addBead(model as IBead); if (controller is IBead) addBead(controller as IBead); MouseEventConverter.setupAllConverters(stage); for each (var bead:IBead in beads) addBead(bead); dispatchEvent(new org.apache.flex.events.Event("beadsAdded")); MXMLDataInterpreter.generateMXMLInstances(this, null, MXMLDescriptor); dispatchEvent(new org.apache.flex.events.Event("initialize")); if (initialView) { initialView.applicationModel = model; if (isNaN(initialView.explicitWidth)) initialView.width = stage.stageWidth; if (isNaN(initialView.explicitHeight)) initialView.height = stage.stageHeight; this.addElement(initialView); var bgColor:Object = ValuesManager.valuesImpl.getValue(this, "background-color"); if (bgColor != null) { var backgroundColor:uint = ValuesManager.valuesImpl.convertColor(bgColor); graphics.beginFill(backgroundColor); graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); graphics.endFill(); } dispatchEvent(new org.apache.flex.events.Event("viewChanged")); } dispatchEvent(new org.apache.flex.events.Event("applicationComplete")); } /** * The org.apache.flex.core.IValuesImpl that will * determine the default values and other values * for the application. The most common choice * is org.apache.flex.core.SimpleCSSValuesImpl. * * @see org.apache.flex.core.SimpleCSSValuesImpl * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set valuesImpl(value:IValuesImpl):void { ValuesManager.valuesImpl = value; ValuesManager.valuesImpl.init(this); } /** * The initial view. * * @see org.apache.flex.core.ViewBase * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var initialView:ViewBase; /** * The data model (for the initial view). * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var model:Object; /** * The controller. The controller typically watches * the UI for events and updates the model accordingly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var controller:Object; /** * An array of data that describes the MXML attributes * and tags in an MXML document. This data is usually * decoded by an MXMLDataInterpreter * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get MXMLDescriptor():Array { return null; } /** * An method called by the compiler's generated * code to kick off the setting of MXML attribute * values and instantiation of child tags. * * The call has to be made in the generated code * in order to ensure that the constructors have * completed first. * * @param data The encoded data representing the * MXML attributes. * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function generateMXMLAttributes(data:Array):void { MXMLDataInterpreter.generateMXMLProperties(this, data); } /** * The array property that is used to add additional * beads to an MXML tag. From ActionScript, just * call addBead directly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var beads:Array; private var _beads:Vector.<IBead>; /** * @copy org.apache.flex.core.IStrand#addBead() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addBead(bead:IBead):void { if (!_beads) _beads = new Vector.<IBead>; _beads.push(bead); bead.strand = this; } /** * @copy org.apache.flex.core.IStrand#getBeadByType() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getBeadByType(classOrInterface:Class):IBead { for each (var bead:IBead in _beads) { if (bead is classOrInterface) return bead; } return null; } /** * @copy org.apache.flex.core.IStrand#removeBead() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeBead(value:IBead):IBead { var n:int = _beads.length; for (var i:int = 0; i < n; i++) { var bead:IBead = _beads[i]; if (bead == value) { _beads.splice(i, 1); return bead; } } return null; } private var _info:Object; /** * An Object containing information generated * by the compiler that is useful at startup time. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function info():Object { if (!_info) { var mainClassName:String = getQualifiedClassName(this); var initClassName:String = "_" + mainClassName + "_FlexInit"; var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class; _info = c.info(); } return _info; } /** * @copy org.apache.flex.core.IParent#addElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addElement(c:Object, dispatchEvent:Boolean = true):void { if (c is IUIBase) { addChild(IUIBase(c).element as DisplayObject); IUIBase(c).addedToParent(); } else addChild(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#addElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addElementAt(c:Object, index:int, dispatchEvent:Boolean = true):void { if (c is IUIBase) { addChildAt(IUIBase(c).element as DisplayObject, index); IUIBase(c).addedToParent(); } else addChildAt(c as DisplayObject, index); } /** * @copy org.apache.flex.core.IParent#getElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getElementAt(index:int):Object { return getChildAt(index); } /** * @copy org.apache.flex.core.IParent#getElementIndex() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getElementIndex(c:Object):int { if (c is IUIBase) return getChildIndex(IUIBase(c).element as DisplayObject); return getChildIndex(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#removeElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeElement(c:Object, dispatchEvent:Boolean = true):void { if (c is IUIBase) { removeChild(IUIBase(c).element as DisplayObject); } else removeChild(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#numElements * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get numElements():int { return numChildren; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.display.DisplayObject; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageQuality; import flash.display.StageScaleMode; import flash.events.Event; import flash.system.ApplicationDomain; import flash.utils.getQualifiedClassName; import org.apache.flex.events.Event; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.events.MouseEvent; import org.apache.flex.events.utils.MouseEventConverter; import org.apache.flex.utils.MXMLDataInterpreter; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched at startup. Attributes and sub-instances of * the MXML document have been created and assigned. * The component lifecycle is different * than the Flex SDK. There is no creationComplete event. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="initialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup before the instances get created. * Beads can call preventDefault and defer initialization. * This event will be dispatched on every frame until no * listeners call preventDefault(), then the initialize() * method will be called. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="preinitialize", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="viewChanged", type="org.apache.flex.events.Event")] /** * Dispatched at startup after the initial view has been * put on the display list. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ [Event(name="applicationComplete", type="org.apache.flex.events.Event")] /** * The Application class is the main class and entry point for a FlexJS * application. This Application class is different than the * Flex SDK's mx:Application or spark:Application in that it does not contain * user interface elements. Those UI elements go in the views. This * Application class expects there to be a main model, a controller, and * an initial view. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Application extends Sprite implements IStrand, IFlexInfo, IParent, IEventDispatcher { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function Application() { super(); if (stage) { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; // should be opt-in //stage.quality = StageQuality.HIGH_16X16_LINEAR; } loaderInfo.addEventListener(flash.events.Event.INIT, initHandler); } /** * The document property is used to provide * a property lookup context for non-display objects. * For Application, it points to itself. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var document:Object = this; private function initHandler(event:flash.events.Event):void { if (model is IBead) addBead(model as IBead); if (controller is IBead) addBead(controller as IBead); MouseEventConverter.setupAllConverters(stage); for each (var bead:IBead in beads) addBead(bead); dispatchEvent(new org.apache.flex.events.Event("beadsAdded")); if (dispatchEvent(new org.apache.flex.events.Event("preinitialize", false, true))) initialize(); else addEventListener(flash.events.Event.ENTER_FRAME, enterFrameHandler); } private function enterFrameHandler(event:flash.events.Event):void { if (dispatchEvent(new org.apache.flex.events.Event("preinitialize", false, true))) { removeEventListener(flash.events.Event.ENTER_FRAME, enterFrameHandler); initialize(); } } /** * This method gets called when all preinitialize handlers * no longer call preventDefault(); * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected function initialize():void { MXMLDataInterpreter.generateMXMLInstances(this, null, MXMLDescriptor); dispatchEvent(new org.apache.flex.events.Event("initialize")); if (initialView) { initialView.applicationModel = model; if (isNaN(initialView.explicitWidth)) initialView.width = stage.stageWidth; if (isNaN(initialView.explicitHeight)) initialView.height = stage.stageHeight; this.addElement(initialView); var bgColor:Object = ValuesManager.valuesImpl.getValue(this, "background-color"); if (bgColor != null) { var backgroundColor:uint = ValuesManager.valuesImpl.convertColor(bgColor); graphics.beginFill(backgroundColor); graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight); graphics.endFill(); } dispatchEvent(new org.apache.flex.events.Event("viewChanged")); } dispatchEvent(new org.apache.flex.events.Event("applicationComplete")); } /** * The org.apache.flex.core.IValuesImpl that will * determine the default values and other values * for the application. The most common choice * is org.apache.flex.core.SimpleCSSValuesImpl. * * @see org.apache.flex.core.SimpleCSSValuesImpl * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set valuesImpl(value:IValuesImpl):void { ValuesManager.valuesImpl = value; ValuesManager.valuesImpl.init(this); } /** * The initial view. * * @see org.apache.flex.core.ViewBase * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var initialView:ViewBase; /** * The data model (for the initial view). * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var model:Object; /** * The controller. The controller typically watches * the UI for events and updates the model accordingly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var controller:Object; /** * An array of data that describes the MXML attributes * and tags in an MXML document. This data is usually * decoded by an MXMLDataInterpreter * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get MXMLDescriptor():Array { return null; } /** * An method called by the compiler's generated * code to kick off the setting of MXML attribute * values and instantiation of child tags. * * The call has to be made in the generated code * in order to ensure that the constructors have * completed first. * * @param data The encoded data representing the * MXML attributes. * * @see org.apache.flex.utils.MXMLDataInterpreter * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function generateMXMLAttributes(data:Array):void { MXMLDataInterpreter.generateMXMLProperties(this, data); } /** * The array property that is used to add additional * beads to an MXML tag. From ActionScript, just * call addBead directly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var beads:Array; private var _beads:Vector.<IBead>; /** * @copy org.apache.flex.core.IStrand#addBead() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addBead(bead:IBead):void { if (!_beads) _beads = new Vector.<IBead>; _beads.push(bead); bead.strand = this; } /** * @copy org.apache.flex.core.IStrand#getBeadByType() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getBeadByType(classOrInterface:Class):IBead { for each (var bead:IBead in _beads) { if (bead is classOrInterface) return bead; } return null; } /** * @copy org.apache.flex.core.IStrand#removeBead() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeBead(value:IBead):IBead { var n:int = _beads.length; for (var i:int = 0; i < n; i++) { var bead:IBead = _beads[i]; if (bead == value) { _beads.splice(i, 1); return bead; } } return null; } private var _info:Object; /** * An Object containing information generated * by the compiler that is useful at startup time. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function info():Object { if (!_info) { var mainClassName:String = getQualifiedClassName(this); var initClassName:String = "_" + mainClassName + "_FlexInit"; var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class; _info = c.info(); } return _info; } /** * @copy org.apache.flex.core.IParent#addElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addElement(c:Object, dispatchEvent:Boolean = true):void { if (c is IUIBase) { addChild(IUIBase(c).element as DisplayObject); IUIBase(c).addedToParent(); } else addChild(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#addElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function addElementAt(c:Object, index:int, dispatchEvent:Boolean = true):void { if (c is IUIBase) { addChildAt(IUIBase(c).element as DisplayObject, index); IUIBase(c).addedToParent(); } else addChildAt(c as DisplayObject, index); } /** * @copy org.apache.flex.core.IParent#getElementAt() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getElementAt(index:int):Object { return getChildAt(index); } /** * @copy org.apache.flex.core.IParent#getElementIndex() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getElementIndex(c:Object):int { if (c is IUIBase) return getChildIndex(IUIBase(c).element as DisplayObject); return getChildIndex(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#removeElement() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function removeElement(c:Object, dispatchEvent:Boolean = true):void { if (c is IUIBase) { removeChild(IUIBase(c).element as DisplayObject); } else removeChild(c as DisplayObject); } /** * @copy org.apache.flex.core.IParent#numElements * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get numElements():int { return numChildren; } } }
add preinitialize event as a way to defer initialization so things like fonts can get loaded first
add preinitialize event as a way to defer initialization so things like fonts can get loaded first
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
614668a41b6c946aefad337904b82091ab16d6b4
crt/amd64-linux/crt.as
crt/amd64-linux/crt.as
.file "crt.as" .text .global _start _start: call $main movl %eax, %edi call $exit
.file "crt.as" .text .global _start _start: call main movl %eax, %edi call exit
Fix main,exit types
[crt-amd64-linux] Fix main,exit types
ActionScript
isc
k0gaMSX/scc,k0gaMSX/scc,k0gaMSX/scc
f52c937262b130281d0d0486c20db0b3958cad4b
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/IUIBase.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/IUIBase.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import org.apache.flex.events.IEventDispatcher; /** * The IUIBase interface is the basic interface for user interface components. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public interface IUIBase extends IStrand, IEventDispatcher { /** * Each IUIBase has an element that is actually added to * the platform's display list DOM. It may not be the actual * component itself. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get element():Object; /** * Called by parent components when the component is * added via a call to addElement or addElementAt. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function addedToParent():void; /** * The alpha or opacity in the range of 0 to 1. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get alpha():Number; function set alpha(value:Number):void; /** * The x co-ordinate or left side position of the bounding box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get x():Number; function set x(value:Number):void; /** * The y co-ordinate or top position of the bounding box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get y():Number; function set y(value:Number):void; /** * The width of the bounding box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get width():Number; function set width(value:Number):void; /** * The height of the bounding box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get height():Number; function set height(value:Number):void; } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import org.apache.flex.events.IEventDispatcher; /** * The IUIBase interface is the basic interface for user interface components. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public interface IUIBase extends IStrand, IEventDispatcher { /** * Each IUIBase has an element that is actually added to * the platform's display list DOM. It may not be the actual * component itself. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get element():Object; /** * Called by parent components when the component is * added via a call to addElement or addElementAt. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function addedToParent():void; /** * The alpha or opacity in the range of 0 to 1. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get alpha():Number; function set alpha(value:Number):void; /** * The x co-ordinate or left side position of the bounding box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get x():Number; function set x(value:Number):void; /** * The y co-ordinate or top position of the bounding box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get y():Number; function set y(value:Number):void; /** * The width of the bounding box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get width():Number; function set width(value:Number):void; /** * The height of the bounding box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get height():Number; function set height(value:Number):void; /** * Whether the component is visible. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ function get visible():Boolean; function set visible(value:Boolean):void; } }
add visible to IUIBase
add visible to IUIBase
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
eed8bdaab346ed417ae8d1dd7445aac3d1380254
frameworks/as/projects/FlexJSJX/src/org/apache/flex/charts/supportClasses/BoxItemRenderer.as
frameworks/as/projects/FlexJSJX/src/org/apache/flex/charts/supportClasses/BoxItemRenderer.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.charts.supportClasses { import org.apache.flex.charts.core.IChartItemRenderer; import org.apache.flex.charts.core.IChartSeries; import org.apache.flex.core.graphics.IFill; import org.apache.flex.core.graphics.IStroke; import org.apache.flex.core.graphics.Rect; import org.apache.flex.html.supportClasses.DataItemRenderer; /** * The BoxItemRenderer displays a colored rectangular area suitable for use as * an itemRenderer for a BarChartSeries. This class implements the * org.apache.flex.charts.core.IChartItemRenderer * interface. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class BoxItemRenderer extends DataItemRenderer implements IChartItemRenderer { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function BoxItemRenderer() { super(); } private var _series:IChartSeries; /** * The series to which this itemRenderer instance belongs. Or, the series * being presented. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get series():IChartSeries { return _series; } public function set series(value:IChartSeries):void { _series = value; } private var filledRect:Rect; private var _yField:String = "y"; /** * The name of the field containing the value for the Y axis. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get yField():String { return _yField; } public function set yField(value:String):void { _yField = value; } private var _xField:String = "x"; /** * The name of the field containing the value for the X axis. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get xField():String { return _xField; } public function set xField(value:String):void { _xField = value; } private var _fill:IFill; /** * The color used to fill the interior of the box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get fill():IFill { return _fill; } public function set fill(value:IFill):void { _fill = value; } private var _stroke:IStroke; /** * The outline of the box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get stroke():IStroke { return _stroke; } public function set stroke(value:IStroke):void { _stroke = value; } /** * @copy org.apache.flex.supportClasses.UIItemRendererBase#data * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set data(value:Object):void { super.data = value; drawBar(); } /** * @copy org.apache.flex.core.UIBase#width * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set width(value:Number):void { super.width = value; drawBar(); } /** * @copy org.apache.flex.core.UIBase#height * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set height(value:Number):void { super.height = value; drawBar(); } /** * @private */ protected function drawBar():void { if ((this.width > 0) && (this.height > 0)) { var needsAdd:Boolean = false; if (filledRect == null) { filledRect = new Rect(); needsAdd = true; } filledRect.fill = fill; filledRect.stroke = stroke; filledRect.drawRect(0,0,this.width,this.height); if (needsAdd) { addElement(filledRect); } } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.charts.supportClasses { import org.apache.flex.charts.core.IChartItemRenderer; import org.apache.flex.charts.core.IChartSeries; import org.apache.flex.core.graphics.IFill; import org.apache.flex.core.graphics.IStroke; import org.apache.flex.core.graphics.Rect; import org.apache.flex.html.supportClasses.DataItemRenderer; /** * The BoxItemRenderer displays a colored rectangular area suitable for use as * an itemRenderer for a BarChartSeries. This class implements the * org.apache.flex.charts.core.IChartItemRenderer * interface. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class BoxItemRenderer extends DataItemRenderer implements IChartItemRenderer { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function BoxItemRenderer() { super(); } private var _series:IChartSeries; /** * The series to which this itemRenderer instance belongs. Or, the series * being presented. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get series():IChartSeries { return _series; } public function set series(value:IChartSeries):void { _series = value; } private var filledRect:Rect; private var _yField:String = "y"; /** * The name of the field containing the value for the Y axis. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get yField():String { return _yField; } public function set yField(value:String):void { _yField = value; } private var _xField:String = "x"; /** * The name of the field containing the value for the X axis. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get xField():String { return _xField; } public function set xField(value:String):void { _xField = value; } private var _fill:IFill; /** * The color used to fill the interior of the box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get fill():IFill { return _fill; } public function set fill(value:IFill):void { _fill = value; } private var _stroke:IStroke; /** * The outline of the box. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get stroke():IStroke { return _stroke; } public function set stroke(value:IStroke):void { _stroke = value; } /** * @copy org.apache.flex.supportClasses.UIItemRendererBase#data * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set data(value:Object):void { super.data = value; drawBar(); } /** * @copy org.apache.flex.core.UIBase#width * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set width(value:Number):void { super.width = value; drawBar(); } /** * @copy org.apache.flex.core.UIBase#height * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ override public function set height(value:Number):void { super.height = value; drawBar(); } /** * @private */ protected function drawBar():void { if ((this.width > 0) && (this.height > 0)) { var needsAdd:Boolean = false; if (filledRect == null) { filledRect = new Rect(); needsAdd = true; } filledRect.fill = fill; filledRect.stroke = stroke; filledRect.x = 0; filledRect.y = 0; filledRect.width = this.width; filledRect.height = this.height; if (needsAdd) { addElement(filledRect); } } } } }
Fix BoxItemRenderer to accommodate for drawing api changes
Fix BoxItemRenderer to accommodate for drawing api changes
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
2c60e6c3cfa8b0b3539f7619d99fdd819d3e0828
src/as/com/threerings/flex/ChatControl.as
src/as/com/threerings/flex/ChatControl.as
// // $Id$ package com.threerings.flex { import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TextEvent; import flash.ui.Keyboard; import mx.containers.HBox; import mx.core.Application; import mx.controls.TextInput; import mx.events.FlexEvent; import com.threerings.util.ArrayUtil; import com.threerings.util.StringUtil; import com.threerings.flex.CommandButton; import com.threerings.flex.CommandMenu; import com.threerings.crowd.chat.client.ChatDirector; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.util.CrowdContext; /** * The chat control widget. */ public class ChatControl extends HBox { /** * Request focus for the oldest ChatControl. */ public static function grabFocus () :void { if (_controls.length > 0) { (_controls[0] as ChatControl).setFocus(); } } public function ChatControl ( ctx :CrowdContext, sendButtonLabel :String = "send", height :Number = NaN, controlHeight :Number = NaN) { _ctx = ctx; _chatDtr = _ctx.getChatDirector(); this.height = height; styleName = "chatControl"; addChild(_txt = new ChatInput()); _txt.addEventListener(FlexEvent.ENTER, sendChat, false, 0, true); _txt.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp); _but = new CommandButton(sendButtonLabel, sendChat); addChild(_but); if (!isNaN(controlHeight)) { _txt.height = controlHeight; _but.height = controlHeight; } addEventListener(Event.ADDED_TO_STAGE, handleAddRemove); addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove); } /** * Provides access to the text field we use to accept chat. */ public function get chatInput () :ChatInput { return _txt; } /** * Provides access to the send button. */ public function get sendButton () :CommandButton { return _but; } /** * Request focus to this chat control. */ override public function setFocus () :void { _txt.setFocus(); } /** * Enables or disables our chat input. */ public function setEnabled (enabled :Boolean) :void { _txt.enabled = enabled; _but.enabled = enabled; } /** * Configures the chat director to which we should send our chat. Pass null to restore our * default chat director. */ public function setChatDirector (chatDtr :ChatDirector) :void { _chatDtr = (chatDtr == null) ? _ctx.getChatDirector() : chatDtr; } /** * Configures the background color of the text entry area. */ public function setChatColor (color :int) :void { _txt.setStyle("backgroundColor", color); } /** * Handles FlexEvent.ENTER and the action from the send button. */ protected function sendChat (... ignored) :void { var message :String = StringUtil.trim(_txt.text); if ("" == message) { return; } var result :String = _chatDtr.requestChat(null, message, true); if (result != ChatCodes.SUCCESS) { _chatDtr.displayFeedback(null, result); return; } // if there was no error, clear the entry area in prep for the next entry event _txt.text = ""; _histidx = -1; } protected function scrollHistory (next :Boolean) :void { var size :int = _chatDtr.getCommandHistorySize(); if ((_histidx == -1) || (_histidx == size)) { _curLine = _txt.text; _histidx = size; } _histidx = (next) ? Math.min(_histidx + 1, size) : Math.max(_histidx - 1, 0); var text :String = (_histidx == size) ? _curLine : _chatDtr.getCommandHistory(_histidx); _txt.text = text; _txt.setSelection(text.length, text.length); } /** * Handles Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE. */ protected function handleAddRemove (event :Event) :void { if (event.type == Event.ADDED_TO_STAGE) { // set up any already-configured text _txt.text = _curLine; _histidx = -1; // request focus callLater(_txt.setFocus); _controls.push(this); } else { _curLine = _txt.text; ArrayUtil.removeAll(_controls, this); } } protected function handleKeyUp (event :KeyboardEvent) :void { switch (event.keyCode) { case Keyboard.UP: scrollHistory(false); break; case Keyboard.DOWN: scrollHistory(true); break; } } /** Our client-side context. */ protected var _ctx :CrowdContext; /** The director to which we are sending chat requests. */ protected var _chatDtr :ChatDirector; /** The place where the user may enter chat. */ protected var _txt :ChatInput; /** The current index in the chat command history. */ protected var _histidx :int = -1; /** The button for sending chat. */ protected var _but :CommandButton; /** An array of the currently shown-controls. */ protected static var _controls :Array = []; /** The preserved current line of text when traversing history or carried between instances of * ChatControl. */ protected static var _curLine :String; } }
// // $Id$ package com.threerings.flex { import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.FocusEvent; import flash.events.KeyboardEvent; import flash.events.MouseEvent; import flash.events.TextEvent; import flash.ui.Keyboard; import mx.containers.HBox; import mx.core.Application; import mx.controls.TextInput; import mx.events.FlexEvent; import com.threerings.util.ArrayUtil; import com.threerings.util.StringUtil; import com.threerings.flex.CommandButton; import com.threerings.flex.CommandMenu; import com.threerings.crowd.chat.client.ChatDirector; import com.threerings.crowd.chat.data.ChatCodes; import com.threerings.crowd.util.CrowdContext; /** * The chat control widget. */ public class ChatControl extends HBox { /** * Request focus for the oldest ChatControl. */ public static function grabFocus () :void { if (_controls.length > 0) { (_controls[0] as ChatControl).setFocus(); } } public function ChatControl ( ctx :CrowdContext, sendButtonLabel :String = "send", height :Number = NaN, controlHeight :Number = NaN) { _ctx = ctx; _chatDtr = _ctx.getChatDirector(); this.height = height; styleName = "chatControl"; addChild(_txt = new ChatInput()); _txt.addEventListener(FlexEvent.ENTER, sendChat, false, 0, true); _txt.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp); _but = new CommandButton(sendButtonLabel, sendChat); addChild(_but); if (!isNaN(controlHeight)) { _txt.height = controlHeight; _but.height = controlHeight; } addEventListener(Event.ADDED_TO_STAGE, handleAddRemove); addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove); } /** * Provides access to the text field we use to accept chat. */ public function get chatInput () :ChatInput { return _txt; } /** * Provides access to the send button. */ public function get sendButton () :CommandButton { return _but; } override public function set enabled (en :Boolean) :void { // don't call super (and the only time these aren't around is during construction) if (_txt != null) { _txt.enabled = en; _but.enabled = en; } } override public function get enabled () :Boolean { return _txt.enabled; } /** * Request focus to this chat control. */ override public function setFocus () :void { _txt.setFocus(); } /** * Configures the chat director to which we should send our chat. Pass null to restore our * default chat director. */ public function setChatDirector (chatDtr :ChatDirector) :void { _chatDtr = (chatDtr == null) ? _ctx.getChatDirector() : chatDtr; } /** * Configures the background color of the text entry area. */ public function setChatColor (color :int) :void { _txt.setStyle("backgroundColor", color); } /** * Handles FlexEvent.ENTER and the action from the send button. */ protected function sendChat (... ignored) :void { var message :String = StringUtil.trim(_txt.text); if ("" == message) { return; } var result :String = _chatDtr.requestChat(null, message, true); if (result != ChatCodes.SUCCESS) { _chatDtr.displayFeedback(null, result); return; } // if there was no error, clear the entry area in prep for the next entry event _txt.text = ""; _histidx = -1; } protected function scrollHistory (next :Boolean) :void { var size :int = _chatDtr.getCommandHistorySize(); if ((_histidx == -1) || (_histidx == size)) { _curLine = _txt.text; _histidx = size; } _histidx = (next) ? Math.min(_histidx + 1, size) : Math.max(_histidx - 1, 0); var text :String = (_histidx == size) ? _curLine : _chatDtr.getCommandHistory(_histidx); _txt.text = text; _txt.setSelection(text.length, text.length); } /** * Handles Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE. */ protected function handleAddRemove (event :Event) :void { if (event.type == Event.ADDED_TO_STAGE) { // set up any already-configured text _txt.text = _curLine; _histidx = -1; // request focus callLater(_txt.setFocus); _controls.push(this); } else { _curLine = _txt.text; ArrayUtil.removeAll(_controls, this); } } protected function handleKeyUp (event :KeyboardEvent) :void { switch (event.keyCode) { case Keyboard.UP: scrollHistory(false); break; case Keyboard.DOWN: scrollHistory(true); break; } } /** Our client-side context. */ protected var _ctx :CrowdContext; /** The director to which we are sending chat requests. */ protected var _chatDtr :ChatDirector; /** The place where the user may enter chat. */ protected var _txt :ChatInput; /** The current index in the chat command history. */ protected var _histidx :int = -1; /** The button for sending chat. */ protected var _but :CommandButton; /** An array of the currently shown-controls. */ protected static var _controls :Array = []; /** The preserved current line of text when traversing history or carried between instances of * ChatControl. */ protected static var _curLine :String; } }
Use the 'enabled' property setter/getter.
Use the 'enabled' property setter/getter. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@748 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
4c467a37a1ab9c9af2c3f5bb7593fec8980fa7c6
Tablet/Clipboard/blackberry.clipboard/src/Air/Clipboard/src/blackberry/clipboard/ClipboardExtension.as
Tablet/Clipboard/blackberry.clipboard/src/Air/Clipboard/src/blackberry/clipboard/ClipboardExtension.as
/* * Copyright 2010-2011 Research In Motion Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //------------------------------------------------------------------------------------ // // CREATE YOUR OWN BLACKBERRY WEBWORKS EXTENSION WITH THIS TEMPLATE. // GET STARTED BY COMPLETING ALL OF THE 'STEP' INSTRUCTIONS LISTED BELOW. // // 1. Package name // 2. Class and constructor name // 3. Feature names // 4. Properties and functions // // // Consider contributing your extension to the BlackBerry WebWorks Community APIs: // https://github.com/blackberry/WebWorks-Community-APIs // //------------------------------------------------------------------------------------ /** * An extension is a bridge between JavaScript, running in a WebWorks application, and * developer APIs found in the underlying OS (J2ME for BlackBerry Smartphones and Adobe * AIR for BlackBerry Tablet OS). * * Using this technique, WebWorks developers can expose any available devices features * in their HTML5 application content. * * Example (config.xml): * <feature id="webworks.template" required="true" version="1.0.0.0"/> * * Example (JavaScript): * webworks.template.add(5,6); //11 */ // //STEP 1: Choose a unique package name that describes your extension. // Use the same package name in all classes that define this extension. // // e.g. "my.extension" or "companyname.description" // package blackberry.clipboard { import flash.events.Event; import flash.desktop.Clipboard; import flash.desktop.ClipboardFormats; import webworks.extension.DefaultExtension; import qnx.events.QNXApplicationEvent; import qnx.system.QNXApplication; // //STEP 2: Rename this class and constructor to describe the primary purpose of this extension. // e.g. HelloWorldExtension or LEDextension // public class ClipboardExtension extends DefaultExtension { // //STEP 3: For each feature name, add it to an array. // private const FEATURE_ID:Array = new Array("blackberry.clipboard"); // //STEP 2 (Continued): Rename this constructor to match the class name. // public function ClipboardExtension() { super(); } /* public override function unloadFeature():void { webView.removeEventListener(Event.ACTIVATE,activate); } */ override public function getFeatureList():Array { return FEATURE_ID; } // //STEP 4: Replace the following section with any properties or functions that // will be supported in your extension. // // // Functions: // public function setText(value:String):void { Clipboard.generalClipboard.clear(); Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, value); } public function getText():String { return String(Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT)); } } }
/* * Copyright 2010-2011 Research In Motion Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //------------------------------------------------------------------------------------ // // CREATE YOUR OWN BLACKBERRY WEBWORKS EXTENSION WITH THIS TEMPLATE. // GET STARTED BY COMPLETING ALL OF THE 'STEP' INSTRUCTIONS LISTED BELOW. // // 1. Package name // 2. Class and constructor name // 3. Feature names // 4. Properties and functions // // // Consider contributing your extension to the BlackBerry WebWorks Community APIs: // https://github.com/blackberry/WebWorks-Community-APIs // //------------------------------------------------------------------------------------ /** * An extension is a bridge between JavaScript, running in a WebWorks application, and * developer APIs found in the underlying OS (J2ME for BlackBerry Smartphones and Adobe * AIR for BlackBerry Tablet OS). * * Using this technique, WebWorks developers can expose any available devices features * in their HTML5 application content. * * Example (config.xml): * <feature id="webworks.template" required="true" version="1.0.0.0"/> * * Example (JavaScript): * webworks.template.add(5,6); //11 */ // //STEP 1: Choose a unique package name that describes your extension. // Use the same package name in all classes that define this extension. // // e.g. "my.extension" or "companyname.description" // package blackberry.clipboard { import flash.utils.ByteArray; import flash.events.Event; import flash.desktop.Clipboard; import flash.desktop.ClipboardFormats; import webworks.extension.DefaultExtension; import qnx.events.QNXApplicationEvent; import qnx.system.QNXApplication; // //STEP 2: Rename this class and constructor to describe the primary purpose of this extension. // e.g. HelloWorldExtension or LEDextension // public class ClipboardExtension extends DefaultExtension { // //STEP 3: For each feature name, add it to an array. // private const FEATURE_ID:Array = new Array("blackberry.clipboard"); // //STEP 2 (Continued): Rename this constructor to match the class name. // public function ClipboardExtension() { super(); } /* public override function unloadFeature():void { webView.removeEventListener(Event.ACTIVATE,activate); } */ override public function getFeatureList():Array { return FEATURE_ID; } // //STEP 4: Replace the following section with any properties or functions that // will be supported in your extension. // // // Functions: // public function setText(value:String):void { Clipboard.generalClipboard.clear(); value = encodeUtf8(value); // Use UTF8 encoding Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, value); } public function getText():String { return String(Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT)); } public function encodeUtf8(str: String):String { if (str != null && str != "undefined") { var oriByteArr: ByteArray = new ByteArray(); oriByteArr.writeUTFBytes(str); var tempByteArr:ByteArray = new ByteArray(); for(var i:Number = 0; i < oriByteArr.length; i++) { if(oriByteArr[i] == 194){ tempByteArr.writeByte(oriByteArr[i+1]); i++; } else if (oriByteArr[i] == 195) { tempByteArr.writeByte(oriByteArr[i+1] + 64); i++; } else { tempByteArr.writeByte(oriByteArr[i]); } } tempByteArr.position = 0; return tempByteArr.readMultiByte(tempByteArr.bytesAvailable, "utf-8"); } else { return ""; } } } }
Use UTF8 encoding; Thanks to Guichun Chen for providing the conversion algorithm!
Use UTF8 encoding; Thanks to Guichun Chen for providing the conversion algorithm!
ActionScript
apache-2.0
gamerDecathlete/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,gamerDecathlete/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,parker-mar/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,Makoz/WebWorks-Community-APIs,timwindsor/WebWorks-Community-APIs,T-M-C/WebWorks-Community-APIs,blackberry/WebWorks-Community-APIs,Jayapraju/WebWorks-Community-APIs,jcmurray/WebWorks-Community-APIs
a52512f1414c32c6b96c98965148f4a97ec4c3dd
src/goplayer/FlashContentLoadAttempt.as
src/goplayer/FlashContentLoadAttempt.as
package goplayer { import flash.display.Loader import flash.events.Event import flash.events.IOErrorEvent import flash.net.URLRequest import flash.system.ApplicationDomain import flash.system.LoaderContext import flash.system.SecurityDomain public class FlashContentLoadAttempt { private const loader : Loader = new Loader private var url : String private var listener : FlashContentLoaderListener public function FlashContentLoadAttempt (url : String, listener : FlashContentLoaderListener) { this.url = url, this.listener = listener loader.contentLoaderInfo.addEventListener (Event.COMPLETE, handleContentLoaded) loader.contentLoaderInfo.addEventListener (IOErrorEvent.IO_ERROR, handleIOError) } public function execute() : void { loader.load(new URLRequest(url)) } private function handleContentLoaded(event : Event) : void { listener.handleContentLoaded(loader.contentLoaderInfo) } private function handleIOError(event : IOErrorEvent) : void { debug("Failed to load <" + url + ">: " + event.text) } } }
package goplayer { import flash.display.Loader import flash.events.Event import flash.events.IOErrorEvent import flash.net.URLRequest import flash.system.ApplicationDomain import flash.system.LoaderContext import flash.system.SecurityDomain public class FlashContentLoadAttempt { private const loader : Loader = new Loader private var url : String private var listener : FlashContentLoaderListener public function FlashContentLoadAttempt (url : String, listener : FlashContentLoaderListener) { this.url = url, this.listener = listener loader.contentLoaderInfo.addEventListener (Event.COMPLETE, handleContentLoaded) loader.contentLoaderInfo.addEventListener (IOErrorEvent.IO_ERROR, handleIOError) } public function execute() : void { loader.load(new URLRequest(url)) } private function handleContentLoaded(event : Event) : void { listener.handleContentLoaded(loader.contentLoaderInfo) } private function handleIOError(event : IOErrorEvent) : void { const code : String = event.text.match(/^Error #(\d+)/)[1] const message : String = code == "2035" ? "Not found" : event.text debug("Error: Failed to load <" + url + ">: " + message) } } }
Improve error handling of external content loading.
Improve error handling of external content loading.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
1ad2608d13cd787ab836c972c463b12e5b18df4c
src/org/flintparticles/twoD/actions/TurnAwayFromMouse.as
src/org/flintparticles/twoD/actions/TurnAwayFromMouse.as
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2011 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.twoD.actions { import flash.display.DisplayObject; /** * The TurnAwayFromMouse action causes the particle to constantly adjust its * direction so that it travels away from the mouse pointer. */ public class TurnAwayFromMouse extends TurnTowardsMouse { /** * The constructor creates a TurnAwayFromMouse action for use by an emitter. * To add a TurnAwayFromMouse to all particles created by an emitter, use the * emitter's addAction method. * * @see org.flintparticles.common.emitters.Emitter#addAction() * * @param power The strength of the turn action. Higher values produce a sharper turn. * @param renderer The display object whose coordinate system the mouse position is * converted to. This is usually the renderer for the particle system created by the emitter. */ public function TurnAwayFromMouse( power:Number = 0, renderer:DisplayObject = null ) { super( -power, renderer ); } /** * The strength of the turn action. Higher values produce a sharper turn. */ override public function get power():Number { return -super.power; } override public function set power( value:Number ):void { super.power = -value; } } }
/* * FLINT PARTICLE SYSTEM * ..................... * * Author: Richard Lord * Copyright (c) Richard Lord 2008-2011 * http://flintparticles.org * * * Licence Agreement * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.flintparticles.twoD.actions { import org.flintparticles.common.actions.ActionBase; import org.flintparticles.common.emitters.Emitter; import org.flintparticles.common.particles.Particle; import org.flintparticles.twoD.particles.Particle2D; import flash.display.DisplayObject; /** * The TurnAwayFromMouse action causes the particle to constantly adjust its direction * so that it travels away from the mouse pointer. */ public class TurnAwayFromMouse extends ActionBase { private var _power:Number; private var _renderer:DisplayObject; /** * The constructor creates a TurnAwayFromMouse action for use by an emitter. * To add a TurnAwayFromMouse to all particles created by an emitter, use the * emitter's addAction method. * * @see org.flintparticles.common.emitters.Emitter#addAction() * * @param power The strength of the turn action. Higher values produce a sharper turn. * @param renderer The display object whose coordinate system the mouse position is * converted to. This is usually the renderer for the particle system created by the emitter. */ public function TurnAwayFromMouse( power:Number = 0, renderer:DisplayObject = null ) { this.power = power; this.renderer = renderer; } /** * The strength of the turn action. Higher values produce a sharper turn. */ public function get power():Number { return _power; } public function set power( value:Number ):void { _power = value; } /** * The display object whose coordinate system the mouse position is converted to. This * is usually the renderer for the particle system created by the emitter. */ public function get renderer():DisplayObject { return _renderer; } public function set renderer( value:DisplayObject ):void { _renderer = value; } /** * Calculates the direction to the mouse and turns the particle towards * this direction. * * <p>This method is called by the emitter and need not be called by the * user.</p> * * @param emitter The Emitter that created the particle. * @param particle The particle to be updated. * @param time The duration of the frame - used for time based updates. * * @see org.flintparticles.common.actions.Action#update() */ override public function update( emitter:Emitter, particle:Particle, time:Number ):void { var p:Particle2D = Particle2D( particle ); var turnLeft:Boolean = ( ( p.y - _renderer.mouseY ) * p.velX + ( _renderer.mouseX - p.x ) * p.velY < 0 ); var newAngle:Number; if ( turnLeft ) { newAngle = Math.atan2( p.velY, p.velX ) - _power * time; } else { newAngle = Math.atan2( p.velY, p.velX ) + _power * time; } var len:Number = Math.sqrt( p.velX * p.velX + p.velY * p.velY ); p.velX = len * Math.cos( newAngle ); p.velY = len * Math.sin( newAngle ); var overturned:Boolean = ( ( p.y - _renderer.mouseY ) * p.velX + ( _renderer.mouseX - p.x ) * p.velY < 0 ) != turnLeft; if( overturned ) { var dx:Number = p.x - _renderer.mouseX; var dy:Number = p.y - _renderer.mouseY; var factor:Number = len / Math.sqrt( dx * dx + dy * dy ); p.velX = dx * factor; p.velY = dy * factor; } } } }
Fix error in TurnAwayFromMouse action.
Fix error in TurnAwayFromMouse action.
ActionScript
mit
richardlord/Flint
405355157514f3882794855aa3261846e8d6fbf6
frameworks/projects/Binding/as/src/org/apache/flex/binding/ConstantBinding.as
frameworks/projects/Binding/as/src/org/apache/flex/binding/ConstantBinding.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.binding { import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.core.IDocument; /** * The ConstantBinding class is lightweight data-binding class that * is optimized for simple assignments of one object's constant to * another object's property. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ConstantBinding implements IBead, IDocument { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ConstantBinding() { } /** * The source object who's property has the value we want. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var source:Object; /** * The host mxml document for the source and * destination objects. The source object * is either this document for simple bindings * like {foo} where foo is a property on * the mxml documnet, or found as document[sourceID] * for simple bindings like {someid.someproperty} * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var document:Object; /** * The destination object. It is always the same * as the strand. ConstantBindings are attached to * the strand of the destination object. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var destination:Object; /** * If not null, the id of the mxml tag who's property * is being watched for changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var sourceID:String; /** * If not null, the name of a property on the * mxml document that is being watched for changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var sourcePropertyName:String; /** * The name of the property on the strand that * is set when the source property changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var destinationPropertyName:String; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { if (destination == null) destination = value; if (sourceID != null) source = document[sourceID]; else source = document; var val:*; if (sourcePropertyName in source) { try { val = source[sourcePropertyName]; destination[destinationPropertyName] = val; } catch (e:Error) { } } else if (sourcePropertyName in source.constructor) { try { val = source.constructor[sourcePropertyName]; destination[destinationPropertyName] = val; } catch (e2:Error) { } } } /** * @copy org.apache.flex.core.IDocument#setDocument() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function setDocument(document:Object, id:String = null):void { this.document = document; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.binding { import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.core.IDocument; /** * The ConstantBinding class is lightweight data-binding class that * is optimized for simple assignments of one object's constant to * another object's property. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class ConstantBinding implements IBead, IDocument { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function ConstantBinding() { } /** * The source object who's property has the value we want. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var source:Object; /** * The host mxml document for the source and * destination objects. The source object * is either this document for simple bindings * like {foo} where foo is a property on * the mxml documnet, or found as document[sourceID] * for simple bindings like {someid.someproperty} * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var document:Object; /** * The destination object. It is always the same * as the strand. ConstantBindings are attached to * the strand of the destination object. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var destination:Object; /** * If not null, the id of the mxml tag who's property * is being watched for changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var sourceID:String; /** * If not null, the name of a property on the * mxml document that is being watched for changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var sourcePropertyName:String; /** * The name of the property on the strand that * is set when the source property changes. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var destinationPropertyName:String; /** * @copy org.apache.flex.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { if (destination == null) destination = value; if (sourceID != null) source = document[sourceID]; else source = document; var val:*; if (sourcePropertyName in source) { try { val = source[sourcePropertyName]; destination[destinationPropertyName] = val; } catch (e:Error) { } } else if (sourcePropertyName in source.constructor) { try { val = source.constructor[sourcePropertyName]; destination[destinationPropertyName] = val; } catch (e2:Error) { } } else { COMPILE::JS { // GCC optimizer only puts exported class constants on // Window and not on the class itself (which got renamed) var cname:Object = source.FLEXJS_CLASS_INFO; if (cname) { cname = cname.names[0].qName; var parts:Array = cname.split('.'); var n:int = parts.length; var o:Object = window; for (var i:int = 0; i < n; i++) { o = o[parts[i]]; } val = o[sourcePropertyName]; destination[destinationPropertyName] = val; } } } } /** * @copy org.apache.flex.core.IDocument#setDocument() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function setDocument(document:Object, id:String = null):void { this.document = document; } } }
fix constant binding in release mode
fix constant binding in release mode
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
408e775d0fcbd60776c451052d2c77c362baade9
src/main/actionscript/com/dotfold/dotvimstat/net/service/VimeoBasicService.as
src/main/actionscript/com/dotfold/dotvimstat/net/service/VimeoBasicService.as
package com.dotfold.dotvimstat.net.service { import asx.object.merge; import com.codecatalyst.promise.Deferred; import com.codecatalyst.promise.Promise; import com.dotfold.dotvimstat.net.http.HTTPClient; import com.dotfold.dotvimstat.net.serializer.VideosResponseSerializer; import flash.media.Video; import org.as3commons.logging.ILogger; import org.as3commons.logging.LoggerFactory; /** * Service layer handles communications with the Vimeo Basic API. * * @author jamesmcnamee * */ public class VimeoBasicService implements IVimeoService { private static var logger:ILogger = LoggerFactory.getClassLogger(VimeoBasicService); [Inject] /** * HTTPClient used for API communications. */ public function set http(value:HTTPClient):void { _http = value; initialiseMappings(); } public function get http():HTTPClient { return _http; } private var _http:HTTPClient; /** * Default name value pairs used in common URL endpoints. */ protected var urlDefaults:Object; /** * Constructor. */ public function VimeoBasicService() { super(); urlDefaults = { host: 'vimeo.com', application: 'api/v2', user: 'primarythreads' }; } /** * Set up the named resource mappings on the HTTPClient. */ private function initialiseMappings():void { http.mapUrl("videos", merge(urlDefaults, { resource: 'videos.json' }) ).addReponseSerializer(new VideosResponseSerializer()) http.mapUrl("likes", merge(urlDefaults, { resource: 'likes.json' }) ); http.mapUrl("activity", merge(urlDefaults, { resource: 'user_did.json' }) ); } // // API Endpoints // /** * Retrieves the `info` for the set username. */ public function getInfo():Promise { logger.debug('getInfo'); return http.get("info"); } /** * Retrieves the `videos` listing for the set username. */ public function getVideos():Promise { logger.debug('getVideos'); return http.get("videos"); } /** * Retrieves the `likes` listing for the set username. */ public function getLikes():Promise { logger.debug('getLikes'); return http.get("likes"); } /** * Retrieves the user activity listing for the set username. */ public function getActivity():Promise { logger.debug('getActivity'); return http.get("activity"); } } }
package com.dotfold.dotvimstat.net.service { import asx.object.merge; import com.codecatalyst.promise.Deferred; import com.codecatalyst.promise.Promise; import com.dotfold.dotvimstat.net.http.HTTPClient; import com.dotfold.dotvimstat.net.serializer.*; import flash.media.Video; import org.as3commons.logging.ILogger; import org.as3commons.logging.LoggerFactory; /** * Service layer handles communications with the Vimeo Basic API. * * @author jamesmcnamee * */ public class VimeoBasicService implements IVimeoService { private static var logger:ILogger = LoggerFactory.getClassLogger(VimeoBasicService); [Inject] /** * HTTPClient used for API communications. */ public function set http(value:HTTPClient):void { _http = value; initialiseMappings(); } public function get http():HTTPClient { return _http; } private var _http:HTTPClient; /** * Default name value pairs used in common URL endpoints. */ protected var urlDefaults:Object; /** * Constructor. */ public function VimeoBasicService() { super(); urlDefaults = { host: 'vimeo.com', application: 'api/v2', user: 'primarythreads' }; } /** * Set up the named resource mappings on the HTTPClient. */ private function initialiseMappings():void { http.mapUrl("videos", merge(urlDefaults, { resource: 'videos.json' }) ) .addReponseSerializer(new VideosResponseSerializer()) http.mapUrl("likes", merge(urlDefaults, { resource: 'likes.json' }) ) .addReponseSerializer(new LikesResponseSerializer()); http.mapUrl("activity", merge(urlDefaults, { resource: 'user_did.json' }) ) .addReponseSerializer(new ActivityResponseSerializer()); http.mapUrl("info", merge(urlDefaults, { resource: 'info.json' }) ) .addReponseSerializer(new UserInfoResponseSerializer()); } // // API Endpoints // /** * Retrieves the `info` for the set username. */ public function getInfo():Promise { logger.debug('getInfo'); return http.get("info"); } /** * Retrieves the `videos` listing for the set username. */ public function getVideos():Promise { logger.debug('getVideos'); return http.get("videos"); } /** * Retrieves the `likes` listing for the set username. */ public function getLikes():Promise { logger.debug('getLikes'); return http.get("likes"); } /** * Retrieves the user activity listing for the set username. */ public function getActivity():Promise { logger.debug('getActivity'); return http.get("activity"); } } }
add info service mapping
[feat] add info service mapping
ActionScript
mit
dotfold/dotvimstat
f4b49471ccfc6eaad274b765e620841dda0a4503
src/com/esri/builder/controllers/supportClasses/StartupWidgetTypeLoader.as
src/com/esri/builder/controllers/supportClasses/StartupWidgetTypeLoader.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.controllers.supportClasses { import com.esri.builder.model.WidgetType; import com.esri.builder.model.WidgetTypeRegistryModel; import com.esri.builder.supportClasses.FileUtil; import com.esri.builder.supportClasses.LogUtil; import com.esri.builder.views.BuilderAlert; import flash.events.EventDispatcher; import flash.filesystem.File; import flash.utils.Dictionary; import mx.logging.ILogger; import mx.logging.Log; import mx.resources.ResourceManager; public class StartupWidgetTypeLoader extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(StartupWidgetTypeLoader); private var widgetTypeArr:Array = []; private var pendingLoaders:Array; public function loadWidgetTypes():void { if (Log.isInfo()) { LOG.info('Loading modules...'); } var moduleFiles:Array = getModuleFiles(WellKnownDirectories.getInstance().bundledModules) .concat(getModuleFiles(WellKnownDirectories.getInstance().customModules)); var swfFileAndXMLFileMaps:Array = mapFilenameToModuleSWFAndXMLFiles(moduleFiles); var processedFileNames:Array = []; var loaders:Array = []; for each (var moduleFile:File in moduleFiles) { var fileName:String = FileUtil.getFileName(moduleFile); if (Log.isDebug()) { LOG.debug('loading module {0}', fileName); } if (processedFileNames.indexOf(fileName) == -1) { processedFileNames.push(fileName); loaders.push(new WidgetTypeLoader(swfFileAndXMLFileMaps[0][fileName], swfFileAndXMLFileMaps[1][fileName])); } } pendingLoaders = loaders; for each (var loader:WidgetTypeLoader in loaders) { loader.addEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler); loader.addEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler); loader.load(); } checkIfWidgetTypeLoadersComplete(); } private function mapFilenameToModuleSWFAndXMLFiles(moduleFiles:Array):Array { var uniqueFileNameToSWF:Dictionary = new Dictionary(); var uniqueFileNameToXML:Dictionary = new Dictionary(); for each (var file:File in moduleFiles) { if (file.extension == "swf") { uniqueFileNameToSWF[FileUtil.getFileName(file)] = file; } else if (file.extension == "xml") { uniqueFileNameToXML[FileUtil.getFileName(file)] = file; } } return [ uniqueFileNameToSWF, uniqueFileNameToXML ]; } private function getModuleFiles(directory:File):Array { var moduleFiles:Array = []; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); for each (var file:File in files) { if (file.isDirectory) { moduleFiles = moduleFiles.concat(getModuleFiles(file)); } else if (isModuleFile(file)) { moduleFiles.push(file); } } } return moduleFiles; } private function isModuleFile(file:File):Boolean { const moduleFileName:RegExp = /^.*Module\.(swf|xml)$/; return !file.isDirectory && (moduleFileName.test(file.name)); } private function checkIfWidgetTypeLoadersComplete():void { if (pendingLoaders.length === 0) { sortAndAssignWidgetTypes(); } } private function markModuleAsLoaded(loader:WidgetTypeLoader):void { var loaderIndex:int = pendingLoaders.indexOf(loader); if (loaderIndex > -1) { pendingLoaders.splice(loaderIndex, 1); } } private function sortAndAssignWidgetTypes():void { if (Log.isInfo()) { LOG.info('All modules resolved'); } for each (var widgetType:WidgetType in widgetTypeArr) { if (widgetType.isManaged) { WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType); } else { WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(widgetType); } } WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.sort(); WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.sort(); dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_TYPES_COMPLETE)); } private function loader_loadCompleteHandler(event:WidgetTypeLoaderEvent):void { var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader; loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler); loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler); var widgetType:WidgetType = event.widgetType; if (Log.isDebug()) { LOG.debug('Module {0} is resolved', widgetType.name); } widgetTypeArr.push(widgetType); markModuleAsLoaded(loader); checkIfWidgetTypeLoadersComplete(); } private function loader_loadErrorHandler(event:WidgetTypeLoaderEvent):void { var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader; loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler); loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler); var errorMessage:String = ResourceManager.getInstance().getString('BuilderStrings', 'importWidgetProcess.couldNotLoadCustomWidgets', [ loader.name ]); if (Log.isDebug()) { LOG.debug(errorMessage); } BuilderAlert.show(errorMessage, ResourceManager.getInstance().getString('BuilderStrings', 'error')); markModuleAsLoaded(loader); checkIfWidgetTypeLoadersComplete(); } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //////////////////////////////////////////////////////////////////////////////// package com.esri.builder.controllers.supportClasses { import com.esri.builder.model.WidgetType; import com.esri.builder.model.WidgetTypeRegistryModel; import com.esri.builder.supportClasses.FileUtil; import com.esri.builder.supportClasses.LogUtil; import com.esri.builder.views.BuilderAlert; import flash.events.EventDispatcher; import flash.filesystem.File; import flash.utils.Dictionary; import mx.logging.ILogger; import mx.logging.Log; import mx.resources.ResourceManager; public class StartupWidgetTypeLoader extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(StartupWidgetTypeLoader); private var widgetTypeArr:Array = []; private var pendingLoaders:Array; public function loadWidgetTypes():void { if (Log.isInfo()) { LOG.info('Loading modules...'); } var moduleFiles:Array = getModuleFiles(WellKnownDirectories.getInstance().bundledModules) .concat(getModuleFiles(WellKnownDirectories.getInstance().customModules)); var swfFileAndXMLFileMaps:Array = mapFilenameToModuleSWFAndXMLFiles(moduleFiles); var processedFileNames:Array = []; var loaders:Array = []; for each (var moduleFile:File in moduleFiles) { var fileName:String = FileUtil.getFileName(moduleFile); if (Log.isDebug()) { LOG.debug('loading module {0}', fileName); } if (processedFileNames.indexOf(fileName) == -1) { processedFileNames.push(fileName); loaders.push(new WidgetTypeLoader(swfFileAndXMLFileMaps[0][fileName], swfFileAndXMLFileMaps[1][fileName])); } } pendingLoaders = loaders; for each (var loader:WidgetTypeLoader in loaders) { loader.addEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler); loader.addEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler); loader.load(); } checkIfWidgetTypeLoadersComplete(); } private function mapFilenameToModuleSWFAndXMLFiles(moduleFiles:Array):Array { var uniqueFileNameToSWF:Dictionary = new Dictionary(); var uniqueFileNameToXML:Dictionary = new Dictionary(); for each (var file:File in moduleFiles) { if (file.extension == "swf") { uniqueFileNameToSWF[FileUtil.getFileName(file)] = file; } else if (file.extension == "xml") { uniqueFileNameToXML[FileUtil.getFileName(file)] = file; } } return [ uniqueFileNameToSWF, uniqueFileNameToXML ]; } private function getModuleFiles(directory:File):Array { var moduleFiles:Array = []; if (directory.isDirectory) { const files:Array = directory.getDirectoryListing(); for each (var file:File in files) { if (file.isDirectory) { moduleFiles = moduleFiles.concat(getModuleFiles(file)); } else if (isModuleFile(file)) { moduleFiles.push(file); } } } return moduleFiles; } private function isModuleFile(file:File):Boolean { const moduleFileName:RegExp = /^.*Module\.(swf|xml)$/; return !file.isDirectory && (moduleFileName.test(file.name)); } private function checkIfWidgetTypeLoadersComplete():void { if (pendingLoaders.length === 0) { sortAndAssignWidgetTypes(); } } private function markModuleAsLoaded(loader:WidgetTypeLoader):void { var loaderIndex:int = pendingLoaders.indexOf(loader); if (loaderIndex > -1) { pendingLoaders.splice(loaderIndex, 1); } } private function sortAndAssignWidgetTypes():void { if (Log.isInfo()) { LOG.info('All modules resolved'); } for each (var widgetType:WidgetType in widgetTypeArr) { if (widgetType.isManaged) { WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType); } else { WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(widgetType); } } WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.sort(); WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.sort(); dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_TYPES_COMPLETE)); } private function loader_loadCompleteHandler(event:WidgetTypeLoaderEvent):void { var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader; loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler); loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler); var widgetType:WidgetType = event.widgetType; if (Log.isDebug()) { LOG.debug('Module {0} is resolved', widgetType.name); } widgetTypeArr.push(widgetType); markModuleAsLoaded(loader); checkIfWidgetTypeLoadersComplete(); } private function loader_loadErrorHandler(event:WidgetTypeLoaderEvent):void { var loader:WidgetTypeLoader = event.currentTarget as WidgetTypeLoader; loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_COMPLETE, loader_loadCompleteHandler); loader.removeEventListener(WidgetTypeLoaderEvent.LOAD_ERROR, loader_loadErrorHandler); var errorMessage:String = ResourceManager.getInstance().getString('BuilderStrings', 'importWidgetProcess.couldNotLoadCustomWidgets', [ loader.name ]); if (Log.isDebug()) { LOG.debug(errorMessage); } BuilderAlert.show(errorMessage, ResourceManager.getInstance().getString('BuilderStrings', 'error')); markModuleAsLoaded(loader); checkIfWidgetTypeLoadersComplete(); } } }
Clean up.
Clean up.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
f872070e54a03fc3591db39f9a3730f581220c84
frameworks/projects/apache/src/org/apache/flex/promises/enums/PromiseState.as
frameworks/projects/apache/src/org/apache/flex/promises/enums/PromiseState.as
package org.apache.flex.promises.enums { public class PromiseState { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- public static const BLOCKED:PromiseState = new PromiseState("blocked"); public static const FULFILLED:PromiseState = new PromiseState("fulfilled"); public static const PENDING:PromiseState = new PromiseState("pending"); public static const REJECTED:PromiseState = new PromiseState("rejected"); //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- public function PromiseState(stringValue:String) { this.stringValue = stringValue; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var stringValue:String; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- //---------------------------------- // toString //---------------------------------- public function toString():String { return stringValue; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.promises.enums { public class PromiseState { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- public static const BLOCKED:PromiseState = new PromiseState("blocked"); public static const FULFILLED:PromiseState = new PromiseState("fulfilled"); public static const PENDING:PromiseState = new PromiseState("pending"); public static const REJECTED:PromiseState = new PromiseState("rejected"); //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- public function PromiseState(stringValue:String) { this.stringValue = stringValue; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var stringValue:String; //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- //---------------------------------- // toString //---------------------------------- public function toString():String { return stringValue; } } }
Add license header
Add license header Signed-off-by: Erik de Bruin <[email protected]>
ActionScript
apache-2.0
adufilie/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk
68b5daf75b5f84e6ff8e1326144c6ecc1fa8efb6
src/com/mangui/HLS/streaming/Buffer.as
src/com/mangui/HLS/streaming/Buffer.as
package com.mangui.HLS.streaming { import com.mangui.HLS.*; import com.mangui.HLS.muxing.*; import com.mangui.HLS.streaming.*; import com.mangui.HLS.parsing.*; import com.mangui.HLS.utils.*; import flash.media.*; import flash.net.*; import flash.utils.*; /** Class that keeps the buffer filled. **/ public class Buffer { /** Reference to the framework controller. **/ private var _hls:HLS; /** The buffer with video tags. **/ private var _buffer:Vector.<Tag>; /** NetConnection legacy stuff. **/ private var _connection:NetConnection; /** The fragment loader. **/ private var _loader:Loader; /** Store that a fragment load is in progress. **/ private var _loading:Boolean; /** Interval for checking buffer and position. **/ private var _interval:Number; /** Next loading fragment sequence number. **/ /** The start position of the stream. **/ public var PlaybackStartPosition:Number = 0; /** start play time **/ private var _playback_start_time:Number; /** playback start PTS. **/ private var _playback_start_pts:Number; /** playlist start PTS when playback started. **/ private var _playlist_start_pts:Number; /** Current play position (relative position from beginning of sliding window) **/ private var _playback_current_position:Number; /** buffer last PTS. **/ private var _buffer_last_pts:Number; /** next buffer time. **/ private var _buffer_next_time:Number; /** previous buffer time. **/ private var _last_buffer:Number; /** Current playback state. **/ private var _state:String; /** Netstream instance used for playing the stream. **/ private var _stream:NetStream; /** The last tag that was appended to the buffer. **/ private var _tag:Number; /** soundtransform object. **/ private var _transform:SoundTransform; /** Reference to the video object. **/ private var _video:Object; /** Create the buffer. **/ public function Buffer(hls:HLS, loader:Loader, video:Object):void { _hls = hls; _loader = loader; _video = video; _hls.addEventListener(HLSEvent.MANIFEST,_manifestHandler); _connection = new NetConnection(); _connection.connect(null); _transform = new SoundTransform(); _transform.volume = 0.9; _setState(HLSStates.IDLE); }; /** Check the bufferlength. **/ private function _checkBuffer():void { var reachedend:Boolean = false; var buffer:Number = 0; // Calculate the buffer and position. if(_buffer.length) { buffer = (_buffer_last_pts - _playback_start_pts)/1000 - _stream.time; /** Current play time (time since beginning of playback) **/ var playback_current_time:Number = (Math.round(_stream.time*100 + _playback_start_time*100)/100); var playliststartpts:Number = _loader.getPlayListStartPTS(); var play_position:Number; if(playliststartpts < 0) { play_position = 0; } else { play_position = playback_current_time -(playliststartpts-_playlist_start_pts)/1000; } if(play_position != _playback_current_position || buffer !=_last_buffer) { if (play_position <0) { play_position = 0; } _playback_current_position = play_position; _last_buffer = buffer; _hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME,{ position:_playback_current_position, buffer:buffer, duration:_loader.getPlayListDuration()})); } } // Load new tags from fragment. if(buffer < _loader.getBufferLength() && !_loading) { var loadstatus:Number = _loader.loadfragment(_buffer_next_time,_buffer_last_pts,buffer,_loaderCallback,(_buffer.length == 0)); if (loadstatus == 0) { // good, new fragment being loaded _loading = true; } else if (loadstatus < 0) { /* it means sequence number requested is smaller than any seqnum available. it could happen on live playlist in 2 scenarios : if bandwidth available is lower than lowest quality needed bandwidth after long pause => seek(offset) to force a restart of the playback session we target second segment */ Log.txt("long pause on live stream or bad network quality"); seek(_loader.getSegmentMaxDuration()); return; } else if(loadstatus > 0) { //seqnum not available in playlist if (_hls.getType() == HLSTypes.VOD) { // if VOD playlist, it means we reached the end, on live playlist do nothing and wait ... reachedend = true; } } } // Append tags to buffer. if((_state == HLSStates.PLAYING && _stream.bufferLength < 10) || (_state == HLSStates.BUFFERING && buffer > 10)) { //Log.txt("appending data"); while(_tag < _buffer.length && _stream.bufferLength < 20) { try { _stream.appendBytes(_buffer[_tag].data); } catch (error:Error) { _errorHandler(new Error(_buffer[_tag].type+": "+ error.message)); } // Last tag done? Then append sequence end. if (reachedend ==true && _tag == _buffer.length - 1) { _stream.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); _stream.appendBytes(new ByteArray()); } _tag++; } } // Set playback state and complete. if(_stream.bufferLength < 3) { if(reachedend ==true) { if(_stream.bufferLength == 0) { _complete(); } } else if(_state == HLSStates.PLAYING) { _setState(HLSStates.BUFFERING); } } else if (_state == HLSStates.BUFFERING) { _setState(HLSStates.PLAYING); } }; /** The video completed playback. **/ private function _complete():void { _setState(HLSStates.IDLE); clearInterval(_interval); // _stream.pause(); _hls.dispatchEvent(new HLSEvent(HLSEvent.COMPLETE)); }; /** Dispatch an error to the controller. **/ private function _errorHandler(error:Error):void { _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,error.toString())); }; /** Return the current playback state. **/ public function getPosition():Number { return _playback_current_position; }; /** Return the current playback state. **/ public function getState():String { return _state; }; /** Add a fragment to the buffer. **/ private function _loaderCallback(tags:Vector.<Tag>,min_pts:Number,max_pts:Number):void { _buffer = _buffer.slice(_tag); _tag = 0; if (_playback_start_pts == 0) { _playback_start_pts = min_pts; _playlist_start_pts = _loader.getPlayListStartPTS(); } _buffer_last_pts = max_pts; tags.sort(_sortTagsbyDTS); for each (var t:Tag in tags) { _buffer.push(t); } _buffer_next_time=_playback_start_time+(_buffer_last_pts-_playback_start_pts)/1000; Log.txt("_loaderCallback,_buffer_next_time:"+ _buffer_next_time); _loading = false; }; /** Start streaming on manifest load. **/ private function _manifestHandler(event:HLSEvent):void { if(_state == HLSStates.IDLE) { _stream = new NetStream(_connection); _video.attachNetStream(_stream); _stream.play(null); _stream.soundTransform = _transform; _stream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); _stream.appendBytes(FLV.getHeader()); seek(PlaybackStartPosition); } }; /** Toggle playback. **/ public function pause():void { clearInterval(_interval); if(_state == HLSStates.PAUSED) { _setState(HLSStates.BUFFERING); _stream.resume(); _interval = setInterval(_checkBuffer,100); } else if(_state == HLSStates.PLAYING) { _setState(HLSStates.PAUSED); _stream.pause(); } }; /** Change playback state. **/ private function _setState(state:String):void { if(state != _state) { _state = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.STATE,_state)); } }; /** Sort the buffer by tag. **/ private function _sortTagsbyDTS(x:Tag,y:Tag):Number { if(x.dts < y.dts) { return -1; } else if (x.dts > y.dts) { return 1; } else { if(x.type == Tag.AVC_HEADER || x.type == Tag.AAC_HEADER) { return -1; } else if (y.type == Tag.AVC_HEADER || y.type == Tag.AAC_HEADER) { return 1; } else { if(x.type == Tag.AVC_NALU) { return -1; } else if (y.type == Tag.AVC_NALU) { return 1; } else { return 0; } } } }; /** Start playing data in the buffer. **/ public function seek(position:Number):void { _buffer = new Vector.<Tag>(); _loader.clearLoader(); _loading = false; _tag = 0; PlaybackStartPosition = position; _stream.seek(0); _stream.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); _playback_start_time = position; _playback_start_pts = 0; _buffer_next_time = _playback_start_time; _buffer_last_pts = 0; _last_buffer = 0; _setState(HLSStates.BUFFERING); clearInterval(_interval); _interval = setInterval(_checkBuffer,100); }; /** Stop playback. **/ public function stop():void { if(_stream) { _stream.pause(); } _loading = false; clearInterval(_interval); _setState(HLSStates.IDLE); }; /** Change the volume (set in the NetStream). **/ public function volume(percent:Number):void { _transform.volume = percent/100; if(_stream) { _stream.soundTransform = _transform; } }; } }
package com.mangui.HLS.streaming { import com.mangui.HLS.*; import com.mangui.HLS.muxing.*; import com.mangui.HLS.streaming.*; import com.mangui.HLS.parsing.*; import com.mangui.HLS.utils.*; import flash.media.*; import flash.net.*; import flash.utils.*; /** Class that keeps the buffer filled. **/ public class Buffer { /** Reference to the framework controller. **/ private var _hls:HLS; /** The buffer with video tags. **/ private var _buffer:Vector.<Tag>; /** NetConnection legacy stuff. **/ private var _connection:NetConnection; /** The fragment loader. **/ private var _loader:Loader; /** Store that a fragment load is in progress. **/ private var _loading:Boolean; /** Interval for checking buffer and position. **/ private var _interval:Number; /** Next loading fragment sequence number. **/ /** The start position of the stream. **/ public var PlaybackStartPosition:Number = 0; /** start play time **/ private var _playback_start_time:Number; /** playback start PTS. **/ private var _playback_start_pts:Number; /** playlist start PTS when playback started. **/ private var _playlist_start_pts:Number; /** Current play position (relative position from beginning of sliding window) **/ private var _playback_current_position:Number; /** buffer last PTS. **/ private var _buffer_last_pts:Number; /** next buffer time. **/ private var _buffer_next_time:Number; /** previous buffer time. **/ private var _last_buffer:Number; /** Current playback state. **/ private var _state:String; /** Netstream instance used for playing the stream. **/ private var _stream:NetStream; /** The last tag that was appended to the buffer. **/ private var _tag:Number; /** soundtransform object. **/ private var _transform:SoundTransform; /** Reference to the video object. **/ private var _video:Object; /** Create the buffer. **/ public function Buffer(hls:HLS, loader:Loader, video:Object):void { _hls = hls; _loader = loader; _video = video; _hls.addEventListener(HLSEvent.MANIFEST,_manifestHandler); _connection = new NetConnection(); _connection.connect(null); _transform = new SoundTransform(); _transform.volume = 0.9; _setState(HLSStates.IDLE); }; /** Check the bufferlength. **/ private function _checkBuffer():void { var reachedend:Boolean = false; var buffer:Number = 0; // Calculate the buffer and position. if(_buffer.length) { buffer = (_buffer_last_pts - _playback_start_pts)/1000 - _stream.time; /** Current play time (time since beginning of playback) **/ var playback_current_time:Number = (Math.round(_stream.time*100 + _playback_start_time*100)/100); var playliststartpts:Number = _loader.getPlayListStartPTS(); var play_position:Number; if(playliststartpts < 0) { play_position = 0; } else { play_position = playback_current_time -(playliststartpts-_playlist_start_pts)/1000; } if(play_position != _playback_current_position || buffer !=_last_buffer) { if (play_position <0) { play_position = 0; } _playback_current_position = play_position; _last_buffer = buffer; _hls.dispatchEvent(new HLSEvent(HLSEvent.MEDIA_TIME,{ position:_playback_current_position, buffer:buffer, duration:_loader.getPlayListDuration()})); } } // Load new tags from fragment. if(buffer < _loader.getBufferLength() && !_loading) { var loadstatus:Number = _loader.loadfragment(_buffer_next_time,_buffer_last_pts,buffer,_loaderCallback,(_buffer.length == 0)); if (loadstatus == 0) { // good, new fragment being loaded _loading = true; } else if (loadstatus < 0) { /* it means sequence number requested is smaller than any seqnum available. it could happen on live playlist in 2 scenarios : if bandwidth available is lower than lowest quality needed bandwidth after long pause => seek(offset) to force a restart of the playback session we target second segment */ Log.txt("long pause on live stream or bad network quality"); seek(_loader.getSegmentMaxDuration()); return; } else if(loadstatus > 0) { //seqnum not available in playlist if (_hls.getType() == HLSTypes.VOD) { // if VOD playlist, it means we reached the end, on live playlist do nothing and wait ... reachedend = true; } } } // Append tags to buffer. if((_state == HLSStates.PLAYING && _stream.bufferLength < 10) || (_state == HLSStates.BUFFERING && buffer > 10)) { //Log.txt("appending data"); while(_tag < _buffer.length && _stream.bufferLength < 20) { try { _stream.appendBytes(_buffer[_tag].data); } catch (error:Error) { _errorHandler(new Error(_buffer[_tag].type+": "+ error.message)); } // Last tag done? Then append sequence end. if (reachedend ==true && _tag == _buffer.length - 1) { _stream.appendBytesAction(NetStreamAppendBytesAction.END_SEQUENCE); _stream.appendBytes(new ByteArray()); } _tag++; } } // Set playback state and complete. if(_stream.bufferLength < 3) { if(reachedend ==true) { if(_stream.bufferLength == 0) { _complete(); } } else if(_state == HLSStates.PLAYING) { _setState(HLSStates.BUFFERING); } } else if (_state == HLSStates.BUFFERING) { _setState(HLSStates.PLAYING); } }; /** The video completed playback. **/ private function _complete():void { _setState(HLSStates.IDLE); clearInterval(_interval); // _stream.pause(); _hls.dispatchEvent(new HLSEvent(HLSEvent.COMPLETE)); }; /** Dispatch an error to the controller. **/ private function _errorHandler(error:Error):void { _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,error.toString())); }; /** Return the current playback state. **/ public function getPosition():Number { return _playback_current_position; }; /** Return the current playback state. **/ public function getState():String { return _state; }; /** Add a fragment to the buffer. **/ private function _loaderCallback(tags:Vector.<Tag>,min_pts:Number,max_pts:Number):void { _buffer = _buffer.slice(_tag); _tag = 0; if (_playback_start_pts == 0) { _playback_start_pts = min_pts; _playlist_start_pts = _loader.getPlayListStartPTS(); } _buffer_last_pts = max_pts; tags.sort(_sortTagsbyDTS); for each (var t:Tag in tags) { _buffer.push(t); } _buffer_next_time=_playback_start_time+(_buffer_last_pts-_playback_start_pts)/1000; Log.txt("_loaderCallback,_buffer_next_time:"+ _buffer_next_time); _loading = false; }; /** Start streaming on manifest load. **/ private function _manifestHandler(event:HLSEvent):void { if(_state == HLSStates.IDLE) { _stream = new NetStream(_connection); _video.attachNetStream(_stream); _stream.play(null); _stream.soundTransform = _transform; _stream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); _stream.appendBytes(FLV.getHeader()); seek(PlaybackStartPosition); } }; /** Toggle playback. **/ public function pause():void { clearInterval(_interval); if(_state == HLSStates.PAUSED) { _setState(HLSStates.BUFFERING); _stream.resume(); _interval = setInterval(_checkBuffer,100); } else if(_state == HLSStates.PLAYING) { _setState(HLSStates.PAUSED); _stream.pause(); } }; /** Change playback state. **/ private function _setState(state:String):void { if(state != _state) { _state = state; _hls.dispatchEvent(new HLSEvent(HLSEvent.STATE,_state)); } }; /** Sort the buffer by tag. **/ private function _sortTagsbyDTS(x:Tag,y:Tag):Number { if(x.dts < y.dts) { return -1; } else if (x.dts > y.dts) { return 1; } else { if(x.type == Tag.AVC_HEADER || x.type == Tag.AAC_HEADER) { return -1; } else if (y.type == Tag.AVC_HEADER || y.type == Tag.AAC_HEADER) { return 1; } else { if(x.type == Tag.AVC_NALU) { return -1; } else if (y.type == Tag.AVC_NALU) { return 1; } else { return 0; } } } }; /** Start playing data in the buffer. **/ public function seek(position:Number):void { _buffer = new Vector.<Tag>(); _loader.clearLoader(); _loading = false; _tag = 0; PlaybackStartPosition = position; _stream.seek(0); _stream.appendBytesAction(NetStreamAppendBytesAction.RESET_SEEK); _playback_start_time = position; _playback_start_pts = 0; _buffer_next_time = _playback_start_time; _buffer_last_pts = 0; _last_buffer = 0; _setState(HLSStates.BUFFERING); clearInterval(_interval); _interval = setInterval(_checkBuffer,100); }; /** Stop playback. **/ public function stop():void { if(_stream) { _stream.pause(); } _loading = false; clearInterval(_interval); _setState(HLSStates.IDLE); }; /** Change the volume (set in the NetStream). **/ public function volume(percent:Number):void { _transform.volume = percent/100; if(_stream) { _stream.soundTransform = _transform; } }; } }
trim trailing spaces
trim trailing spaces
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
8ded0cd5c6232d88cf501e7664dbe2a721195405
src/com/mangui/HLS/streaming/Getter.as
src/com/mangui/HLS/streaming/Getter.as
package com.mangui.HLS.streaming { import com.mangui.HLS.*; import com.mangui.HLS.parsing.*; import com.mangui.HLS.utils.*; import flash.events.*; import flash.net.*; import flash.utils.*; /** Loader for hls streaming manifests. **/ public class Getter { /** Reference to the hls framework controller. **/ private var _hls:HLS; /** Array with levels. **/ private var _levels:Array = []; /** Object that fetches the manifest. **/ private var _urlloader:URLLoader; /** Link to the M3U8 file. **/ private var _url:String; /** Amount of playlists still need loading. **/ private var _toLoad:Number; /** are all playlists filled ? **/ private var _canStart:Boolean; /** initial reload timer **/ private var _fragmentDuration:Number = 5000; /** Timeout ID for reloading live playlists. **/ private var _timeoutID:Number; /** Streaming type (live, ondemand). **/ private var _type:String; /** last reload manifest time **/ private var _reload_playlists_timer:uint; /** Setup the loader. **/ public function Getter(hls:HLS) { _hls = hls; _hls.addEventListener(HLSEvent.STATE,_stateHandler); _levels = []; _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE,_loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR,_errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,_errorHandler); }; /** Loading failed; return errors. **/ private function _errorHandler(event:ErrorEvent):void { var txt:String = "Cannot load M3U8: "+event.text; if(event is SecurityErrorEvent) { txt = "Cannot load M3U8: crossdomain access denied"; } else if (event is IOErrorEvent) { txt = "Cannot load M3U8: 404 not found"; } _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,txt)); }; /** return true if first two levels contain at least 2 fragments **/ private function _areFirstLevelsFilled():Boolean { for(var i:Number = 0; (i < _levels.length) && (i < 2); i++) { if(_levels[i].fragments.length < 2) { return false; } } return true; }; /** Return the current manifest. **/ public function getLevels():Array { return _levels; }; /** Return the stream type. **/ public function getType():String { return _type; }; /** Load the manifest file. **/ public function load(url:String):void { _url = url; _levels = []; _canStart = false; _reload_playlists_timer = getTimer(); _urlloader.load(new URLRequest(_url)); }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event:Event):void { _loadManifest(String(event.target.data)); }; /** load a playlist **/ private function _loadPlaylist(string:String,url:String,index:Number):void { if(string != null && string.length != 0) { var frags:Array = Manifest.getFragments(string,url); // set fragment and update sequence number range _levels[index].setFragments(frags); _levels[index].targetduration = Manifest.getTargetDuration(string); _levels[index].start_seqnum = frags[0].seqnum; _levels[index].end_seqnum = frags[frags.length-1].seqnum; _levels[index].duration = frags[frags.length-1].start + frags[frags.length-1].duration; _fragmentDuration = _levels[index].targetduration; } if(--_toLoad == 0) { // Check whether the stream is live or not finished yet if(Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; } else { _type = HLSTypes.LIVE; var timeout:Number = Math.max(100,_reload_playlists_timer + _fragmentDuration - getTimer()); Log.txt("Live Playlist parsing finished: reload in " + timeout + " ms"); _timeoutID = setTimeout(_loadPlaylists,timeout); } if (!_canStart && (_canStart =_areFirstLevelsFilled())) { Log.txt("first 2 levels are filled with at least 2 fragments, notify event"); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST,_levels)); } } }; /** load First Level Playlist **/ private function _loadManifest(string:String):void { // Check for M3U8 playlist or manifest. if(string.indexOf(Manifest.HEADER) == 0) { //1 level playlist, create unique level and parse playlist if(string.indexOf(Manifest.FRAGMENT) > 0) { var level:Level = new Level(); level.url = _url; _levels.push(level); _toLoad = 1; Log.txt("1 Level Playlist, load it"); _loadPlaylist(string,_url,0); } else if(string.indexOf(Manifest.LEVEL) > 0) { //adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string,_url); _loadPlaylists(); } } else { var message:String = "Manifest is not a valid M3U8 file" + _url; _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,message)); } }; /** load/reload all M3U8 playlists **/ private function _loadPlaylists():void { _reload_playlists_timer = getTimer(); _toLoad = _levels.length; //Log.txt("HLS Playlist, with " + _toLoad + " levels"); for(var i:Number = 0; i < _levels.length; i++) { new Manifest().loadPlaylist(_levels[i].url,_loadPlaylist,_errorHandler,i); } }; /** When the framework idles out, reloading is cancelled. **/ public function _stateHandler(event:HLSEvent):void { if(event.state == HLSStates.IDLE) { clearTimeout(_timeoutID); } }; } }
package com.mangui.HLS.streaming { import com.mangui.HLS.*; import com.mangui.HLS.parsing.*; import com.mangui.HLS.utils.*; import flash.events.*; import flash.net.*; import flash.utils.*; /** Loader for hls streaming manifests. **/ public class Getter { /** Reference to the hls framework controller. **/ private var _hls:HLS; /** Array with levels. **/ private var _levels:Array = []; /** Object that fetches the manifest. **/ private var _urlloader:URLLoader; /** Link to the M3U8 file. **/ private var _url:String; /** Amount of playlists still need loading. **/ private var _toLoad:Number; /** are all playlists filled ? **/ private var _canStart:Boolean; /** initial reload timer **/ private var _fragmentDuration:Number = 5000; /** Timeout ID for reloading live playlists. **/ private var _timeoutID:Number; /** Streaming type (live, ondemand). **/ private var _type:String; /** last reload manifest time **/ private var _reload_playlists_timer:uint; /** Setup the loader. **/ public function Getter(hls:HLS) { _hls = hls; _hls.addEventListener(HLSEvent.STATE,_stateHandler); _levels = []; _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE,_loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR,_errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,_errorHandler); }; /** Loading failed; return errors. **/ private function _errorHandler(event:ErrorEvent):void { var txt:String = "Cannot load M3U8: "+event.text; if(event is SecurityErrorEvent) { txt = "Cannot load M3U8: crossdomain access denied"; } else if (event is IOErrorEvent) { txt = "Cannot load M3U8: 404 not found"; } _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,txt)); }; /** return true if first two levels contain at least 2 fragments **/ private function _areFirstLevelsFilled():Boolean { for(var i:Number = 0; (i < _levels.length) && (i < 2); i++) { if(_levels[i].fragments.length < 2) { return false; } } return true; }; /** Return the current manifest. **/ public function getLevels():Array { return _levels; }; /** Return the stream type. **/ public function getType():String { return _type; }; /** Load the manifest file. **/ public function load(url:String):void { _url = url; _levels = []; _canStart = false; _reload_playlists_timer = getTimer(); _urlloader.load(new URLRequest(_url)); }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event:Event):void { _loadManifest(String(event.target.data)); }; /** load a playlist **/ private function _loadPlaylist(string:String,url:String,index:Number):void { if(string != null && string.length != 0) { var frags:Array = Manifest.getFragments(string,url); // set fragment and update sequence number range _levels[index].setFragments(frags); _levels[index].targetduration = Manifest.getTargetDuration(string); _levels[index].start_seqnum = frags[0].seqnum; _levels[index].end_seqnum = frags[frags.length-1].seqnum; _levels[index].duration = frags[frags.length-1].start + frags[frags.length-1].duration; _fragmentDuration = 1000*_levels[index].targetduration; } if(--_toLoad == 0) { // Check whether the stream is live or not finished yet if(Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; } else { _type = HLSTypes.LIVE; var timeout:Number = Math.max(100,_reload_playlists_timer + _fragmentDuration - getTimer()); Log.txt("Live Playlist parsing finished: reload in " + timeout + " ms"); _timeoutID = setTimeout(_loadPlaylists,timeout); } if (!_canStart && (_canStart =_areFirstLevelsFilled())) { Log.txt("first 2 levels are filled with at least 2 fragments, notify event"); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST,_levels)); } } }; /** load First Level Playlist **/ private function _loadManifest(string:String):void { // Check for M3U8 playlist or manifest. if(string.indexOf(Manifest.HEADER) == 0) { //1 level playlist, create unique level and parse playlist if(string.indexOf(Manifest.FRAGMENT) > 0) { var level:Level = new Level(); level.url = _url; _levels.push(level); _toLoad = 1; Log.txt("1 Level Playlist, load it"); _loadPlaylist(string,_url,0); } else if(string.indexOf(Manifest.LEVEL) > 0) { //adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string,_url); _loadPlaylists(); } } else { var message:String = "Manifest is not a valid M3U8 file" + _url; _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR,message)); } }; /** load/reload all M3U8 playlists **/ private function _loadPlaylists():void { _reload_playlists_timer = getTimer(); _toLoad = _levels.length; //Log.txt("HLS Playlist, with " + _toLoad + " levels"); for(var i:Number = 0; i < _levels.length; i++) { new Manifest().loadPlaylist(_levels[i].url,_loadPlaylist,_errorHandler,i); } }; /** When the framework idles out, reloading is cancelled. **/ public function _stateHandler(event:HLSEvent):void { if(event.state == HLSStates.IDLE) { clearTimeout(_timeoutID); } }; } }
fix playlist reloading too often ...
fix playlist reloading too often ...
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
d53ed7d95954436dec47d2532c2f5161a9a4a78a
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSValuesImpl.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSValuesImpl.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.system.ApplicationDomain; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; import flash.utils.getQualifiedSuperclassName; import org.apache.flex.events.EventDispatcher; import org.apache.flex.events.ValueChangeEvent; /** * The SimpleCSSValuesImpl class implements a minimal set of * CSS lookup rules that is sufficient for most applications. * It does not support attribute selectors or descendant selectors * or id selectors. It will filter on a custom -flex-flash * media query but not other media queries. It can be * replaced with other implementations that handle more complex * selector lookups. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleCSSValuesImpl extends EventDispatcher implements IValuesImpl { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleCSSValuesImpl() { super(); } private var mainClass:Object; private var conditionCombiners:Object; /** * @copy org.apache.flex.core.IValuesImpl#init() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function init(mainClass:Object):void { var styleClassName:String; var c:Class; if (!values) { values = {}; this.mainClass = mainClass; var mainClassName:String = getQualifiedClassName(mainClass); styleClassName = "_" + mainClassName + "_Styles"; c = ApplicationDomain.currentDomain.getDefinition(styleClassName) as Class; } else { c = mainClass.constructor as Class; } generateCSSStyleDeclarations(c["factoryFunctions"], c["data"]); } /** * Process the encoded CSS data into data structures. Usually not called * directly by application developers. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function generateCSSStyleDeclarations(factoryFunctions:Object, arr:Array):void { if (factoryFunctions == null) return; if (arr == null) return; var declarationName:String = ""; var segmentName:String = ""; var n:int = arr.length; for (var i:int = 0; i < n; i++) { var className:int = arr[i]; if (className == CSSClass.CSSSelector) { var selectorName:String = arr[++i]; segmentName = selectorName + segmentName; if (declarationName != "") declarationName += " "; declarationName += segmentName; segmentName = ""; } else if (className == CSSClass.CSSCondition) { if (!conditionCombiners) { conditionCombiners = {}; conditionCombiners["class"] = "."; conditionCombiners["id"] = "#"; conditionCombiners["pseudo"] = ':'; } var conditionType:String = arr[++i]; var conditionName:String = arr[++i]; segmentName = segmentName + conditionCombiners[conditionType] + conditionName; } else if (className == CSSClass.CSSStyleDeclaration) { var factoryName:int = arr[++i]; // defaultFactory or factory var defaultFactory:Boolean = factoryName == CSSFactory.DefaultFactory; /* if (defaultFactory) { mergedStyle = styleManager.getMergedStyleDeclaration(declarationName); style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); } else { style = styleManager.getStyleDeclaration(declarationName); if (!style) { style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); if (factoryName == CSSFactory.Override) newSelectors.push(style); } } */ var mq:String = null; var o:Object; if (i < n - 2) { // peek ahead to see if there is a media query if (arr[i + 1] == CSSClass.CSSMediaQuery) { mq = arr[i + 2]; i += 2; declarationName = mq + "_" + declarationName; } } var finalName:String; var valuesFunction:Function; var valuesObject:Object; if (defaultFactory) { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); } else { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); } if (isValidStaticMediaQuery(mq)) { finalName = fixNames(declarationName, mq); o = values[finalName]; if (o == null) values[finalName] = valuesObject; else { valuesFunction.prototype = o; values[finalName] = new valuesFunction(); } } declarationName = ""; } } } private function isValidStaticMediaQuery(mq:String):Boolean { if (mq == null) return true; if (mq == "-flex-flash") return true; // TODO: (aharui) other media query return false; } private function fixNames(s:String, mq:String):String { if (mq != null) s = s.substr(mq.length + 1); // 1 more for the hyphen if (s == "") return "*"; var arr:Array = s.split(" "); var n:int = arr.length; for (var i:int = 0; i < n; i++) { var segmentName:String = arr[i]; if (segmentName.charAt(0) == "#" || segmentName.charAt(0) == ".") continue; var c:int = segmentName.lastIndexOf("."); if (c > -1) // it is 0 for class selectors { segmentName = segmentName.substr(0, c) + "::" + segmentName.substr(c + 1); arr[i] = segmentName; } } return arr.join(" "); } /** * The map of values. The format is not documented and it is not recommended * to manipulate this structure directly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var values:Object; /** * @copy org.apache.flex.core.IValuesImpl#getValue() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):* { var c:int = valueName.indexOf("-"); while (c != -1) { valueName = valueName.substr(0, c) + valueName.charAt(c + 1).toUpperCase() + valueName.substr(c + 2); c = valueName.indexOf("-"); } var value:*; var o:Object; var className:String; var selectorName:String; if (thisObject is IStyleableObject) { var styleable:IStyleableObject = IStyleableObject(thisObject); if (styleable.style != null) { try { value = styleable.style[valueName]; } catch (e:Error) { value = undefined; } if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } className = styleable.className; if (state) { selectorName = className + ":" + state; o = values["." + selectorName]; if (o) { value = o[valueName]; if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } } o = values["." + className]; if (o) { value = o[valueName]; if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } } className = getQualifiedClassName(thisObject); var thisInstance:Object = thisObject; while (className != "Object") { if (state) { selectorName = className + ":" + state; o = values[selectorName]; if (o) { value = o[valueName]; if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } } o = values[className]; if (o) { value = o[valueName]; if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } className = getQualifiedSuperclassName(thisInstance); thisInstance = getDefinitionByName(className); } if (inheritingStyles[valueName] != null && thisObject is IChild) { var parentObject:Object = IChild(thisObject).parent; if (parentObject) return getValue(parentObject, valueName, state, attrs); } o = values["global"]; if (o) { value = o[valueName]; if (value !== undefined) return value; } o = values["*"]; if(o) { return o[valueName]; } return undefined; } private function getInheritingValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):* { var value:*; if (thisObject is IChild) { var parentObject:Object = IChild(thisObject).parent; if (parentObject) { value = getValue(parentObject, valueName, state, attrs); if (value == "inherit" || value === undefined) return getInheritingValue(parentObject, valueName, state, attrs); if (value !== undefined) return value; } } return "inherit"; } /** * A method that stores a value to be shared with other objects. * It is global, not per instance. Fancier implementations * may store shared values per-instance. * * @param thisObject An object associated with this value. Thiis * parameter is ignored. * @param valueName The name or key of the value being stored. * @param The value to be stored. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function setValue(thisObject:Object, valueName:String, value:*):void { var c:int = valueName.indexOf("-"); while (c != -1) { valueName = valueName.substr(0, c) + valueName.charAt(c + 1).toUpperCase() + valueName..substr(c + 2); c = valueName.indexOf("-"); } var oldValue:Object = values[valueName]; if (oldValue != value) { values[valueName] = value; dispatchEvent(new ValueChangeEvent(ValueChangeEvent.VALUE_CHANGE, false, false, oldValue, value)); } } /** * @copy org.apache.flex.core.IValuesImpl#newInstance() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function newInstance(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):* { var c:Class = getValue(thisObject, valueName, state, attrs); if (c) return new c(); return null; } /** * @copy org.apache.flex.core.IValuesImpl#getInstance() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getInstance(valueName:String):Object { var o:Object = values["global"]; if (o is Class) { o[valueName] = new o[valueName](); if (o[valueName] is IDocument) o[valueName].setDocument(mainClass); } return o[valueName]; } /** * @copy org.apache.flex.core.IValuesImpl#convertColor() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function convertColor(value:Object):uint { if (!(value is String)) return uint(value); var stringValue:String = value as String; if (stringValue.charAt(0) == '#') return uint(stringValue.substr(1)); return uint(stringValue); } /** * A map of inheriting styles * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public static var inheritingStyles:Object = { "color" : 1, "fontFamily" : 1, "fontSize" : 1, "fontStyle" : 1 } } } class CSSClass { public static const CSSSelector:int = 0; public static const CSSCondition:int = 1; public static const CSSStyleDeclaration:int = 2; public static const CSSMediaQuery:int = 3; } class CSSFactory { public static const DefaultFactory:int = 0; public static const Factory:int = 1; public static const Override:int = 2; } class CSSDataType { public static const Native:int = 0; public static const Definition:int = 1; }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.system.ApplicationDomain; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; import flash.utils.getQualifiedSuperclassName; import org.apache.flex.events.EventDispatcher; import org.apache.flex.events.ValueChangeEvent; /** * The SimpleCSSValuesImpl class implements a minimal set of * CSS lookup rules that is sufficient for most applications. * It does not support attribute selectors or descendant selectors * or id selectors. It will filter on a custom -flex-flash * media query but not other media queries. It can be * replaced with other implementations that handle more complex * selector lookups. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleCSSValuesImpl extends EventDispatcher implements IValuesImpl { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleCSSValuesImpl() { super(); } private var mainClass:Object; private var conditionCombiners:Object; /** * @copy org.apache.flex.core.IValuesImpl#init() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function init(mainClass:Object):void { var styleClassName:String; var c:Class; if (!values) { values = {}; this.mainClass = mainClass; var mainClassName:String = getQualifiedClassName(mainClass); styleClassName = "_" + mainClassName + "_Styles"; c = ApplicationDomain.currentDomain.getDefinition(styleClassName) as Class; } else { c = mainClass.constructor as Class; } generateCSSStyleDeclarations(c["factoryFunctions"], c["data"]); } /** * Process the encoded CSS data into data structures. Usually not called * directly by application developers. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function generateCSSStyleDeclarations(factoryFunctions:Object, arr:Array):void { if (factoryFunctions == null) return; if (arr == null) return; var declarationName:String = ""; var segmentName:String = ""; var n:int = arr.length; for (var i:int = 0; i < n; i++) { var className:int = arr[i]; if (className == CSSClass.CSSSelector) { var selectorName:String = arr[++i]; segmentName = selectorName + segmentName; if (declarationName != "") declarationName += " "; declarationName += segmentName; segmentName = ""; } else if (className == CSSClass.CSSCondition) { if (!conditionCombiners) { conditionCombiners = {}; conditionCombiners["class"] = "."; conditionCombiners["id"] = "#"; conditionCombiners["pseudo"] = ':'; } var conditionType:String = arr[++i]; var conditionName:String = arr[++i]; segmentName = segmentName + conditionCombiners[conditionType] + conditionName; } else if (className == CSSClass.CSSStyleDeclaration) { var factoryName:int = arr[++i]; // defaultFactory or factory var defaultFactory:Boolean = factoryName == CSSFactory.DefaultFactory; /* if (defaultFactory) { mergedStyle = styleManager.getMergedStyleDeclaration(declarationName); style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); } else { style = styleManager.getStyleDeclaration(declarationName); if (!style) { style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); if (factoryName == CSSFactory.Override) newSelectors.push(style); } } */ var mq:String = null; var o:Object; if (i < n - 2) { // peek ahead to see if there is a media query if (arr[i + 1] == CSSClass.CSSMediaQuery) { mq = arr[i + 2]; i += 2; declarationName = mq + "_" + declarationName; } } var finalName:String; var valuesFunction:Function; var valuesObject:Object; if (defaultFactory) { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); } else { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); } if (isValidStaticMediaQuery(mq)) { finalName = fixNames(declarationName, mq); o = values[finalName]; if (o == null) values[finalName] = valuesObject; else { valuesFunction.prototype = o; values[finalName] = new valuesFunction(); } } declarationName = ""; } } } private function isValidStaticMediaQuery(mq:String):Boolean { if (mq == null) return true; if (mq == "-flex-flash") return true; // TODO: (aharui) other media query return false; } private function fixNames(s:String, mq:String):String { if (mq != null) s = s.substr(mq.length + 1); // 1 more for the hyphen if (s == "") return "*"; var arr:Array = s.split(" "); var n:int = arr.length; for (var i:int = 0; i < n; i++) { var segmentName:String = arr[i]; if (segmentName.charAt(0) == "#" || segmentName.charAt(0) == ".") continue; var c:int = segmentName.lastIndexOf("."); if (c > -1) // it is 0 for class selectors { segmentName = segmentName.substr(0, c) + "::" + segmentName.substr(c + 1); arr[i] = segmentName; } } return arr.join(" "); } /** * The map of values. The format is not documented and it is not recommended * to manipulate this structure directly. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public var values:Object; /** * @copy org.apache.flex.core.IValuesImpl#getValue() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):* { var c:int = valueName.indexOf("-"); while (c != -1) { valueName = valueName.substr(0, c) + valueName.charAt(c + 1).toUpperCase() + valueName.substr(c + 2); c = valueName.indexOf("-"); } var value:*; var o:Object; var className:String; var selectorName:String; if (thisObject is IStyleableObject) { var styleable:IStyleableObject = IStyleableObject(thisObject); if (styleable.style != null) { try { value = styleable.style[valueName]; } catch (e:Error) { value = undefined; } if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } className = styleable.className; if (state) { selectorName = className + ":" + state; o = values["." + selectorName]; if (o) { value = o[valueName]; if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } } o = values["." + className]; if (o) { value = o[valueName]; if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } } className = getQualifiedClassName(thisObject); var thisInstance:Object = thisObject; while (className != "Object") { if (state) { selectorName = className + ":" + state; o = values[selectorName]; if (o) { value = o[valueName]; if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } } o = values[className]; if (o) { value = o[valueName]; if (value == "inherit") return getInheritingValue(thisObject, valueName, state, attrs); if (value !== undefined) return value; } className = getQualifiedSuperclassName(thisInstance); thisInstance = getDefinitionByName(className); } if (inheritingStyles[valueName] != null && thisObject is IChild) { var parentObject:Object = IChild(thisObject).parent; if (parentObject) return getValue(parentObject, valueName, state, attrs); } o = values["global"]; if (o) { value = o[valueName]; if (value !== undefined) return value; } o = values["*"]; if(o) { return o[valueName]; } return undefined; } private function getInheritingValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):* { var value:*; if (thisObject is IChild) { var parentObject:Object = IChild(thisObject).parent; if (parentObject) { value = getValue(parentObject, valueName, state, attrs); if (value == "inherit" || value === undefined) return getInheritingValue(parentObject, valueName, state, attrs); if (value !== undefined) return value; } } return "inherit"; } /** * A method that stores a value to be shared with other objects. * It is global, not per instance. Fancier implementations * may store shared values per-instance. * * @param thisObject An object associated with this value. Thiis * parameter is ignored. * @param valueName The name or key of the value being stored. * @param The value to be stored. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function setValue(thisObject:Object, valueName:String, value:*):void { var c:int = valueName.indexOf("-"); while (c != -1) { valueName = valueName.substr(0, c) + valueName.charAt(c + 1).toUpperCase() + valueName..substr(c + 2); c = valueName.indexOf("-"); } var oldValue:Object = values[valueName]; if (oldValue != value) { values[valueName] = value; dispatchEvent(new ValueChangeEvent(ValueChangeEvent.VALUE_CHANGE, false, false, oldValue, value)); } } /** * @copy org.apache.flex.core.IValuesImpl#newInstance() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function newInstance(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):* { var c:Class = getValue(thisObject, valueName, state, attrs); if (c) return new c(); return null; } /** * @copy org.apache.flex.core.IValuesImpl#getInstance() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getInstance(valueName:String):Object { var o:Object = values["global"]; if (o is Class) { o[valueName] = new o[valueName](); if (o[valueName] is IDocument) o[valueName].setDocument(mainClass); } return o[valueName]; } /** * @copy org.apache.flex.core.IValuesImpl#convertColor() * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function convertColor(value:Object):uint { if (!(value is String)) return uint(value); var stringValue:String = value as String; if (stringValue.charAt(0) == '#') return uint(stringValue.substr(1)); return uint(stringValue); } /** * A map of inheriting styles * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public static var inheritingStyles:Object = { "color" : 1, "fontFamily" : 1, "fontSize" : 1, "fontStyle" : 1, "textAlign" : 1 } } } class CSSClass { public static const CSSSelector:int = 0; public static const CSSCondition:int = 1; public static const CSSStyleDeclaration:int = 2; public static const CSSMediaQuery:int = 3; } class CSSFactory { public static const DefaultFactory:int = 0; public static const Factory:int = 1; public static const Override:int = 2; } class CSSDataType { public static const Native:int = 0; public static const Definition:int = 1; }
handle text-align
handle text-align
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
0ab0ab2ef2c475c04aaccaa052c9e7206817604b
plugins/playlistApiPlugin/src/com/kaltura/kdpfl/plugin/component/PlaylistEntryVO.as
plugins/playlistApiPlugin/src/com/kaltura/kdpfl/plugin/component/PlaylistEntryVO.as
package com.kaltura.kdpfl.plugin.component { import com.kaltura.vo.KalturaPlayableEntry; import mx.utils.ObjectProxy; [Bindable] /** * This class represents playlist entry object * @author michalr * */ public class PlaylistEntryVO extends ObjectProxy { /** * Kaltura entry object */ public var entry:KalturaPlayableEntry; public var isOver:Boolean; public function PlaylistEntryVO(entry:KalturaPlayableEntry) { this.entry = entry; } ////////////////////////////////////////////////////////////////////// // the following getters are required to keep backward compatibility ////////////////////////////////////////////////////////////////////// public function get name():String { return entry.name; } public function get thumbnailUrl():String { return entry.thumbnailUrl; } public function get description():String { return entry.description; } public function get duration():int { return entry.duration; } public function get rank():Number { return entry.rank; } public function get plays():int { return entry.plays; } public function get entryId():String { return entry.entryId; } } }
package com.kaltura.kdpfl.plugin.component { import com.kaltura.vo.KalturaPlayableEntry; import mx.utils.ObjectProxy; [Bindable] /** * This class represents playlist entry object * @author michalr * */ public class PlaylistEntryVO extends ObjectProxy { /** * Kaltura entry object */ public var entry:KalturaPlayableEntry; public var isOver:Boolean; public function PlaylistEntryVO(entry:KalturaPlayableEntry) { this.entry = entry; } ////////////////////////////////////////////////////////////////////// // the following getters are required to keep backward compatibility ////////////////////////////////////////////////////////////////////// public function get name():String { return entry.name; } public function get thumbnailUrl():String { return entry.thumbnailUrl; } public function get description():String { return entry.description; } public function get duration():int { return entry.duration; } public function get rank():Number { return entry.rank; } public function get plays():int { return entry.plays; } public function get entryId():String { return entry.entryId; } public function get tags():String{ return entry.tags; } public function get categories():String{ return entry.categories; } public function get createdAt():int{ return entry.createdAt; } public function get userScreenName():String { return entry.userScreenName; } } }
add backward compatibility to this.tags, categories, createdAt and userScreenName
qnd: add backward compatibility to this.tags, categories, createdAt and userScreenName git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@86344 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
ActionScript
agpl-3.0
kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp
d894c8965be5cf4a915c09a484efa4adcb0c75a4
flex/AirTestFairy/src/com/testfairy/AirTestFairy.as
flex/AirTestFairy/src/com/testfairy/AirTestFairy.as
package com.testfairy { import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirTestFairy { public static function get isSupported():Boolean { return Capabilities.manufacturer.indexOf("iOS") > -1; } public static function begin():void { traceLog("TESTFAIRY LOG"); call("begin"); } public static function pushFeedbackController():void { traceLog("TESTFAIRY LOG"); call("pushFeedbackController"); } public static function setCorrelationId(value:String):void { traceLog("TESTFAIRY LOG"); if (value) { call("setCorrelationId", value); } } public static function getSessionUrl():String { traceLog("TESTFAIRY LOG"); return call("getSessionUrl"); } public static function pause():void { traceLog("TESTFAIRY LOG"); call("pause"); } public static function resume():void { traceLog("TESTFAIRY LOG"); call("resume"); } public static function takeScreenshot():void { traceLog("TESTFAIRY LOG"); call("takeScreenshot"); } public static function log(value:String):void { traceLog("TESTFAIRY LOG"); if (value) { call("log", value); } } private static const EXTENSION_ID : String = "com.testfairy"; private static var _context : ExtensionContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null); private static function call(...args):* { if (!isSupported) return null; if (!_context) throw new Error("Extension context is null. Please check if extension.xml is setup correctly."); return _context.call.apply(_context, args); } private static function traceLog(msg:String):void { trace("Adam" + msg); } } }
package com.testfairy { import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirTestFairy { public static function get isSupported():Boolean { return Capabilities.manufacturer.indexOf("iOS") > -1; } public static function begin(appToken:String):void { if (value) { call("begin", appToken); } } public static function pushFeedbackController():void { call("pushFeedbackController"); } public static function setCorrelationId(value:String):void { if (value) { call("setCorrelationId", value); } } public static function getSessionUrl():String { return call("getSessionUrl"); } public static function pause():void { call("pause"); } public static function resume():void { call("resume"); } public static function takeScreenshot():void { call("takeScreenshot"); } public static function log(value:String):void { if (value) { call("log", value); } } public static function getVersion():String { return call("getVersion"); } private static const EXTENSION_ID : String = "com.testfairy"; private static var _context : ExtensionContext = ExtensionContext.createExtensionContext(EXTENSION_ID, null); private static function call(...args):* { if (!isSupported) return null; if (!_context) throw new Error("Extension context is null. Please check if extension.xml is setup correctly."); return _context.call.apply(_context, args); } private static function traceLog(msg:String):void { } } }
Update AirTestFairy.as
Update AirTestFairy.as
ActionScript
apache-2.0
testfairy/testfairy-ane,testfairy/testfairy-ane
25f87a7456aafa1969dd32654b5089059e4cccb2
src/aerys/minko/type/Signal.as
src/aerys/minko/type/Signal.as
package aerys.minko.type { public final class Signal { private var _name : String; private var _callbacks : Vector.<Function>; private var _numCallbacks : uint; private var _executed : Boolean; private var _numAdded : uint; private var _toAdd : Vector.<Function>; private var _numRemoved : uint; private var _toRemove : Vector.<Function>; public function get numCallbacks() : uint { return _numCallbacks; } public function Signal(name : String) { _name = name; _callbacks = new <Function>[]; } public function add(callback : Function) : void { if (_callbacks.indexOf(callback) >= 0) throw new Error('The same callback cannot be added twice.'); if (_executed) { if (_toAdd) _toAdd.push(callback); else _toAdd = new <Function>[callback]; ++_numAdded; return ; } _callbacks[_numCallbacks] = callback; ++_numCallbacks; } public function remove(callback : Function) : void { var index : int = _callbacks.indexOf(callback); if (index < 0) throw new Error('This callback does not exist.'); if (_executed) { if (_toRemove) _toRemove.push(callback); else _toRemove = new <Function>[callback]; ++_numRemoved; return ; } --_numCallbacks; _callbacks[index] = _callbacks[_numCallbacks]; _callbacks.length = _numCallbacks; } public function hasCallback(callback : Function) : Boolean { return _callbacks.indexOf(callback) >= 0; } public function execute(...params) : void { if (_numCallbacks) { _executed = true; for (var i : uint = 0; i < _numCallbacks; ++i) _callbacks[i].apply(null, params); _executed = false; for (i = 0; i < _numAdded; ++i) add(_toAdd[i]); _numAdded = 0; _toAdd = null; for (i = 0; i < _numRemoved; ++i) remove(_toRemove[i]); _numRemoved = 0; _toRemove = null; } } } }
package aerys.minko.type { public final class Signal { private var _name : String; private var _callbacks : Vector.<Function>; private var _numCallbacks : uint; private var _executed : Boolean; private var _numAdded : uint; private var _toAdd : Vector.<Function>; private var _numRemoved : uint; private var _toRemove : Vector.<Function>; public function get numCallbacks() : uint { return _numCallbacks; } public function Signal(name : String) { _name = name; _callbacks = new <Function>[]; } public function add(callback : Function) : void { if (_callbacks.indexOf(callback) >= 0) { var removeIndex : int = _toRemove ? _toRemove.indexOf(callback) : -1; // if that callback is in the temp. remove list, we simply remove it from this list // instead of removing/adding it all over again if (removeIndex >= 0) { --_numRemoved; _toRemove[removeIndex] = _toRemove[_numRemoved]; _toRemove.length = _numRemoved; return; } else throw new Error('The same callback cannot be added twice.'); } if (_executed) { if (_toAdd) _toAdd.push(callback); else _toAdd = new <Function>[callback]; ++_numAdded; return ; } _callbacks[_numCallbacks] = callback; ++_numCallbacks; } public function remove(callback : Function) : void { var index : int = _callbacks.indexOf(callback); if (index < 0) { var addIndex : int = _toAdd ? _toAdd.indexOf(callback) : -1; // if that callback is in the temp. add list, we simply remove it from this list // instead of adding/removing it all over again if (addIndex) { --_numAdded; _toAdd[addIndex] = _toAdd[_numAdded]; _toAdd.length = _numAdded; } else throw new Error('This callback does not exist.'); } if (_executed) { if (_toRemove) _toRemove.push(callback); else _toRemove = new <Function>[callback]; ++_numRemoved; return ; } --_numCallbacks; _callbacks[index] = _callbacks[_numCallbacks]; _callbacks.length = _numCallbacks; } public function hasCallback(callback : Function) : Boolean { return _callbacks.indexOf(callback) >= 0; } public function execute(...params) : void { if (_numCallbacks) { _executed = true; for (var i : uint = 0; i < _numCallbacks; ++i) _callbacks[i].apply(null, params); _executed = false; for (i = 0; i < _numAdded; ++i) add(_toAdd[i]); _numAdded = 0; _toAdd = null; for (i = 0; i < _numRemoved; ++i) remove(_toRemove[i]); _numRemoved = 0; _toRemove = null; } } } }
fix Signal.add() and Signal.remove() error checks to take the tmp _toAdd/_toRemove tmp lists into account
fix Signal.add() and Signal.remove() error checks to take the tmp _toAdd/_toRemove tmp lists into account
ActionScript
mit
aerys/minko-as3
053fce7e0e35b3aa5d5ab4bbd14fb09f4ba35e9b
build-aux/base.as
build-aux/base.as
## -*- shell-script -*- ## base.as: This file is part of build-aux. ## Copyright (C) Gostai S.A.S., 2006-2008. ## ## This software is provided "as is" without warranty of any kind, ## either expressed or implied, including but not limited to the ## implied warranties of fitness for a particular purpose. ## ## See the LICENSE file for more information. ## For comments, bug reports and feedback: http://www.urbiforge.com ## m4_pattern_forbid([^_?URBI_])dnl # m4_define([_m4_divert(M4SH-INIT)], 5) m4_define([_m4_divert(URBI-INIT)], 10) m4_defun([_URBI_ABSOLUTE_PREPARE], [ # is_absolute PATH # ---------------- is_absolute () { case $[1] in ([[\\/]]* | ?:[[\\/]]*) return 0;; ( *) return 1;; esac } # absolute NAME -> ABS-NAME # ------------------------- # Return an absolute path to NAME. absolute () { local res AS_IF([is_absolute "$[1]"], [# Absolute paths do not need to be expanded. res=$[1]], [local dir=$(pwd)/$(dirname "$[1]") if test -d "$dir"; then res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]") else fatal "absolute: not a directory: $dir" fi]) # On Windows, we must make sure we have a Windows-like UNIX-friendly path (of # the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice # the use of forward slashes in the Windows path. Windows *does* understand # paths with forward slashes). case $(uname -s) in (CYGWIN*) res=$(cygpath "$res") esac echo "$res" } ]) m4_defun([_URBI_FIND_PROG_PREPARE], [# find_file FILE PATH # ------------------- # Return full path to FILE in PATH ($PATH_SEPARATOR separated), # nothing if not found. find_prog () { _AS_PATH_WALK([$[2]], [AS_IF([test -f $as_dir/$[1]], [echo "$as_dir/$[1]"; break])]) } # xfind_file PROG PATH # -------------------- # Same as xfind_prog, but don't take "no" for an answer. xfind_file () { local res res=$(find_prog "$[1]" "$[2]") test -n "$res" || error OSFILE "cannot find $[1] in $[2]" echo "$res" } # find_prog PROG [PATH=$PATH] # --------------------------- # Return full path to PROG in PATH ($PATH_SEPARATOR separated), # nothing if not found. find_prog () { local path=$PATH test -z "$[2]" || path=$[2] _AS_PATH_WALK([$path], [AS_IF([AS_TEST_X([$as_dir/$[1]])], [echo "$as_dir/$[1]"; break])]) } # xfind_prog PROG [PATH=$PATH] # ---------------------------- # Same as xfind_prog, but don't take "no" for an answer. xfind_prog () { local path=$PATH test -z "$[2]" || path=$[2] local res res=$(find_prog "$[1]" "$path") test -n "$res" || error OSFILE "cannot find executable $[1] in $path" echo "$res" } # require_thing TEST-FLAG ERROR_MESSAGE THING [HINT] # -------------------------------------------------- require_thing () { local flag=$[1] local error="$[2]: $[3]" local thing=$[3] shift 3 test $flag "$thing" || fatal OSFILE "$error" "$[@]" } # require_dir DIR [HINT] # ---------------------- require_dir () { require_thing -d "no such directory" "$[@]" } # require_file FILE [HINT] # ------------------------ require_file () { require_thing -f "no such file" "$[@]" } ]) m4_defun([_URBI_STDERR_PREPARE], [ # stderr LINES # ------------ stderr () { local i for i do echo >&2 "$as_me: $i" done echo >&2 } # error EXIT MESSAGES # ------------------- error () { local exit=$[1] shift stderr "$[@]" ex_exit $exit } # fatal MESSAGES # -------------- fatal () { # To help the user, just make sure that she is not confused between # the prototypes of fatal and error: the first argument is unlikely # to be integer. case $[1] in (*[[!0-9]]*|'') ;; (*) stderr "warning: possible confusion between fatal and error" \ "fatal $[*]";; esac error 1 "$[@]" } # ex_to_string EXIT # ----------------- # Return a decoding of EXIT status if available, nothing otherwise. ex_to_string () { case $[1] in ( 0) echo ' (EX_OK: successful termination)';; ( 64) echo ' (EX_USAGE: command line usage error)';; ( 65) echo ' (EX_DATAERR: data format error)';; ( 66) echo ' (EX_NOINPUT: cannot open input)';; ( 67) echo ' (EX_NOUSER: addressee unknown)';; ( 68) echo ' (EX_NOHOST: host name unknown)';; ( 69) echo ' (EX_UNAVAILABLE: service unavailable)';; ( 70) echo ' (EX_SOFTWARE: internal software error)';; ( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';; ( 72) echo ' (EX_OSFILE: critical OS file missing)';; ( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';; ( 74) echo ' (EX_IOERR: input/output error)';; ( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';; ( 76) echo ' (EX_PROTOCOL: remote error in protocol)';; ( 77) echo ' (EX_NOPERM: permission denied)';; ( 78) echo ' (EX_CONFIG: configuration error)';; (176) echo ' (EX_SKIP: skip this test with unmet dependencies)';; (177) echo ' (EX_HARD: hard error that cannot be saved)';; (242) echo ' (killed by Valgrind)';; ( *) if test 127 -lt $[1]; then echo " (SIG$(kill -l $[1] || true))" fi;; esac } # ex_to_int CODE # -------------- # Decode the CODE and return the corresponding int. ex_to_int () { case $[1] in (OK |EX_OK) echo 0;; (USAGE |EX_USAGE) echo 64;; (DATAERR |EX_DATAERR) echo 65;; (NOINPUT |EX_NOINPUT) echo 66;; (NOUSER |EX_NOUSER) echo 67;; (NOHOST |EX_NOHOST) echo 68;; (UNAVAILABLE|EX_UNAVAILABLE) echo 69;; (SOFTWARE |EX_SOFTWARE) echo 70;; (OSERR |EX_OSERR) echo 71;; (OSFILE |EX_OSFILE) echo 72;; (CANTCREAT |EX_CANTCREAT) echo 73;; (IOERR |EX_IOERR) echo 74;; (TEMPFAIL |EX_TEMPFAIL) echo 75;; (PROTOCOL |EX_PROTOCOL) echo 76;; (NOPERM |EX_NOPERM) echo 77;; (CONFIG |EX_CONFIG) echo 78;; (SKIP |EX_SKIP) echo 176;; (HARD |EX_HARD) echo 177;; (*) echo $[1];; esac } ex_exit () { exit $(ex_to_int $[1]) } ]) # URBI_GET_OPTIONS # ---------------- # Generate get_options(). m4_define([URBI_GET_OPTIONS], [# Parse command line options get_options () { while test $[#] -ne 0; do case $[1] in (--*=*) opt=$(echo "$[1]" | sed -e 's/=.*//') val=$(echo "$[1]" | sed -e ['s/[^=]*=//']) shift set dummy "$opt" "$val" ${1+"$[@]"}; shift ;; esac case $[1] in $@ esac shift done } ]) m4_defun([_URBI_PREPARE], [ # truth TEST-ARGUMENTS... # ----------------------- # Run "test TEST-ARGUMENTS" and echo true/false depending on the result. truth () { if test "$[@]"; then echo true else echo false fi } _URBI_ABSOLUTE_PREPARE _URBI_FIND_PROG_PREPARE _URBI_STDERR_PREPARE ]) # URBI_PREPARE # ------------ # Output all the M4sh possible initialization into the initialization # diversion. m4_defun([URBI_PREPARE], [m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl URBI_RST_PREPARE()dnl URBI_INSTRUMENT_PREPARE()dnl URBI_CHILDREN_PREPARE()dnl ]) # URBI_INIT # --------- # Replaces the AS_INIT invocation. # Must be defined via "m4_define", not "m4_defun" since it is AS_INIT # which will set up the diversions used for "m4_defun". m4_define([URBI_INIT], [AS_INIT()dnl URBI_PREPARE() set -e case $VERBOSE in (x) set -x;; esac : ${abs_builddir='@abs_builddir@'} : ${abs_srcdir='@abs_srcdir@'} : ${abs_top_builddir='@abs_top_builddir@'} : ${abs_top_srcdir='@abs_top_srcdir@'} : ${builddir='@builddir@'} : ${srcdir='@srcdir@'} : ${top_builddir='@top_builddir@'} : ${top_srcdir='@top_srcdir@'} ])
## -*- shell-script -*- ## base.as: This file is part of build-aux. ## Copyright (C) Gostai S.A.S., 2006-2008. ## ## This software is provided "as is" without warranty of any kind, ## either expressed or implied, including but not limited to the ## implied warranties of fitness for a particular purpose. ## ## See the LICENSE file for more information. ## For comments, bug reports and feedback: http://www.urbiforge.com ## m4_pattern_forbid([^_?URBI_])dnl # m4_define([_m4_divert(M4SH-INIT)], 5) m4_define([_m4_divert(URBI-INIT)], 10) m4_defun([_URBI_ABSOLUTE_PREPARE], [ # is_absolute PATH # ---------------- is_absolute () { case $[1] in ([[\\/]]* | ?:[[\\/]]*) return 0;; ( *) return 1;; esac } # absolute NAME -> ABS-NAME # ------------------------- # Return an absolute path to NAME. absolute () { local res AS_IF([is_absolute "$[1]"], [# Absolute paths do not need to be expanded. res=$[1]], [local dir=$(pwd)/$(dirname "$[1]") if test -d "$dir"; then res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]") else fatal "absolute: not a directory: $dir" fi]) # On Windows, we must make sure we have a Windows-like UNIX-friendly path (of # the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice # the use of forward slashes in the Windows path. Windows *does* understand # paths with forward slashes). case $(uname -s) in (CYGWIN*) res=$(cygpath "$res") esac echo "$res" } ]) m4_defun([_URBI_FIND_PROG_PREPARE], [# find_file FILE PATH # ------------------- # Return full path to FILE in PATH ($PATH_SEPARATOR separated), # nothing if not found. find_prog () { _AS_PATH_WALK([$[2]], [AS_IF([test -f $as_dir/$[1]], [echo "$as_dir/$[1]"; break])]) } # xfind_file PROG PATH # -------------------- # Same as xfind_prog, but don't take "no" for an answer. xfind_file () { local res res=$(find_prog "$[1]" "$[2]") test -n "$res" || error OSFILE "cannot find $[1] in $[2]" echo "$res" } # find_prog PROG [PATH=$PATH] # --------------------------- # Return full path to PROG in PATH ($PATH_SEPARATOR separated), # nothing if not found. find_prog () { local path=$PATH test -z "$[2]" || path=$[2] _AS_PATH_WALK([$path], [AS_IF([AS_TEST_X([$as_dir/$[1]])], [echo "$as_dir/$[1]"; break])]) } # xfind_prog PROG [PATH=$PATH] # ---------------------------- # Same as xfind_prog, but don't take "no" for an answer. xfind_prog () { local path=$PATH test -z "$[2]" || path=$[2] local res res=$(find_prog "$[1]" "$path") test -n "$res" || error OSFILE "cannot find executable $[1] in $path" echo "$res" } # require_thing TEST-FLAG ERROR_MESSAGE THING [HINT] # -------------------------------------------------- require_thing () { local flag=$[1] local error="$[2]: $[3]" local thing=$[3] shift 3 test $flag "$thing" || error OSFILE "$error" "$[@]" } # require_dir DIR [HINT] # ---------------------- require_dir () { require_thing -d "no such directory" "$[@]" } # require_file FILE [HINT] # ------------------------ require_file () { require_thing -f "no such file" "$[@]" } ]) m4_defun([_URBI_STDERR_PREPARE], [ # stderr LINES # ------------ stderr () { local i for i do echo >&2 "$as_me: $i" done echo >&2 } # error EXIT MESSAGES # ------------------- error () { local exit=$[1] shift stderr "$[@]" ex_exit $exit } # fatal MESSAGES # -------------- fatal () { # To help the user, just make sure that she is not confused between # the prototypes of fatal and error: the first argument is unlikely # to be integer. case $[1] in (*[[!0-9]]*|'') ;; (*) stderr "warning: possible confusion between fatal and error" \ "fatal $[*]";; esac error 1 "$[@]" } # ex_to_string EXIT # ----------------- # Return a decoding of EXIT status if available, nothing otherwise. ex_to_string () { case $[1] in ( 0) echo ' (EX_OK: successful termination)';; ( 64) echo ' (EX_USAGE: command line usage error)';; ( 65) echo ' (EX_DATAERR: data format error)';; ( 66) echo ' (EX_NOINPUT: cannot open input)';; ( 67) echo ' (EX_NOUSER: addressee unknown)';; ( 68) echo ' (EX_NOHOST: host name unknown)';; ( 69) echo ' (EX_UNAVAILABLE: service unavailable)';; ( 70) echo ' (EX_SOFTWARE: internal software error)';; ( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';; ( 72) echo ' (EX_OSFILE: critical OS file missing)';; ( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';; ( 74) echo ' (EX_IOERR: input/output error)';; ( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';; ( 76) echo ' (EX_PROTOCOL: remote error in protocol)';; ( 77) echo ' (EX_NOPERM: permission denied)';; ( 78) echo ' (EX_CONFIG: configuration error)';; (176) echo ' (EX_SKIP: skip this test with unmet dependencies)';; (177) echo ' (EX_HARD: hard error that cannot be saved)';; (242) echo ' (killed by Valgrind)';; ( *) if test 127 -lt $[1]; then echo " (SIG$(kill -l $[1] || true))" fi;; esac } # ex_to_int CODE # -------------- # Decode the CODE and return the corresponding int. ex_to_int () { case $[1] in (OK |EX_OK) echo 0;; (USAGE |EX_USAGE) echo 64;; (DATAERR |EX_DATAERR) echo 65;; (NOINPUT |EX_NOINPUT) echo 66;; (NOUSER |EX_NOUSER) echo 67;; (NOHOST |EX_NOHOST) echo 68;; (UNAVAILABLE|EX_UNAVAILABLE) echo 69;; (SOFTWARE |EX_SOFTWARE) echo 70;; (OSERR |EX_OSERR) echo 71;; (OSFILE |EX_OSFILE) echo 72;; (CANTCREAT |EX_CANTCREAT) echo 73;; (IOERR |EX_IOERR) echo 74;; (TEMPFAIL |EX_TEMPFAIL) echo 75;; (PROTOCOL |EX_PROTOCOL) echo 76;; (NOPERM |EX_NOPERM) echo 77;; (CONFIG |EX_CONFIG) echo 78;; (SKIP |EX_SKIP) echo 176;; (HARD |EX_HARD) echo 177;; (*) echo $[1];; esac } ex_exit () { exit $(ex_to_int $[1]) } ]) # URBI_GET_OPTIONS # ---------------- # Generate get_options(). m4_define([URBI_GET_OPTIONS], [# Parse command line options get_options () { while test $[#] -ne 0; do case $[1] in (--*=*) opt=$(echo "$[1]" | sed -e 's/=.*//') val=$(echo "$[1]" | sed -e ['s/[^=]*=//']) shift set dummy "$opt" "$val" ${1+"$[@]"}; shift ;; esac case $[1] in $@ esac shift done } ]) m4_defun([_URBI_PREPARE], [ # truth TEST-ARGUMENTS... # ----------------------- # Run "test TEST-ARGUMENTS" and echo true/false depending on the result. truth () { if test "$[@]"; then echo true else echo false fi } _URBI_ABSOLUTE_PREPARE _URBI_FIND_PROG_PREPARE _URBI_STDERR_PREPARE ]) # URBI_PREPARE # ------------ # Output all the M4sh possible initialization into the initialization # diversion. m4_defun([URBI_PREPARE], [m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl URBI_RST_PREPARE()dnl URBI_INSTRUMENT_PREPARE()dnl URBI_CHILDREN_PREPARE()dnl ]) # URBI_INIT # --------- # Replaces the AS_INIT invocation. # Must be defined via "m4_define", not "m4_defun" since it is AS_INIT # which will set up the diversions used for "m4_defun". m4_define([URBI_INIT], [AS_INIT()dnl URBI_PREPARE() set -e case $VERBOSE in (x) set -x;; esac : ${abs_builddir='@abs_builddir@'} : ${abs_srcdir='@abs_srcdir@'} : ${abs_top_builddir='@abs_top_builddir@'} : ${abs_top_srcdir='@abs_top_srcdir@'} : ${builddir='@builddir@'} : ${srcdir='@srcdir@'} : ${top_builddir='@top_builddir@'} : ${top_srcdir='@top_srcdir@'} ])
Fix error vs. fatal confusion.
Fix error vs. fatal confusion. * build-aux/base.as: here.
ActionScript
bsd-3-clause
aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport,aldebaran/libport
c7ba075f88ed16545ffaca17479846ff7ad8b641
Arguments/src/components/AgoraMap.as
Arguments/src/components/AgoraMap.as
//This class is the canvas on which everything will be drawn package components { import Controller.ArgumentController; import Controller.LayoutController; import Controller.LoadController; import Controller.logic.ConditionalSyllogism; import Controller.logic.DisjunctiveSyllogism; import Controller.logic.ModusPonens; import Controller.logic.ModusTollens; import Controller.logic.NotAllSyllogism; import Controller.logic.ParentArg; import Events.AGORAEvent; import Model.AGORAModel; import Model.ArgumentTypeModel; import Model.InferenceModel; import Model.StatementModel; import ValueObjects.AGORAParameters; import classes.Language; import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.MovieClip; import flash.events.Event; import flash.events.TimerEvent; import flash.geom.Point; import flash.text.TextField; import flash.utils.Dictionary; import flash.utils.Timer; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; import mx.binding.utils.BindingUtils; import mx.binding.utils.ChangeWatcher; import mx.collections.ArrayCollection; import mx.containers.Canvas; import mx.controls.Alert; import mx.controls.Label; import mx.controls.Menu; import mx.core.DragSource; import mx.core.UIComponent; import mx.events.DragEvent; import mx.events.FlexEvent; import mx.events.ScrollEvent; import mx.managers.DragManager; import mx.states.State; public class AgoraMap extends Canvas { public static const BY_ARGUMENT:String = "ByArgument"; public static const BY_CLAIM:String = "ByClaim"; public var beganBy:String; public var drawUtility:UIComponent = null; public var ID:int; public var helpText:HelpText; public var firstClaimHelpText:FirstClaimHelpText; private static var _tempID:int; public var timer:Timer; private var _removePreviousElements:Boolean; public var panelsHash:Dictionary; public var menuPanelsHash:Dictionary; public function AgoraMap() { addEventListener(DragEvent.DRAG_ENTER,acceptDrop); addEventListener(DragEvent.DRAG_DROP,handleDrop ); initializeMapStructures(); timer = new Timer(10000); timer.addEventListener(TimerEvent.TIMER, onMapTimer); beganBy = BY_CLAIM; removePreviousElements = false; } //--------------------- getters and setters -------------------// public function get removePreviousElements():Boolean{ return _removePreviousElements; } public function set removePreviousElements(value:Boolean):void{ _removePreviousElements = value; invalidateProperties(); invalidateDisplayList(); } protected function onMapTimer(event:TimerEvent):void{ LoadController.getInstance().fetchMapData(); } public function getGlobalCoordinates(point:Point):Point { return localToGlobal(point); } public function initializeMapStructures():void{ panelsHash = new Dictionary; menuPanelsHash = new Dictionary; removePreviousElements = true; } override protected function createChildren():void { super.createChildren(); drawUtility = new UIComponent(); this.addChild(drawUtility); drawUtility.depth = 0; helpText = new HelpText; addChild(helpText); helpText.visible = false; firstClaimHelpText = new FirstClaimHelpText; addChild(firstClaimHelpText); firstClaimHelpText.visible = false; } public function acceptDrop(d:DragEvent):void { DragManager.acceptDragDrop(Canvas(d.currentTarget)); } public function handleDrop(dragEvent:DragEvent):void { var currentStage:Canvas = Canvas(dragEvent.currentTarget); var gridPanel:GridPanel = dragEvent.dragInitiator as GridPanel; var dragSource:DragSource = dragEvent.dragSource; var tmpx:int = int(dragSource.dataForFormat("x")); var tmpy:int = int(dragSource.dataForFormat("y")); tmpx = currentStage.mouseX - tmpx; tmpy = currentStage.mouseY - tmpy; var toxgrid:int = Math.floor(tmpy/AGORAParameters.getInstance().gridWidth); var toygrid:int = Math.floor(tmpx/AGORAParameters.getInstance().gridWidth); var diffx:int = toxgrid - int(dragSource.dataForFormat("gx")); var diffy:int = toygrid - int(dragSource.dataForFormat("gy")); setChildIndex(gridPanel, numChildren - 1); LayoutController.getInstance().movePanel(gridPanel,diffx, diffy); } override protected function commitProperties():void{ super.commitProperties(); if(removePreviousElements){ removeAllChildren(); removeAllElements(); _removePreviousElements = false; } try{ removeChild(drawUtility); }catch(e:Error){ } addChildAt(drawUtility, 0); try{ removeChild(helpText); }catch(e:Error){ } addChild(helpText); try{ removeChild(firstClaimHelpText); }catch(e:Error){ } addChild(firstClaimHelpText); var newPanels:ArrayCollection = AGORAModel.getInstance().agoraMapModel.newPanels; for(var i:int=0; i< newPanels.length; i++){ if(StatementModel(newPanels[i]).statementFunction == StatementModel.INFERENCE){ var inference:ArgumentPanel = new ArgumentPanel; inference.model = newPanels[i]; panelsHash[inference.model.ID] = inference; addChild(inference); //add the next infobox var addArgumentsInfo:InfoBox = new InfoBox; addArgumentsInfo.visible = false; addArgumentsInfo.text = Language.lookup('ArgComplete'); addArgumentsInfo.boxWidth = 500; addChild(addArgumentsInfo); } else if(newPanels[i] is StatementModel){ var argumentPanel:ArgumentPanel; var model:StatementModel = newPanels[i]; if(model.statementType != StatementModel.OBJECTION){ argumentPanel = new ArgumentPanel; argumentPanel.model = model; panelsHash[model.ID] = argumentPanel; argumentPanel.addEventListener(AGORAEvent.STATEMENT_STATE_TO_EDIT, ArgumentController.getInstance().removeOption); if(model.argumentTypeModel){ if(!model.argumentTypeModel.reasonsCompleted) { if(model.argumentTypeModel.reasonModels.length == 1){ argumentPanel.branchControl = new Option; argumentPanel.branchControl.x = argumentPanel.x + AGORAParameters.getInstance().gridWidth * 10; argumentPanel.branchControl.y = argumentPanel.y; argumentPanel.branchControl.argumentTypeModel = model.argumentTypeModel; addChild(argumentPanel.branchControl); } } } addChild(argumentPanel); argumentPanel.changeTypeInfo = new InfoBox; argumentPanel.changeTypeInfo.visible = false; argumentPanel.changeTypeInfo.text = Language.lookup('PartUnivReq'); argumentPanel.changeTypeInfo.boxWidth = argumentPanel.getExplicitOrMeasuredWidth(); addChild(argumentPanel.changeTypeInfo); } else{ argumentPanel = new ArgumentPanel; argumentPanel.model = model; panelsHash[model.ID] = argumentPanel; addChild(argumentPanel); } } } var newMenuPanels:ArrayCollection = AGORAModel.getInstance().agoraMapModel.newConnections; for each(var argumentTypeModel:ArgumentTypeModel in newMenuPanels){ var menuPanel:MenuPanel = new MenuPanel; menuPanel.model = argumentTypeModel; menuPanel.schemeSelector = new ArgSelector; menuPanel.schemeSelector.visible = false; menuPanel.schemeSelector.argumentTypeModel = argumentTypeModel; menuPanelsHash[menuPanel.model.ID] = menuPanel; addChild(menuPanel); addChild(menuPanel.schemeSelector); } LoadController.getInstance().mapUpdateCleanUp(); } override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth,unscaledHeight); connectRelatedPanels(); } protected function connectRelatedPanels():void { var panelList:Dictionary = panelsHash; drawUtility.graphics.clear(); drawUtility.graphics.lineStyle(2,0,1); var gridWidth:int = AGORAParameters.getInstance().gridWidth; var layoutController:LayoutController = LayoutController.getInstance(); var statementModel:StatementModel; var argumentTypeModel:ArgumentTypeModel; //code for the connecting arrows for each(var model:StatementModel in AGORAModel.getInstance().agoraMapModel.panelListHash){ if(model.supportingArguments.length > 0 || model.objections.length > 0){ //First Vertical Line Starting Point var argumentPanel:ArgumentPanel = panelsHash[model.ID]; var fvlspx:int = ((argumentPanel.x + argumentPanel.width)/gridWidth + 2) * gridWidth; var fvlspy:int = argumentPanel.y + 72; if(model.supportingArguments.length > 0){ //draw arrow drawUtility.graphics.lineStyle(10, 0x29ABE2, 10); drawUtility.graphics.moveTo(argumentPanel.x + argumentPanel.width + 20, argumentPanel.y + 87); drawUtility.graphics.lineTo(argumentPanel.x + argumentPanel.width, argumentPanel.y + 72); drawUtility.graphics.lineTo(argumentPanel.x + argumentPanel.width + 20, argumentPanel.y + 57); //First Vertical Line Finishing Point var lastMenuPanel:MenuPanel = menuPanelsHash[layoutController.getBottomArgument(model).ID]; var fvlfpy:int = (lastMenuPanel.y + 72); //draw a line drawUtility.graphics.moveTo(fvlspx, fvlspy); drawUtility.graphics.lineTo(fvlspx, fvlfpy); //Line from claim to vertical line starting point var firstMenuPanel:MenuPanel = menuPanelsHash[model.supportingArguments[0].ID]; drawUtility.graphics.moveTo(argumentPanel.x + argumentPanel.width, argumentPanel.y + 72); drawUtility.graphics.lineTo(fvlspx, argumentPanel.y + 72); //for each argument for each(argumentTypeModel in model.supportingArguments){ //get the point one grid before the first reason horizontally. var rspx:int = (argumentTypeModel.reasonModels[0].ygrid - 1) * gridWidth; var rspy:int = argumentTypeModel.xgrid * gridWidth + 72; //get the point in front of the last reason var rfpy:int = layoutController.getBottomReason(argumentTypeModel).xgrid * gridWidth + 72; //draw a line drawUtility.graphics.moveTo(rspx, rspy); drawUtility.graphics.lineTo(rspx, rfpy); var menuPanel:MenuPanel = menuPanelsHash[argumentTypeModel.ID]; //Line from menu Panel to the starting point of reason vertical line drawUtility.graphics.moveTo(menuPanel.x + menuPanel.width -30, menuPanel.y + 72); drawUtility.graphics.lineTo(rspx, menuPanel.y + 72); //Line from first vertical line to menu Panel drawUtility.graphics.moveTo(fvlspx, menuPanel.y + 72); drawUtility.graphics.lineTo(menuPanel.x+10, menuPanel.y + 72); //Line from menuPanel to Inference var inferencePanel:ArgumentPanel = panelsHash[argumentTypeModel.inferenceModel.ID]; if(inferencePanel.visible){ drawUtility.graphics.moveTo(menuPanel.x + menuPanel.width/2, menuPanel.y+menuPanel.height+10); drawUtility.graphics.lineTo(menuPanel.x + menuPanel.width/2, inferencePanel.y); } for each(statementModel in argumentTypeModel.reasonModels){ //hline var poReason:int = statementModel.xgrid * gridWidth + 72; drawUtility.graphics.moveTo(rspx, poReason); drawUtility.graphics.lineTo(statementModel.ygrid * gridWidth, poReason); } } } if(model.objections.length > 0){ drawUtility.graphics.lineStyle(10, 0xF99653, 10); argumentPanel = panelsHash[model.ID]; var lastObjection:StatementModel = layoutController.getBottomObjection(model); if(lastObjection != null){ var bottomObjection:ArgumentPanel = panelsHash[lastObjection.ID]; fvlspx = argumentPanel.x + argumentPanel.getExplicitOrMeasuredWidth() - 30; fvlspy = argumentPanel.y-15 + argumentPanel.getExplicitOrMeasuredHeight(); fvlfpy = bottomObjection.y + 72; //draw a line from the first objection to the last objection //and an arrow drawUtility.graphics.moveTo(fvlspx, fvlfpy); drawUtility.graphics.lineTo(fvlspx, fvlspy); drawUtility.graphics.lineTo(fvlspx-15, fvlspy +15); drawUtility.graphics.moveTo(fvlspx, fvlspy); drawUtility.graphics.lineTo(fvlspx+15, fvlspy+15); for each(var obj:StatementModel in model.objections){ //horizontal line from the vertical line to the objection if(panelsHash.hasOwnProperty(obj.ID)){ var objectionPanel:ArgumentPanel = panelsHash[obj.ID]; drawUtility.graphics.moveTo(fvlspx, objectionPanel.y +72); drawUtility.graphics.lineTo(objectionPanel.x, objectionPanel.y + 72); } } } } } } } } }
//This class is the canvas on which everything will be drawn package components { import Controller.ArgumentController; import Controller.LayoutController; import Controller.LoadController; import Controller.logic.ConditionalSyllogism; import Controller.logic.DisjunctiveSyllogism; import Controller.logic.ModusPonens; import Controller.logic.ModusTollens; import Controller.logic.NotAllSyllogism; import Controller.logic.ParentArg; import Events.AGORAEvent; import Model.AGORAModel; import Model.ArgumentTypeModel; import Model.InferenceModel; import Model.StatementModel; import ValueObjects.AGORAParameters; import classes.Language; import flash.display.DisplayObject; import flash.display.Graphics; import flash.display.MovieClip; import flash.events.Event; import flash.events.TimerEvent; import flash.geom.Point; import flash.text.TextField; import flash.utils.Dictionary; import flash.utils.Timer; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; import mx.binding.utils.BindingUtils; import mx.binding.utils.ChangeWatcher; import mx.collections.ArrayCollection; import mx.containers.Canvas; import mx.controls.Alert; import mx.controls.Label; import mx.controls.Menu; import mx.core.DragSource; import mx.core.UIComponent; import mx.events.DragEvent; import mx.events.FlexEvent; import mx.events.ScrollEvent; import mx.managers.DragManager; import mx.states.State; public class AgoraMap extends Canvas { public static const BY_ARGUMENT:String = "ByArgument"; public static const BY_CLAIM:String = "ByClaim"; public var beganBy:String; public var drawUtility:UIComponent = null; public var ID:int; public var helpText:HelpText; public var firstClaimHelpText:FirstClaimHelpText; private static var _tempID:int; public var timer:Timer; private var _removePreviousElements:Boolean; public var panelsHash:Dictionary; public var menuPanelsHash:Dictionary; public function AgoraMap() { addEventListener(DragEvent.DRAG_ENTER,acceptDrop); addEventListener(DragEvent.DRAG_DROP,handleDrop ); initializeMapStructures(); timer = new Timer(10000); timer.addEventListener(TimerEvent.TIMER, onMapTimer); beganBy = BY_CLAIM; removePreviousElements = false; } //--------------------- getters and setters -------------------// public function get removePreviousElements():Boolean{ return _removePreviousElements; } public function set removePreviousElements(value:Boolean):void{ _removePreviousElements = value; invalidateProperties(); invalidateDisplayList(); } protected function onMapTimer(event:TimerEvent):void{ LoadController.getInstance().fetchMapData(); } public function getGlobalCoordinates(point:Point):Point { return localToGlobal(point); } public function initializeMapStructures():void{ panelsHash = new Dictionary; menuPanelsHash = new Dictionary; removePreviousElements = true; } override protected function createChildren():void { super.createChildren(); drawUtility = new UIComponent(); this.addChild(drawUtility); drawUtility.depth = 0; helpText = new HelpText; addChild(helpText); helpText.visible = false; firstClaimHelpText = new FirstClaimHelpText; addChild(firstClaimHelpText); firstClaimHelpText.visible = false; } public function acceptDrop(d:DragEvent):void { DragManager.acceptDragDrop(Canvas(d.currentTarget)); } public function handleDrop(dragEvent:DragEvent):void { var currentStage:Canvas = Canvas(dragEvent.currentTarget); var gridPanel:GridPanel = dragEvent.dragInitiator as GridPanel; var dragSource:DragSource = dragEvent.dragSource; var tmpx:int = int(dragSource.dataForFormat("x")); var tmpy:int = int(dragSource.dataForFormat("y")); tmpx = currentStage.mouseX - tmpx; tmpy = currentStage.mouseY - tmpy; var toxgrid:int = Math.floor(tmpy/AGORAParameters.getInstance().gridWidth); var toygrid:int = Math.floor(tmpx/AGORAParameters.getInstance().gridWidth); var diffx:int = toxgrid - int(dragSource.dataForFormat("gx")); var diffy:int = toygrid - int(dragSource.dataForFormat("gy")); setChildIndex(gridPanel, numChildren - 1); LayoutController.getInstance().movePanel(gridPanel,diffx, diffy); } override protected function commitProperties():void{ super.commitProperties(); if(removePreviousElements){ removeAllChildren(); removeAllElements(); _removePreviousElements = false; } try{ removeChild(drawUtility); }catch(e:Error){ } addChildAt(drawUtility, 0); try{ removeChild(helpText); }catch(e:Error){ } addChild(helpText); try{ removeChild(firstClaimHelpText); }catch(e:Error){ } addChild(firstClaimHelpText); for each(var info:UIComponent in getChildren()) { if(info is InfoBox) { var info1:InfoBox = info as InfoBox; if(info1.helptext == Language.lookup('ArgComplete')) removeChild(info); } } var newPanels:ArrayCollection = AGORAModel.getInstance().agoraMapModel.newPanels; for(var i:int=0; i< newPanels.length; i++){ if(StatementModel(newPanels[i]).statementFunction == StatementModel.INFERENCE){ var inference:ArgumentPanel = new ArgumentPanel; inference.model = newPanels[i]; panelsHash[inference.model.ID] = inference; addChild(inference); //add the next infobox var addArgumentsInfo:InfoBox = new InfoBox; addArgumentsInfo.visible = false; addArgumentsInfo.text = Language.lookup('ArgComplete'); addArgumentsInfo.boxWidth = 500; addChild(addArgumentsInfo); } else if(newPanels[i] is StatementModel){ var argumentPanel:ArgumentPanel; var model:StatementModel = newPanels[i]; if(model.statementType != StatementModel.OBJECTION){ argumentPanel = new ArgumentPanel; argumentPanel.model = model; panelsHash[model.ID] = argumentPanel; argumentPanel.addEventListener(AGORAEvent.STATEMENT_STATE_TO_EDIT, ArgumentController.getInstance().removeOption); if(model.argumentTypeModel){ if(!model.argumentTypeModel.reasonsCompleted) { if(model.argumentTypeModel.reasonModels.length == 1){ argumentPanel.branchControl = new Option; argumentPanel.branchControl.x = argumentPanel.x + AGORAParameters.getInstance().gridWidth * 10; argumentPanel.branchControl.y = argumentPanel.y; argumentPanel.branchControl.argumentTypeModel = model.argumentTypeModel; addChild(argumentPanel.branchControl); } } } addChild(argumentPanel); argumentPanel.changeTypeInfo = new InfoBox; argumentPanel.changeTypeInfo.visible = false; argumentPanel.changeTypeInfo.text = Language.lookup('PartUnivReq'); argumentPanel.changeTypeInfo.boxWidth = argumentPanel.getExplicitOrMeasuredWidth(); addChild(argumentPanel.changeTypeInfo); } else{ argumentPanel = new ArgumentPanel; argumentPanel.model = model; panelsHash[model.ID] = argumentPanel; addChild(argumentPanel); } } } var newMenuPanels:ArrayCollection = AGORAModel.getInstance().agoraMapModel.newConnections; for each(var argumentTypeModel:ArgumentTypeModel in newMenuPanels){ var menuPanel:MenuPanel = new MenuPanel; menuPanel.model = argumentTypeModel; menuPanel.schemeSelector = new ArgSelector; menuPanel.schemeSelector.visible = false; menuPanel.schemeSelector.argumentTypeModel = argumentTypeModel; menuPanelsHash[menuPanel.model.ID] = menuPanel; addChild(menuPanel); addChild(menuPanel.schemeSelector); } LoadController.getInstance().mapUpdateCleanUp(); } override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth,unscaledHeight); connectRelatedPanels(); } protected function connectRelatedPanels():void { var panelList:Dictionary = panelsHash; drawUtility.graphics.clear(); drawUtility.graphics.lineStyle(2,0,1); var gridWidth:int = AGORAParameters.getInstance().gridWidth; var layoutController:LayoutController = LayoutController.getInstance(); var statementModel:StatementModel; var argumentTypeModel:ArgumentTypeModel; //code for the connecting arrows for each(var model:StatementModel in AGORAModel.getInstance().agoraMapModel.panelListHash){ if(model.supportingArguments.length > 0 || model.objections.length > 0){ //First Vertical Line Starting Point var argumentPanel:ArgumentPanel = panelsHash[model.ID]; var fvlspx:int = ((argumentPanel.x + argumentPanel.width)/gridWidth + 2) * gridWidth; var fvlspy:int = argumentPanel.y + 72; if(model.supportingArguments.length > 0){ //draw arrow drawUtility.graphics.lineStyle(10, 0x29ABE2, 10); drawUtility.graphics.moveTo(argumentPanel.x + argumentPanel.width + 20, argumentPanel.y + 87); drawUtility.graphics.lineTo(argumentPanel.x + argumentPanel.width, argumentPanel.y + 72); drawUtility.graphics.lineTo(argumentPanel.x + argumentPanel.width + 20, argumentPanel.y + 57); //First Vertical Line Finishing Point var lastMenuPanel:MenuPanel = menuPanelsHash[layoutController.getBottomArgument(model).ID]; var fvlfpy:int = (lastMenuPanel.y + 72); //draw a line drawUtility.graphics.moveTo(fvlspx, fvlspy); drawUtility.graphics.lineTo(fvlspx, fvlfpy); //Line from claim to vertical line starting point var firstMenuPanel:MenuPanel = menuPanelsHash[model.supportingArguments[0].ID]; drawUtility.graphics.moveTo(argumentPanel.x + argumentPanel.width, argumentPanel.y + 72); drawUtility.graphics.lineTo(fvlspx, argumentPanel.y + 72); //for each argument for each(argumentTypeModel in model.supportingArguments){ //get the point one grid before the first reason horizontally. var rspx:int = (argumentTypeModel.reasonModels[0].ygrid - 1) * gridWidth; var rspy:int = argumentTypeModel.xgrid * gridWidth + 72; //get the point in front of the last reason var rfpy:int = layoutController.getBottomReason(argumentTypeModel).xgrid * gridWidth + 72; //draw a line drawUtility.graphics.moveTo(rspx, rspy); drawUtility.graphics.lineTo(rspx, rfpy); var menuPanel:MenuPanel = menuPanelsHash[argumentTypeModel.ID]; //Line from menu Panel to the starting point of reason vertical line drawUtility.graphics.moveTo(menuPanel.x + menuPanel.width -30, menuPanel.y + 72); drawUtility.graphics.lineTo(rspx, menuPanel.y + 72); //Line from first vertical line to menu Panel drawUtility.graphics.moveTo(fvlspx, menuPanel.y + 72); drawUtility.graphics.lineTo(menuPanel.x+10, menuPanel.y + 72); //Line from menuPanel to Inference var inferencePanel:ArgumentPanel = panelsHash[argumentTypeModel.inferenceModel.ID]; if(inferencePanel.visible){ drawUtility.graphics.moveTo(menuPanel.x + menuPanel.width/2, menuPanel.y+menuPanel.height+10); drawUtility.graphics.lineTo(menuPanel.x + menuPanel.width/2, inferencePanel.y); } for each(statementModel in argumentTypeModel.reasonModels){ //hline var poReason:int = statementModel.xgrid * gridWidth + 72; drawUtility.graphics.moveTo(rspx, poReason); drawUtility.graphics.lineTo(statementModel.ygrid * gridWidth, poReason); } } } if(model.objections.length > 0){ drawUtility.graphics.lineStyle(10, 0xF99653, 10); argumentPanel = panelsHash[model.ID]; var lastObjection:StatementModel = layoutController.getBottomObjection(model); if(lastObjection != null){ var bottomObjection:ArgumentPanel = panelsHash[lastObjection.ID]; fvlspx = argumentPanel.x + argumentPanel.getExplicitOrMeasuredWidth() - 30; fvlspy = argumentPanel.y-15 + argumentPanel.getExplicitOrMeasuredHeight(); fvlfpy = bottomObjection.y + 72; //draw a line from the first objection to the last objection //and an arrow drawUtility.graphics.moveTo(fvlspx, fvlfpy); drawUtility.graphics.lineTo(fvlspx, fvlspy); drawUtility.graphics.lineTo(fvlspx-15, fvlspy +15); drawUtility.graphics.moveTo(fvlspx, fvlspy); drawUtility.graphics.lineTo(fvlspx+15, fvlspy+15); for each(var obj:StatementModel in model.objections){ //horizontal line from the vertical line to the objection if(panelsHash.hasOwnProperty(obj.ID)){ var objectionPanel:ArgumentPanel = panelsHash[obj.ID]; drawUtility.graphics.moveTo(fvlspx, objectionPanel.y +72); drawUtility.graphics.lineTo(objectionPanel.x, objectionPanel.y + 72); } } } } } } } } }
make support box disappear
make support box disappear
ActionScript
agpl-3.0
MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA
322508081172a94d2056cc070d72a18b2b71babc
src/aerys/minko/render/DrawCallBindingsConsumer.as
src/aerys/minko/render/DrawCallBindingsConsumer.as
package aerys.minko.render { import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import flash.utils.Dictionary; import aerys.minko.type.binding.IDataBindingsConsumer; internal final class DrawCallBindingsConsumer implements IDataBindingsConsumer { private var _enabled : Boolean; private var _bindings : Object; private var _cpuConstants : Dictionary; private var _vsConstants : Vector.<Number>; private var _fsConstants : Vector.<Number>; private var _fsTextures : Vector.<ITextureResource>; private var _changes : Object; public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (value) for (var bindingName : String in _changes) { setProperty(bindingName, _changes[bindingName]); delete _changes[bindingName]; } } public function DrawCallBindingsConsumer(bindings : Object, cpuConstants : Dictionary, vsConstants : Vector.<Number>, fsConstants : Vector.<Number>, fsTextures : Vector.<ITextureResource>) { _bindings = bindings; _cpuConstants = cpuConstants; _vsConstants = vsConstants; _fsConstants = fsConstants; _fsTextures = fsTextures; initialize(); } private function initialize() : void { _enabled = true; _changes = {}; } public function setProperty(propertyName : String, value : Object) : void { if (!value) return; if (!_enabled) { _changes[propertyName] = value; return ; } var binding : IBinder = _bindings[propertyName] as IBinder; if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } } }
package aerys.minko.render { import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import flash.utils.Dictionary; import aerys.minko.type.binding.IDataBindingsConsumer; internal final class DrawCallBindingsConsumer implements IDataBindingsConsumer { private var _enabled : Boolean; private var _bindings : Object; private var _cpuConstants : Dictionary; private var _vsConstants : Vector.<Number>; private var _fsConstants : Vector.<Number>; private var _fsTextures : Vector.<ITextureResource>; private var _changes : Object; public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (value) for (var bindingName : String in _changes) { setProperty(bindingName, _changes[bindingName]); delete _changes[bindingName]; } } public function DrawCallBindingsConsumer(bindings : Object, cpuConstants : Dictionary, vsConstants : Vector.<Number>, fsConstants : Vector.<Number>, fsTextures : Vector.<ITextureResource>) { _bindings = bindings; _cpuConstants = cpuConstants; _vsConstants = vsConstants; _fsConstants = fsConstants; _fsTextures = fsTextures; initialize(); } private function initialize() : void { _enabled = true; _changes = {}; } public function setProperty(propertyName : String, value : Object) : void { if (value === null) return; if (!_enabled) { _changes[propertyName] = value; return ; } var binding : IBinder = _bindings[propertyName] as IBinder; if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } } }
fix changing the property to 0
fix changing the property to 0
ActionScript
mit
aerys/minko-as3
56c49d2f63ff03bf03d184215a8e5edc0b8e8b99
frameworks/projects/mobiletheme/src/spark/skins/mobile/SpinnerListContainerSkin.as
frameworks/projects/mobiletheme/src/spark/skins/mobile/SpinnerListContainerSkin.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.skins.mobile { import flash.display.Graphics; import flash.display.InteractiveObject; import flash.display.Sprite; import mx.core.DPIClassification; import spark.components.Group; import spark.components.SpinnerListContainer; import spark.layouts.HorizontalLayout; import spark.skins.mobile.supportClasses.MobileSkin; import spark.skins.mobile120.assets.SpinnerListContainerBackground; import spark.skins.mobile120.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile120.assets.SpinnerListContainerShadow; import spark.skins.mobile160.assets.SpinnerListContainerBackground; import spark.skins.mobile160.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile160.assets.SpinnerListContainerShadow; import spark.skins.mobile240.assets.SpinnerListContainerBackground; import spark.skins.mobile240.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile240.assets.SpinnerListContainerShadow; import spark.skins.mobile320.assets.SpinnerListContainerBackground; import spark.skins.mobile320.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile320.assets.SpinnerListContainerShadow; import spark.skins.mobile480.assets.SpinnerListContainerBackground; import spark.skins.mobile480.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile480.assets.SpinnerListContainerShadow; import spark.skins.mobile640.assets.SpinnerListContainerBackground; import spark.skins.mobile640.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile640.assets.SpinnerListContainerShadow; /** * ActionScript-based skin for the SpinnerListContainer in mobile applications. * * @see spark.components.SpinnerListContainer * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ public class SpinnerListContainerSkin extends MobileSkin { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 * */ public function SpinnerListContainerSkin() { super(); switch (applicationDPI) { case DPIClassification.DPI_640: { // Note provisional may need changes borderClass = spark.skins.mobile640.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile640.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile40.assets.SpinnerListContainerShadow; cornerRadius = 20; borderThickness = 3; selectionIndicatorHeight = 182; break; } case DPIClassification.DPI_480: { // Note provisional may need changes borderClass = spark.skins.mobile480.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile480.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile480.assets.SpinnerListContainerShadow; cornerRadius = 16; borderThickness = 2; selectionIndicatorHeight = 144; break; } case DPIClassification.DPI_320: { borderClass = spark.skins.mobile320.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile320.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile320.assets.SpinnerListContainerShadow; cornerRadius = 10; borderThickness = 2; selectionIndicatorHeight = 96; break; } case DPIClassification.DPI_240: { borderClass = spark.skins.mobile240.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile240.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile240.assets.SpinnerListContainerShadow; cornerRadius = 8; borderThickness = 1; selectionIndicatorHeight = 72; break; } case DPIClassification.DPI_120: { borderClass = spark.skins.mobile120.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile120.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile10.assets.SpinnerListContainerShadow; cornerRadius = 4; borderThickness = 1; selectionIndicatorHeight = 37; break; } default: // default DPI_160 { borderClass = spark.skins.mobile160.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile160.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile160.assets.SpinnerListContainerShadow; cornerRadius = 5; borderThickness = 1; selectionIndicatorHeight = 48; break; } } minWidth = 30; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * Pixel thickness of the border. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var borderThickness:Number; /** * Radius of the border corners. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var cornerRadius:Number; /** * Height of the selection indicator. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var selectionIndicatorHeight:Number; /** * Class for the border part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var borderClass:Class; /** * Class for the selection indicator skin part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var selectionIndicatorClass:Class; /** * Class for the shadow skin part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var shadowClass:Class; /** * Border skin part which includes the background. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var border:InteractiveObject; /** * Selection indicator skin part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var selectionIndicator:InteractiveObject; /** * Shadow skin part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var shadow:InteractiveObject; /** * Mask for the content group. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var contentGroupMask:Sprite; //-------------------------------------------------------------------------- // // Skin parts // //-------------------------------------------------------------------------- /** * An optional skin part that defines the Group where the content * children are pushed into and laid out. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ public var contentGroup:Group; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * @copy spark.skins.spark.ApplicationSkin#hostComponent * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ public var hostComponent:SpinnerListContainer; //-------------------------------------------------------------------------- // // Overridden Methods // //-------------------------------------------------------------------------- /** * @private */ override protected function createChildren():void { super.createChildren(); if (!border) { // Border and background border = new borderClass(); border.mouseEnabled = false; addChild(border); } if (!contentGroup) { // Contains the child elements contentGroup = new Group(); var hLayout:HorizontalLayout = new HorizontalLayout(); hLayout.gap = 0; hLayout.verticalAlign = "middle"; contentGroup.layout = hLayout; contentGroup.id = "contentGroup"; addChild(contentGroup); } if (!shadow) { // Shadowing sits on top of the content shadow = new shadowClass(); shadow.mouseEnabled = false; addChild(shadow); } if (!selectionIndicator) { // Selection indicator is on top selectionIndicator = new selectionIndicatorClass(); selectionIndicator.mouseEnabled = false; addChild(selectionIndicator); } if (!contentGroupMask) { // Create a mask for the content contentGroupMask = new Sprite(); addChild(contentGroupMask); } } /** * @private */ override protected function measure():void { super.measure(); var contentW:Number = contentGroup.getPreferredBoundsWidth(); var contentH:Number = contentGroup.getPreferredBoundsHeight(); measuredWidth = measuredMinWidth = contentW + borderThickness * 2; measuredHeight = contentH + borderThickness * 2; measuredMinHeight = selectionIndicatorHeight + borderThickness * 4; minHeight = measuredMinHeight; } /** * @private */ override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void { super.layoutContents(unscaledWidth, unscaledHeight); unscaledHeight = Math.max(unscaledHeight, selectionIndicatorHeight + borderThickness * 4); setElementSize(contentGroup, unscaledWidth - borderThickness * 2, unscaledHeight - borderThickness * 2); setElementPosition(contentGroup, borderThickness, borderThickness); // Inset by the borderThickness horizontally because the selectionIndicator starts at 0 setElementSize(border, unscaledWidth - borderThickness * 2, unscaledHeight); setElementPosition(border, borderThickness, 0); setElementSize(shadow, unscaledWidth - borderThickness * 4, unscaledHeight - borderThickness * 2); setElementPosition(shadow, borderThickness * 2, borderThickness); setElementSize(selectionIndicator, unscaledWidth, selectionIndicatorHeight); setElementPosition(selectionIndicator, 0, Math.floor((unscaledHeight - selectionIndicatorHeight) / 2)); // The SpinnerLists contain a left and right border. We don't want to show the leftmost // SpinnerLists's left border nor the rightmost one's right border. // We inset the mask on the left and right sides to accomplish this. var g:Graphics = contentGroupMask.graphics; g.clear(); g.beginFill(0x00FF00); g.drawRoundRect(borderThickness * 2, borderThickness, unscaledWidth - borderThickness * 4, unscaledHeight - borderThickness * 2, cornerRadius, cornerRadius); g.endFill(); contentGroup.mask = contentGroupMask; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.skins.mobile { import flash.display.Graphics; import flash.display.InteractiveObject; import flash.display.Sprite; import mx.core.DPIClassification; import spark.components.Group; import spark.components.SpinnerListContainer; import spark.layouts.HorizontalLayout; import spark.skins.mobile.supportClasses.MobileSkin; import spark.skins.mobile120.assets.SpinnerListContainerBackground; import spark.skins.mobile120.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile120.assets.SpinnerListContainerShadow; import spark.skins.mobile160.assets.SpinnerListContainerBackground; import spark.skins.mobile160.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile160.assets.SpinnerListContainerShadow; import spark.skins.mobile240.assets.SpinnerListContainerBackground; import spark.skins.mobile240.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile240.assets.SpinnerListContainerShadow; import spark.skins.mobile320.assets.SpinnerListContainerBackground; import spark.skins.mobile320.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile320.assets.SpinnerListContainerShadow; import spark.skins.mobile480.assets.SpinnerListContainerBackground; import spark.skins.mobile480.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile480.assets.SpinnerListContainerShadow; import spark.skins.mobile640.assets.SpinnerListContainerBackground; import spark.skins.mobile640.assets.SpinnerListContainerSelectionIndicator; import spark.skins.mobile640.assets.SpinnerListContainerShadow; /** * ActionScript-based skin for the SpinnerListContainer in mobile applications. * * @see spark.components.SpinnerListContainer * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ public class SpinnerListContainerSkin extends MobileSkin { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 * */ public function SpinnerListContainerSkin() { super(); switch (applicationDPI) { case DPIClassification.DPI_640: { // Note provisional may need changes borderClass = spark.skins.mobile640.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile640.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile640.assets.SpinnerListContainerShadow; cornerRadius = 20; borderThickness = 3; selectionIndicatorHeight = 182; break; } case DPIClassification.DPI_480: { // Note provisional may need changes borderClass = spark.skins.mobile480.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile480.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile480.assets.SpinnerListContainerShadow; cornerRadius = 16; borderThickness = 2; selectionIndicatorHeight = 144; break; } case DPIClassification.DPI_320: { borderClass = spark.skins.mobile320.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile320.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile320.assets.SpinnerListContainerShadow; cornerRadius = 10; borderThickness = 2; selectionIndicatorHeight = 96; break; } case DPIClassification.DPI_240: { borderClass = spark.skins.mobile240.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile240.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile240.assets.SpinnerListContainerShadow; cornerRadius = 8; borderThickness = 1; selectionIndicatorHeight = 72; break; } case DPIClassification.DPI_120: { borderClass = spark.skins.mobile120.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile120.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile120.assets.SpinnerListContainerShadow; cornerRadius = 4; borderThickness = 1; selectionIndicatorHeight = 37; break; } default: // default DPI_160 { borderClass = spark.skins.mobile160.assets.SpinnerListContainerBackground; selectionIndicatorClass = spark.skins.mobile160.assets.SpinnerListContainerSelectionIndicator; shadowClass = spark.skins.mobile160.assets.SpinnerListContainerShadow; cornerRadius = 5; borderThickness = 1; selectionIndicatorHeight = 48; break; } } minWidth = 30; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * Pixel thickness of the border. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var borderThickness:Number; /** * Radius of the border corners. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var cornerRadius:Number; /** * Height of the selection indicator. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var selectionIndicatorHeight:Number; /** * Class for the border part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var borderClass:Class; /** * Class for the selection indicator skin part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var selectionIndicatorClass:Class; /** * Class for the shadow skin part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var shadowClass:Class; /** * Border skin part which includes the background. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var border:InteractiveObject; /** * Selection indicator skin part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var selectionIndicator:InteractiveObject; /** * Shadow skin part. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var shadow:InteractiveObject; /** * Mask for the content group. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ protected var contentGroupMask:Sprite; //-------------------------------------------------------------------------- // // Skin parts // //-------------------------------------------------------------------------- /** * An optional skin part that defines the Group where the content * children are pushed into and laid out. * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ public var contentGroup:Group; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** * @copy spark.skins.spark.ApplicationSkin#hostComponent * * @langversion 3.0 * @playerversion AIR 3 * @productversion Flex 4.6 */ public var hostComponent:SpinnerListContainer; //-------------------------------------------------------------------------- // // Overridden Methods // //-------------------------------------------------------------------------- /** * @private */ override protected function createChildren():void { super.createChildren(); if (!border) { // Border and background border = new borderClass(); border.mouseEnabled = false; addChild(border); } if (!contentGroup) { // Contains the child elements contentGroup = new Group(); var hLayout:HorizontalLayout = new HorizontalLayout(); hLayout.gap = 0; hLayout.verticalAlign = "middle"; contentGroup.layout = hLayout; contentGroup.id = "contentGroup"; addChild(contentGroup); } if (!shadow) { // Shadowing sits on top of the content shadow = new shadowClass(); shadow.mouseEnabled = false; addChild(shadow); } if (!selectionIndicator) { // Selection indicator is on top selectionIndicator = new selectionIndicatorClass(); selectionIndicator.mouseEnabled = false; addChild(selectionIndicator); } if (!contentGroupMask) { // Create a mask for the content contentGroupMask = new Sprite(); addChild(contentGroupMask); } } /** * @private */ override protected function measure():void { super.measure(); var contentW:Number = contentGroup.getPreferredBoundsWidth(); var contentH:Number = contentGroup.getPreferredBoundsHeight(); measuredWidth = measuredMinWidth = contentW + borderThickness * 2; measuredHeight = contentH + borderThickness * 2; measuredMinHeight = selectionIndicatorHeight + borderThickness * 4; minHeight = measuredMinHeight; } /** * @private */ override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void { super.layoutContents(unscaledWidth, unscaledHeight); unscaledHeight = Math.max(unscaledHeight, selectionIndicatorHeight + borderThickness * 4); setElementSize(contentGroup, unscaledWidth - borderThickness * 2, unscaledHeight - borderThickness * 2); setElementPosition(contentGroup, borderThickness, borderThickness); // Inset by the borderThickness horizontally because the selectionIndicator starts at 0 setElementSize(border, unscaledWidth - borderThickness * 2, unscaledHeight); setElementPosition(border, borderThickness, 0); setElementSize(shadow, unscaledWidth - borderThickness * 4, unscaledHeight - borderThickness * 2); setElementPosition(shadow, borderThickness * 2, borderThickness); setElementSize(selectionIndicator, unscaledWidth, selectionIndicatorHeight); setElementPosition(selectionIndicator, 0, Math.floor((unscaledHeight - selectionIndicatorHeight) / 2)); // The SpinnerLists contain a left and right border. We don't want to show the leftmost // SpinnerLists's left border nor the rightmost one's right border. // We inset the mask on the left and right sides to accomplish this. var g:Graphics = contentGroupMask.graphics; g.clear(); g.beginFill(0x00FF00); g.drawRoundRect(borderThickness * 2, borderThickness, unscaledWidth - borderThickness * 4, unscaledHeight - borderThickness * 2, cornerRadius, cornerRadius); g.endFill(); contentGroup.mask = contentGroupMask; } } }
fix 160/480 path names
fix 160/480 path names
ActionScript
apache-2.0
adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk
f6108cba0dd02ba713a81ef7cf4ac254bbf95f0f
sdk-remote/src/tests/bin/uobject-check.as
sdk-remote/src/tests/bin/uobject-check.as
-*- shell-script -*- URBI_INIT # The full path to the *.uob dir: # ../../../../../sdk-remote/src/tests/uobjects/access-and-change/uaccess.uob uob=$(absolute $1.uob) require_dir "$uob" # The ending part, for our builddir: access-and-change/uaccess.dir. builddir=$(echo "$uob" | sed -e 's,.*/src/tests/uobjects/,uobjects/,;s/\.uob$//').dir # For error messages. me=$(basename "$uob" .uob) # The directory we work in. rm -rf $builddir mkdir -p $builddir cd $builddir # The remote component: an executable. umake_remote=$(xfind_prog "umake-remote") xrun "umake-remote" $umake_remote --output=$me$EXEEXT $uob test -x "$me$EXEEXT" || fatal "$me is not executable" xrun "$me --version" "./$me$EXEEXT" --version # The shared component: a dlopen module. umake_shared=$(xfind_prog "umake-shared") xrun "umake-shared" $umake_shared --output=$me $uob test -f "$me.la" || fatal "$me.la does not exist" # Find urbi-launch. urbi_launch=$(xfind_prog urbi-launch$EXEEXT) # If urbi-launch cannot work because there is no kernel libuobject, # skip the test. Do pass something that will fail to be loaded, # otherwise if it works, a server is launched, and will run endlessly. run "urbi-launch --start" $urbi_launch --start /dev/null || case $? in (72) error 77 "urbi-launch cannot find libuobject";; esac xrun "urbi-launch $me --version" "$urbi_launch" --start $me.la -- --version
-*- shell-script -*- URBI_INIT # The full path to the *.uob dir: # ../../../../../sdk-remote/src/tests/uobjects/access-and-change/uaccess.uob uob=$(absolute $1.uob) require_dir "$uob" # The ending part, for our builddir: access-and-change/uaccess.dir. builddir=$(echo "$uob" | sed -e 's,.*/src/tests/uobjects/,uobjects/,;s/\.uob$//').dir # For error messages. me=$(basename "$uob" .uob) # The directory we work in. rm -rf $builddir mkdir -p $builddir cd $builddir # The remote component: an executable. umake_remote=$(xfind_prog "umake-remote") xrun "umake-remote" $umake_remote --output=$me$EXEEXT $uob test -x "$me$EXEEXT" || fatal "$me is not executable" xrun "$me --version" "./$me$EXEEXT" --version # The shared component: a dlopen module. umake_shared=$(xfind_prog "umake-shared") xrun "umake-shared" $umake_shared --output=$me $uob test -f "$me.la" || fatal "$me.la does not exist" # Find urbi-launch. urbi_launch=$(xfind_prog urbi-launch$EXEEXT) # If urbi-launch cannot work because there is no kernel libuobject, # skip the test. Do pass something that will fail to be loaded, # otherwise if it works, a server is launched, and will run endlessly. run "urbi-launch --start" $urbi_launch --start /dev/null || case $? in (72) error SKIP "urbi-launch cannot find libuobject";; esac xrun "urbi-launch $me --version" "$urbi_launch" --start $me.la -- --version
Fix SKIP exit code.
Fix SKIP exit code. * src/tests/bin/uobject-check.as: Use the symbolic value.
ActionScript
bsd-3-clause
aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi
a84eff2dbd3182410a6daa036d9d181f46394564
src/aerys/minko/render/geometry/stream/IndexStream.as
src/aerys/minko/render/geometry/stream/IndexStream.as
package aerys.minko.render.geometry.stream { import aerys.minko.ns.minko_stream; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.type.Signal; import flash.utils.ByteArray; public final class IndexStream { use namespace minko_stream; minko_stream var _data : Vector.<uint> = null; minko_stream var _localDispose : Boolean = false; private var _usage : uint = 0; private var _resource : IndexBuffer3DResource = null; private var _length : uint = 0; private var _changed : Signal = new Signal('IndexStream.changed'); public function get usage() : uint { return _usage; } public function get resource() : IndexBuffer3DResource { return _resource; } public function get length() : uint { return _length; } public function set length(value : uint) : void { _data.length = value; invalidate(); } public function get changed() : Signal { return _changed; } public function IndexStream(usage : uint, data : Vector.<uint> = null, length : uint = 0) { super(); initialize(data, length, usage); } minko_stream function invalidate() : void { _length = _data.length; _changed.execute(this); } private function initialize(indices : Vector.<uint>, length : uint, usage : uint) : void { _usage = usage; _resource = new IndexBuffer3DResource(this); if (indices) { var numIndices : int = indices && length == 0 ? indices.length : Math.min(indices.length, length); _data = new Vector.<uint>(numIndices); for (var i : int = 0; i < numIndices; ++i) _data[i] = indices[i]; } else { _data = dummyData(length); } invalidate(); } public function get(index : int) : uint { checkReadUsage(this); return _data[index]; } public function set(index : int, value : uint) : void { checkWriteUsage(this); _data[index] = value; } public function deleteTriangleByIndex(index : int) : Vector.<uint> { checkWriteUsage(this); var deletedIndices : Vector.<uint> = _data.splice(index, 3); invalidate(); return deletedIndices; } public function getIndices(indices : Vector.<uint> = null) : Vector.<uint> { checkReadUsage(this); var numIndices : int = length; indices ||= new Vector.<uint>(); for (var i : int = 0; i < numIndices; ++i) indices[i] = _data[i]; return indices; } public function setIndices(indices : Vector.<uint>) : void { checkWriteUsage(this); var length : int = indices.length; for (var i : int = 0; i < length; ++i) _data[i] = indices[i]; _data.length = length; invalidate(); } public function clone(usage : uint = 0) : IndexStream { return new IndexStream(usage || _usage, _data, length); } public function toString() : String { return _data.toString(); } public function concat(indexStream : IndexStream, firstIndex : uint = 0, count : uint = 0, offset : uint = 0) : IndexStream { checkReadUsage(indexStream); checkWriteUsage(this); var numIndices : int = _data.length; var toConcat : Vector.<uint> = indexStream._data; count ||= toConcat.length; for (var i : int = 0; i < count; ++i, ++numIndices) _data[numIndices] = toConcat[int(firstIndex + i)] + offset; invalidate(); return this; } public function push(indices : Vector.<uint>, firstIndex : uint = 0, count : uint = 0, offset : uint = 0) : void { checkWriteUsage(this); var numIndices : int = _data.length; count ||= indices.length; for (var i : int = 0; i < count; ++i) _data[int(numIndices++)] = indices[int(firstIndex + i)] + offset; invalidate(); } public function disposeLocalData(waitForUpload : Boolean = true) : void { if (waitForUpload && _length != resource.numIndices) _localDispose = true; else { _data = null; _usage = StreamUsage.STATIC; } } public function dispose() : void { _resource.dispose(); } private static function checkReadUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.READ)) throw new Error( 'Unable to read from vertex stream: stream usage ' + 'is not set to StreamUsage.READ.' ); } private static function checkWriteUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.WRITE)) throw new Error( 'Unable to write in vertex stream: stream usage ' + 'is not set to StreamUsage.WRITE.' ); } public static function dummyData(size : uint, offset : uint = 0) : Vector.<uint> { var indices : Vector.<uint> = new Vector.<uint>(size); for (var i : int = 0; i < size; ++i) indices[i] = i + offset; return indices; } public static function fromByteArray(usage : uint, data : ByteArray, numIndices : int) : IndexStream { var indices : Vector.<uint> = new Vector.<uint>(numIndices, true); var stream : IndexStream = new IndexStream(usage); for (var i : int = 0; i < numIndices; ++i) indices[i] = data.readInt(); stream._data = indices; stream.invalidate(); return stream; } } }
package aerys.minko.render.geometry.stream { import aerys.minko.ns.minko_stream; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.type.Signal; import flash.utils.ByteArray; public final class IndexStream { use namespace minko_stream; minko_stream var _data : Vector.<uint> = null; minko_stream var _localDispose : Boolean = false; private var _usage : uint = 0; private var _resource : IndexBuffer3DResource = null; private var _length : uint = 0; private var _hasChanged : Boolean = false; private var _locked : Boolean = false; private var _changed : Signal = new Signal('IndexStream.changed'); public function get usage() : uint { return _usage; } public function get resource() : IndexBuffer3DResource { return _resource; } public function get length() : uint { return _length; } public function set length(value : uint) : void { _data.length = value; invalidate(); } public function get changed() : Signal { return _changed; } public function IndexStream(usage : uint, data : Vector.<uint> = null, length : uint = 0) { super(); initialize(data, length, usage); } minko_stream function invalidate() : void { _length = _data.length; if (_locked) _hasChanged = true; else _changed.execute(this); } private function initialize(indices : Vector.<uint>, length : uint, usage : uint) : void { _usage = usage; _resource = new IndexBuffer3DResource(this); if (indices) { var numIndices : int = indices && length == 0 ? indices.length : Math.min(indices.length, length); _data = new Vector.<uint>(numIndices); for (var i : int = 0; i < numIndices; ++i) _data[i] = indices[i]; } else { _data = dummyData(length); } invalidate(); } public function get(index : int) : uint { checkReadUsage(this); return _data[index]; } public function set(index : int, value : uint) : void { checkWriteUsage(this); _data[index] = value; } public function deleteTriangleByIndex(index : int) : Vector.<uint> { checkWriteUsage(this); var deletedIndices : Vector.<uint> = _data.splice(index, 3); invalidate(); return deletedIndices; } public function getIndices(indices : Vector.<uint> = null) : Vector.<uint> { checkReadUsage(this); var numIndices : int = length; indices ||= new Vector.<uint>(); for (var i : int = 0; i < numIndices; ++i) indices[i] = _data[i]; return indices; } public function setIndices(indices : Vector.<uint>) : void { checkWriteUsage(this); var length : int = indices.length; for (var i : int = 0; i < length; ++i) _data[i] = indices[i]; _data.length = length; invalidate(); } public function clone(usage : uint = 0) : IndexStream { return new IndexStream(usage || _usage, _data, length); } public function toString() : String { return _data.toString(); } public function concat(indexStream : IndexStream, firstIndex : uint = 0, count : uint = 0, offset : uint = 0) : IndexStream { checkReadUsage(indexStream); checkWriteUsage(this); var numIndices : int = _data.length; var toConcat : Vector.<uint> = indexStream._data; count ||= toConcat.length; for (var i : int = 0; i < count; ++i, ++numIndices) _data[numIndices] = toConcat[int(firstIndex + i)] + offset; invalidate(); return this; } public function push(indices : Vector.<uint>, firstIndex : uint = 0, count : uint = 0, offset : uint = 0) : void { checkWriteUsage(this); var numIndices : int = _data.length; count ||= indices.length; for (var i : int = 0; i < count; ++i) _data[int(numIndices++)] = indices[int(firstIndex + i)] + offset; invalidate(); } public function disposeLocalData(waitForUpload : Boolean = true) : void { if (waitForUpload && _length != resource.numIndices) _localDispose = true; else { _data = null; _usage = StreamUsage.STATIC; } } public function dispose() : void { _resource.dispose(); } public function lock() : Vector.<uint> { checkReadUsage(this); checkWriteUsage(this); _hasChanged = false; _locked = true; return _data; } public function unlock(hasChanged : Boolean = true) : void { if (_hasChanged && hasChanged) _changed.execute(this); _hasChanged = false; } private static function checkReadUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.READ)) throw new Error( 'Unable to read from vertex stream: stream usage is not set to StreamUsage.READ.' ); } private static function checkWriteUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.WRITE)) throw new Error( 'Unable to write in vertex stream: stream usage is not set to StreamUsage.WRITE.' ); } public static function dummyData(size : uint, offset : uint = 0) : Vector.<uint> { var indices : Vector.<uint> = new Vector.<uint>(size); for (var i : int = 0; i < size; ++i) indices[i] = i + offset; return indices; } public static function fromByteArray(usage : uint, data : ByteArray, numIndices : int) : IndexStream { var indices : Vector.<uint> = new Vector.<uint>(numIndices, true); var stream : IndexStream = new IndexStream(usage); for (var i : int = 0; i < numIndices; ++i) indices[i] = data.readInt(); stream._data = indices; stream.invalidate(); return stream; } } }
fix IndexStram.invalidate() to set _hasChanged = true when locked
fix IndexStram.invalidate() to set _hasChanged = true when locked
ActionScript
mit
aerys/minko-as3
7b02511e468f5e29d3870bc117d24fac3478abee
src/aerys/minko/type/loader/parser/ParserOptions.as
src/aerys/minko/type/loader/parser/ParserOptions.as
package aerys.minko.type.loader.parser { import aerys.minko.render.Effect; import aerys.minko.scene.node.Mesh; import aerys.minko.type.animation.SkinningMethod; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.TextureLoader; import flash.net.URLRequest; /** * ParserOptions objects provide properties and function references * to customize how a LoaderGroup object will load and interpret * content. * * @author Jean-Marc Le Roux * */ public final class ParserOptions { private var _loadDependencies : Boolean = false; private var _dependencyLoaderClosure : Function = defaultDependencyLoaderClosure; private var _loadSkin : Boolean = false; private var _skinningMethod : uint = SkinningMethod.SHADER_DUAL_QUATERNION; private var _mipmapTextures : Boolean = true; private var _meshEffect : Effect = null; private var _vertexStreamUsage : uint = 0; private var _indexStreamUsage : uint = 0; private var _parser : Class = null; public function get skinningMethod() : uint { return _skinningMethod; } public function set skinningMethod(value : uint) : void { _skinningMethod = value; } public function get parser() : Class { return _parser; } public function set parser(value : Class) : void { _parser = value; } public function get indexStreamUsage() : uint { return _indexStreamUsage; } public function set indexStreamUsage(value : uint) : void { _indexStreamUsage = value; } public function get vertexStreamUsage() : uint { return _vertexStreamUsage; } public function set vertexStreamUsage(value : uint) : void { _vertexStreamUsage = value; } public function get effect() : Effect { return _meshEffect; } public function set effect(value : Effect) : void { _meshEffect = value; } public function get mipmapTextures() : Boolean { return _mipmapTextures; } public function set mipmapTextures(value : Boolean) : void { _mipmapTextures = value; } public function get dependencyLoaderClosure() : Function { return _dependencyLoaderClosure; } public function set dependencyLoaderClosure(value : Function) : void { _dependencyLoaderClosure = value; } public function get loadDependencies() : Boolean { return _loadDependencies; } public function set loadDependencies(value : Boolean) : void { _loadDependencies = value; } public function get loadSkin() : Boolean { return _loadSkin; } public function set loadSkin(value : Boolean) : void { _loadSkin = value; } public function clone() : ParserOptions { return new ParserOptions( _loadDependencies, _dependencyLoaderClosure, _loadSkin, _skinningMethod, _mipmapTextures, _meshEffect, _vertexStreamUsage, _indexStreamUsage, _parser ); } public function ParserOptions(loadDependencies : Boolean = false, dependencyLoaderClosure : Function = null, loadSkin : Boolean = true, skinningMethod : uint = 2, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _loadDependencies = loadDependencies; _dependencyLoaderClosure = dependencyLoaderClosure || _dependencyLoaderClosure; _loadSkin = loadSkin; _skinningMethod = skinningMethod; _mipmapTextures = mipmapTextures; _meshEffect = meshEffect || Mesh.DEFAULT_MATERIAL.effect; _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderClosure(dependencyPath : String, isTexture : Boolean, options : ParserOptions) : ILoader { var loader : ILoader; if (isTexture) { loader = new TextureLoader(true); loader.load(new URLRequest(dependencyPath)); } else { loader = new SceneLoader(options); loader.load(new URLRequest(dependencyPath)); } return loader; } } }
package aerys.minko.type.loader.parser { import aerys.minko.render.Effect; import aerys.minko.scene.node.Mesh; import aerys.minko.type.animation.SkinningMethod; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.TextureLoader; import flash.net.URLRequest; /** * ParserOptions objects provide properties and function references * to customize how a LoaderGroup object will load and interpret * content. * * @author Jean-Marc Le Roux * */ public final class ParserOptions { private var _loadDependencies : Boolean = false; private var _dependencyLoaderFunction : Function = defaultDependencyLoaderFunction; private var _loadSkin : Boolean = false; private var _skinningMethod : uint = SkinningMethod.SHADER_DUAL_QUATERNION; private var _mipmapTextures : Boolean = true; private var _meshEffect : Effect = null; private var _vertexStreamUsage : uint = 0; private var _indexStreamUsage : uint = 0; private var _parser : Class = null; public function get skinningMethod() : uint { return _skinningMethod; } public function set skinningMethod(value : uint) : void { _skinningMethod = value; } public function get parser() : Class { return _parser; } public function set parser(value : Class) : void { _parser = value; } public function get indexStreamUsage() : uint { return _indexStreamUsage; } public function set indexStreamUsage(value : uint) : void { _indexStreamUsage = value; } public function get vertexStreamUsage() : uint { return _vertexStreamUsage; } public function set vertexStreamUsage(value : uint) : void { _vertexStreamUsage = value; } public function get effect() : Effect { return _meshEffect; } public function set effect(value : Effect) : void { _meshEffect = value; } public function get mipmapTextures() : Boolean { return _mipmapTextures; } public function set mipmapTextures(value : Boolean) : void { _mipmapTextures = value; } public function get dependencyLoaderFunction() : Function { return _dependencyLoaderFunction; } public function set dependencyLoaderFunction(value : Function) : void { _dependencyLoaderFunction = value; } public function get loadDependencies() : Boolean { return _loadDependencies; } public function set loadDependencies(value : Boolean) : void { _loadDependencies = value; } public function get loadSkin() : Boolean { return _loadSkin; } public function set loadSkin(value : Boolean) : void { _loadSkin = value; } public function clone() : ParserOptions { return new ParserOptions( _loadDependencies, _dependencyLoaderFunction, _loadSkin, _skinningMethod, _mipmapTextures, _meshEffect, _vertexStreamUsage, _indexStreamUsage, _parser ); } public function ParserOptions(loadDependencies : Boolean = false, dependencyLoaderClosure : Function = null, loadSkin : Boolean = true, skinningMethod : uint = 2, mipmapTextures : Boolean = true, meshEffect : Effect = null, vertexStreamUsage : uint = 0, indexStreamUsage : uint = 0, parser : Class = null) { _loadDependencies = loadDependencies; _dependencyLoaderFunction = dependencyLoaderClosure || _dependencyLoaderFunction; _loadSkin = loadSkin; _skinningMethod = skinningMethod; _mipmapTextures = mipmapTextures; _meshEffect = meshEffect || Mesh.DEFAULT_MATERIAL.effect; _vertexStreamUsage = vertexStreamUsage; _indexStreamUsage = indexStreamUsage; _parser = parser; } private function defaultDependencyLoaderFunction(dependencyPath : String, isTexture : Boolean, options : ParserOptions) : ILoader { var loader : ILoader; if (isTexture) { loader = new TextureLoader(true); loader.load(new URLRequest(dependencyPath)); } else { loader = new SceneLoader(options); loader.load(new URLRequest(dependencyPath)); } return loader; } } }
rename ParserOptions.dependencyLoaderClosure into dependencyLoaderFunction
rename ParserOptions.dependencyLoaderClosure into dependencyLoaderFunction
ActionScript
mit
aerys/minko-as3
9048d4b0250a6742f81712f65cccf04c0be4aa94
src/aerys/minko/render/effect/vertex/VertexUVShader.as
src/aerys/minko/render/effect/vertex/VertexUVShader.as
package aerys.minko.render.effect.vertex { import aerys.minko.render.RenderTarget; import aerys.minko.render.effect.basic.BasicProperties; import aerys.minko.render.effect.basic.BasicShader; import aerys.minko.render.shader.SFloat; import aerys.minko.type.stream.format.VertexComponent; public class VertexUVShader extends BasicShader { public function VertexUVShader(target : RenderTarget = null, priority : Number = 0) { super(target, priority); } override protected function getPixelColor() : SFloat { var uv : SFloat = getVertexAttribute(VertexComponent.UV); if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_SCALE)) uv.scaleBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_SCALE, 2)); if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_OFFSET)) uv.incrementBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_OFFSET, 2)); var interpolatedUv : SFloat = fractional(interpolate(uv)); return float4(interpolatedUv.x, interpolatedUv.y, 0, 1); } } }
package aerys.minko.render.effect.vertex { import aerys.minko.render.RenderTarget; import aerys.minko.render.effect.basic.BasicProperties; import aerys.minko.render.effect.basic.BasicShader; import aerys.minko.render.shader.SFloat; import aerys.minko.type.stream.format.VertexComponent; public class VertexUVShader extends BasicShader { public function VertexUVShader(target : RenderTarget = null, priority : Number = 0) { super(target, priority); } override protected function getPixelColor() : SFloat { var uv : SFloat = getVertexAttribute(VertexComponent.UV); if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_SCALE)) uv.scaleBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_SCALE, 2)); if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_OFFSET)) uv.incrementBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_OFFSET, 2)); uv = interpolate(uv); var fractional : SFloat = fractional(uv); var fractionalIsZero : SFloat = equal(fractional, float2(0, 0)); var interpolatedUv : SFloat = add( multiply(not(fractionalIsZero), fractional), multiply(fractionalIsZero, saturate(uv)) ); return float4(interpolatedUv.x, interpolatedUv.y, 0, 1); } } }
Optimize uv shader for limit values
Optimize uv shader for limit values
ActionScript
mit
aerys/minko-as3
435567f62f1e413caca8de2a7b654b637da4a9b4
WeaveData/src/weave/data/AttributeColumns/DateColumn.as
WeaveData/src/weave/data/AttributeColumns/DateColumn.as
/* ***** BEGIN LICENSE BLOCK ***** * * This file is part of Weave. * * The Initial Developer of Weave is the Institute for Visualization * and Perception Research at the University of Massachusetts Lowell. * Portions created by the Initial Developer are Copyright (C) 2008-2015 * the Initial Developer. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * * ***** END LICENSE BLOCK ***** */ package weave.data.AttributeColumns { import flash.system.Capabilities; import flash.utils.Dictionary; import flash.utils.getTimer; import weave.api.data.ColumnMetadata; import weave.api.data.DataType; import weave.api.data.IPrimitiveColumn; import weave.api.data.IQualifiedKey; import weave.api.reportError; import weave.compiler.Compiler; import weave.compiler.StandardLib; import weave.flascc.date_format; import weave.flascc.date_parse; import weave.flascc.dates_detect; /** * @author adufilie */ public class DateColumn extends AbstractAttributeColumn implements IPrimitiveColumn { public function DateColumn(metadata:Object = null) { super(metadata); } private const _uniqueKeys:Array = new Array(); private var _keyToDate:Dictionary = new Dictionary(); // temp variables for async task private var _i:int; private var _keys:Vector.<IQualifiedKey>; private var _dates:Vector.<String>; private var _reportedError:Boolean; // variables that do not get reset after async task private static const compiler:Compiler = new Compiler(); private var _stringToNumberFunction:Function = null; private var _numberToStringFunction:Function = null; private var _dateFormat:String = null; private var _useFlascc:Boolean = true; /** * @inheritDoc */ override public function getMetadata(propertyName:String):String { if (propertyName == ColumnMetadata.DATA_TYPE) return DataType.DATE; if (propertyName == ColumnMetadata.DATE_FORMAT) return _dateFormat; return super.getMetadata(propertyName); } /** * @inheritDoc */ override public function get keys():Array { return _uniqueKeys; } /** * @inheritDoc */ override public function containsKey(key:IQualifiedKey):Boolean { return _keyToDate[key] != undefined; } public function setRecords(keys:Vector.<IQualifiedKey>, dates:Vector.<String>):void { if (keys.length > dates.length) { reportError("Array lengths differ"); return; } // read dateFormat metadata _dateFormat = getMetadata(ColumnMetadata.DATE_FORMAT); if (!_dateFormat) { var possibleFormats:Array = detectDateFormats(dates); StandardLib.sortOn(possibleFormats, 'length'); _dateFormat = possibleFormats.pop(); } _dateFormat = convertDateFormat_as_to_c(_dateFormat); //_useFlascc = _dateFormat && _dateFormat.indexOf('%') >= 0; // compile the number format function from the metadata _stringToNumberFunction = null; var numberFormat:String = getMetadata(ColumnMetadata.NUMBER); if (numberFormat) { try { _stringToNumberFunction = compiler.compileToFunction(numberFormat, null, errorHandler, false, [ColumnMetadata.STRING]); } catch (e:Error) { reportError(e); } } // compile the string format function from the metadata _numberToStringFunction = null; var stringFormat:String = getMetadata(ColumnMetadata.STRING); if (stringFormat) { try { _numberToStringFunction = compiler.compileToFunction(stringFormat, null, errorHandler, false, [ColumnMetadata.NUMBER]); } catch (e:Error) { reportError(e); } } _i = 0; _keys = keys; _dates = dates; _keyToDate = new Dictionary(); _uniqueKeys.length = 0; _reportedError = false; // high priority because not much can be done without data WeaveAPI.StageUtils.startTask(this, _asyncIterate, WeaveAPI.TASK_PRIORITY_HIGH, _asyncComplete); } private function errorHandler(e:*):void { return; // do nothing } private function _asyncComplete():void { _keys = null; _dates = null; triggerCallbacks(); } private function parseDate(string:String):Date { if (_useFlascc) return weave.flascc.date_parse(string, _dateFormat); return StandardLib.parseDate(string, _dateFormat); } private function formatDate(value:Object):String { if (_useFlascc) return weave.flascc.date_format(value as Date || new Date(value), _dateFormat); return StandardLib.formatDate(value, _dateFormat); } private function _asyncIterate(stopTime:int):Number { for (; _i < _keys.length; _i++) { if (getTimer() > stopTime) return _i / _keys.length; // get values for this iteration var key:IQualifiedKey = _keys[_i]; var string:String = _dates[_i]; var date:Date; if (_stringToNumberFunction != null) { var number:Number = _stringToNumberFunction(string); if (_numberToStringFunction != null) { string = _numberToStringFunction(number); if (!string) continue; date = parseDate(string); } else { if (!isFinite(number)) continue; date = new Date(number); } } else { try { if (!string) continue; date = parseDate(string); } catch (e:Error) { if (!_reportedError) { _reportedError = true; var err:String = StandardLib.substitute( 'Warning: Unable to parse this value as a date: "{0}"' + ' (only the first error for this column is reported).' + ' Attribute column: {1}', string, Compiler.stringify(_metadata) ); reportError(err); } continue; } } // keep track of unique keys if (_keyToDate[key] === undefined) { _uniqueKeys.push(key); // save key-to-data mapping _keyToDate[key] = date; } else if (!_reportedError) { _reportedError = true; var fmt:String = 'Warning: Key column values are not unique. Record dropped due to duplicate key ({0}) (only reported for first duplicate). Attribute column: {1}'; var str:String = StandardLib.substitute(fmt, key.localName, Compiler.stringify(_metadata)); if (Capabilities.isDebugger) reportError(str); } } return 1; } /** * @inheritDoc */ public function deriveStringFromNumber(number:Number):String { if (_numberToStringFunction != null) return _numberToStringFunction(number); if (_dateFormat) return formatDate(number); return new Date(number).toString(); } /** * @inheritDoc */ override public function getValueFromKey(key:IQualifiedKey, dataType:Class = null):* { var number:Number; var string:String; var date:Date; if (dataType == Number) { number = _keyToDate[key]; return number; } if (dataType == String) { if (_numberToStringFunction != null) { number = _keyToDate[key]; return _numberToStringFunction(number); } date = _keyToDate[key]; if (!date) return ''; if (_dateFormat) string = formatDate(date); else string = date.toString(); return string; } date = _keyToDate[key]; if (dataType) return date as DataType; return date; } override public function toString():String { return debugId(this) + '{recordCount: '+keys.length+', keyType: "'+getMetadata('keyType')+'", title: "'+getMetadata('title')+'"}'; } private static function convertDateFormat_as_to_c(format:String):String { if (!format || format.indexOf('%') >= 0) return format; return StandardLib.replace.apply(null, [format].concat(dateFormat_replacements_as_to_c)); } private static const dateFormat_replacements_as_to_c:Array = [ 'YYYY','%Y', 'YY','%y', 'MMMM','%B', 'MMM','%b', 'MM','%m', 'M','%-m', 'DD','%d', 'D','%-d', 'E','%u', 'A','%p', 'JJ','%H', 'J','%-H', 'LL','%I', 'L','%-I', 'EEEE','%A', // note this %A is after the A was replaced above 'EEE','%a', 'NN','%M', // note these %M appears after the M's were replaced above 'N','%-M', 'SS','%S' //,'S','%-S' ]; public static function detectDateFormats(dates:*):Array { return weave.flascc.dates_detect(dates, DATE_FORMAT_AUTO_DETECT); } public static const DATE_FORMAT_ADDITIONAL_SUGGESTIONS:Array = [ "%Y" ]; public static const DATE_FORMAT_AUTO_DETECT:Array = [ '%d-%b-%y', '%b-%d-%y', '%d-%b-%Y', '%b-%d-%Y', '%Y-%b-%d', '%d/%b/%y', '%b/%d/%y', '%d/%b/%Y', '%b/%d/%Y', '%Y/%b/%d', '%d.%b.%y', '%b.%d.%y', '%d.%b.%Y', '%b.%d.%Y', '%Y.%b.%d', '%d-%m-%y', '%m-%d-%y', '%d-%m-%Y', '%m-%d-%Y', '%Y-%m-%d', '%d/%m/%y', '%m/%d/%y', '%d/%m/%Y', '%m/%d/%Y', '%Y/%m/%d', '%d.%m.%y', '%m.%d.%y', '%d.%m.%Y', '%m.%d.%Y', '%Y.%m.%d', '%H:%M', '%H:%M:%S', '%a, %d %b %Y %H:%M:%S %z', // RFC_822 // ISO_8601 http://www.thelinuxdaily.com/2014/03/c-function-to-validate-iso-8601-date-formats-using-strptime/ "%Y-%m-%d", "%y-%m-%d", "%Y-%m-%d %T", "%y-%m-%d %T", "%Y-%m-%dT%T", "%y-%m-%dT%T", "%Y-%m-%dT%TZ", "%y-%m-%dT%TZ", "%Y-%m-%d %TZ", "%y-%m-%d %TZ", "%Y%m%dT%TZ", "%y%m%dT%TZ", "%Y%m%d %TZ", "%y%m%d %TZ", "%Y-%b-%d %T", "%Y-%b-%d %H:%M:%S", "%d-%b-%Y %T", "%d-%b-%Y %H:%M:%S" /* //https://code.google.com/p/datejs/source/browse/trunk/src/globalization/en-US.js 'M/d/yyyy', 'dddd, MMMM dd, yyyy', "M/d/yyyy", "dddd, MMMM dd, yyyy", "h:mm tt", "h:mm:ss tt", "dddd, MMMM dd, yyyy h:mm:ss tt", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-dd HH:mm:ssZ", "ddd, dd MMM yyyy HH:mm:ss GMT", "MMMM dd", "MMMM, yyyy", //http://www.java2s.com/Code/Android/Date-Type/parseDateforlistofpossibleformats.htm "EEE, dd MMM yyyy HH:mm:ss z", // RFC_822 "EEE, dd MMM yyyy HH:mm zzzz", "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss.SSSzzzz", // Blogger Atom feed has millisecs also "yyyy-MM-dd'T'HH:mm:sszzzz", "yyyy-MM-dd'T'HH:mm:ss z", "yyyy-MM-dd'T'HH:mm:ssz", // ISO_8601 "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HHmmss.SSSz", //http://stackoverflow.com/a/21737848 "M/d/yyyy", "MM/dd/yyyy", "d/M/yyyy", "dd/MM/yyyy", "yyyy/M/d", "yyyy/MM/dd", "M-d-yyyy", "MM-dd-yyyy", "d-M-yyyy", "dd-MM-yyyy", "yyyy-M-d", "yyyy-MM-dd", "M.d.yyyy", "MM.dd.yyyy", "d.M.yyyy", "dd.MM.yyyy", "yyyy.M.d", "yyyy.MM.dd", "M,d,yyyy", "MM,dd,yyyy", "d,M,yyyy", "dd,MM,yyyy", "yyyy,M,d", "yyyy,MM,dd", "M d yyyy", "MM dd yyyy", "d M yyyy", "dd MM yyyy", "yyyy M d", "yyyy MM dd" */ ]; } }
/* ***** BEGIN LICENSE BLOCK ***** * * This file is part of Weave. * * The Initial Developer of Weave is the Institute for Visualization * and Perception Research at the University of Massachusetts Lowell. * Portions created by the Initial Developer are Copyright (C) 2008-2015 * the Initial Developer. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * * ***** END LICENSE BLOCK ***** */ package weave.data.AttributeColumns { import flash.system.Capabilities; import flash.utils.Dictionary; import flash.utils.getTimer; import weave.api.data.ColumnMetadata; import weave.api.data.DataType; import weave.api.data.IPrimitiveColumn; import weave.api.data.IQualifiedKey; import weave.api.reportError; import weave.compiler.Compiler; import weave.compiler.StandardLib; import weave.flascc.date_format; import weave.flascc.date_parse; import weave.flascc.dates_detect; /** * @author adufilie */ public class DateColumn extends AbstractAttributeColumn implements IPrimitiveColumn { public function DateColumn(metadata:Object = null) { super(metadata); } private const _uniqueKeys:Array = new Array(); private var _keyToDate:Dictionary = new Dictionary(); // temp variables for async task private var _i:int; private var _keys:Vector.<IQualifiedKey>; private var _dates:Vector.<String>; private var _reportedError:Boolean; // variables that do not get reset after async task private static const compiler:Compiler = new Compiler(); private var _stringToNumberFunction:Function = null; private var _numberToStringFunction:Function = null; private var _dateFormat:String = null; private var _useFlascc:Boolean = true; /** * @inheritDoc */ override public function getMetadata(propertyName:String):String { if (propertyName == ColumnMetadata.DATA_TYPE) return DataType.DATE; if (propertyName == ColumnMetadata.DATE_FORMAT) return _dateFormat; return super.getMetadata(propertyName); } /** * @inheritDoc */ override public function get keys():Array { return _uniqueKeys; } /** * @inheritDoc */ override public function containsKey(key:IQualifiedKey):Boolean { return _keyToDate[key] != undefined; } public function setRecords(keys:Vector.<IQualifiedKey>, dates:Vector.<String>):void { if (keys.length > dates.length) { reportError("Array lengths differ"); return; } // read dateFormat metadata _dateFormat = getMetadata(ColumnMetadata.DATE_FORMAT); if (!_dateFormat) { var possibleFormats:Array = detectDateFormats(dates); StandardLib.sortOn(possibleFormats, 'length'); _dateFormat = possibleFormats.pop(); } _dateFormat = convertDateFormat_as_to_c(_dateFormat); //_useFlascc = _dateFormat && _dateFormat.indexOf('%') >= 0; // compile the number format function from the metadata _stringToNumberFunction = null; var numberFormat:String = getMetadata(ColumnMetadata.NUMBER); if (numberFormat) { try { _stringToNumberFunction = compiler.compileToFunction(numberFormat, null, errorHandler, false, [ColumnMetadata.STRING]); } catch (e:Error) { reportError(e); } } // compile the string format function from the metadata _numberToStringFunction = null; var stringFormat:String = getMetadata(ColumnMetadata.STRING); if (stringFormat) { try { _numberToStringFunction = compiler.compileToFunction(stringFormat, null, errorHandler, false, [ColumnMetadata.NUMBER]); } catch (e:Error) { reportError(e); } } _i = 0; _keys = keys; _dates = dates; _keyToDate = new Dictionary(); _uniqueKeys.length = 0; _reportedError = false; // high priority because not much can be done without data WeaveAPI.StageUtils.startTask(this, _asyncIterate, WeaveAPI.TASK_PRIORITY_HIGH, _asyncComplete); } private function errorHandler(e:*):void { return; // do nothing } private function _asyncComplete():void { _keys = null; _dates = null; triggerCallbacks(); } private function parseDate(string:String):Date { if (_useFlascc) return weave.flascc.date_parse(string, _dateFormat); return StandardLib.parseDate(string, _dateFormat); } private function formatDate(value:Object):String { if (_useFlascc) return weave.flascc.date_format(value as Date || new Date(value), _dateFormat); return StandardLib.formatDate(value, _dateFormat); } private function _asyncIterate(stopTime:int):Number { for (; _i < _keys.length; _i++) { if (getTimer() > stopTime) return _i / _keys.length; // get values for this iteration var key:IQualifiedKey = _keys[_i]; var string:String = _dates[_i]; var date:Date; if (_stringToNumberFunction != null) { var number:Number = _stringToNumberFunction(string); if (_numberToStringFunction != null) { string = _numberToStringFunction(number); if (!string) continue; date = parseDate(string); } else { if (!isFinite(number)) continue; date = new Date(number); } } else { try { if (!string) continue; date = parseDate(string); } catch (e:Error) { if (!_reportedError) { _reportedError = true; var err:String = StandardLib.substitute( 'Warning: Unable to parse this value as a date: "{0}"' + ' (only the first error for this column is reported).' + ' Attribute column: {1}', string, Compiler.stringify(_metadata) ); reportError(err); } continue; } } // keep track of unique keys if (_keyToDate[key] === undefined) { _uniqueKeys.push(key); // save key-to-data mapping _keyToDate[key] = date; } else if (!_reportedError) { _reportedError = true; var fmt:String = 'Warning: Key column values are not unique. Record dropped due to duplicate key ({0}) (only reported for first duplicate). Attribute column: {1}'; var str:String = StandardLib.substitute(fmt, key.localName, Compiler.stringify(_metadata)); if (Capabilities.isDebugger) reportError(str); } } return 1; } /** * @inheritDoc */ public function deriveStringFromNumber(number:Number):String { if (_numberToStringFunction != null) return _numberToStringFunction(number); if (_dateFormat) return formatDate(number); return new Date(number).toString(); } /** * @inheritDoc */ override public function getValueFromKey(key:IQualifiedKey, dataType:Class = null):* { var number:Number; var string:String; var date:Date; if (dataType == Number) { number = _keyToDate[key]; return number; } if (dataType == String) { if (_numberToStringFunction != null) { number = _keyToDate[key]; return _numberToStringFunction(number); } date = _keyToDate[key]; if (!date) return ''; if (_dateFormat) string = formatDate(date); else string = date.toString(); return string; } date = _keyToDate[key]; if (dataType) return date as DataType; return date; } override public function toString():String { return debugId(this) + '{recordCount: '+keys.length+', keyType: "'+getMetadata('keyType')+'", title: "'+getMetadata('title')+'"}'; } private static function convertDateFormat_as_to_c(format:String):String { if (!format || format.indexOf('%') >= 0) return format; return StandardLib.replace.apply(null, [format].concat(dateFormat_replacements_as_to_c)); } private static const dateFormat_replacements_as_to_c:Array = [ 'YYYY','%Y', 'YY','%y', 'MMMM','%B', 'MMM','%b', 'MM','%m', 'M','%-m', 'DD','%d', 'D','%-d', 'E','%u', 'A','%p', 'JJ','%H', 'J','%-H', 'LL','%I', 'L','%-I', 'EEEE','%A', // note this %A is after the A was replaced above 'EEE','%a', 'NN','%M', // note these %M appears after the M's were replaced above 'N','%-M', 'SS','%S' //,'S','%-S' ]; public static function detectDateFormats(dates:*):Array { return weave.flascc.dates_detect(dates, DATE_FORMAT_AUTO_DETECT); } public static const DATE_FORMAT_ADDITIONAL_SUGGESTIONS:Array = [ "%Y" ]; public static const DATE_FORMAT_AUTO_DETECT:Array = [ '%d-%b-%y', '%b-%d-%y', '%d-%b-%Y', '%b-%d-%Y', '%Y-%b-%d', '%d/%b/%y', '%b/%d/%y', '%d/%b/%Y', '%b/%d/%Y', '%Y/%b/%d', '%d.%b.%y', '%b.%d.%y', '%d.%b.%Y', '%b.%d.%Y', '%Y.%b.%d', '%d-%m-%y', '%m-%d-%y', '%d-%m-%Y', '%m-%d-%Y', '%Y-%m-%d', '%d/%m/%y', '%m/%d/%y', '%d/%m/%Y', '%m/%d/%Y', '%Y/%m/%d', '%d.%m.%y', '%m.%d.%y', '%d.%m.%Y', '%m.%d.%Y', '%Y.%m.%d', '%H:%M', '%H:%M:%S', '%a, %d %b %Y %H:%M:%S %z', // RFC_822 // ISO_8601 http://www.thelinuxdaily.com/2014/03/c-function-to-validate-iso-8601-date-formats-using-strptime/ "%Y-%m-%d", "%y-%m-%d", "%Y-%m-%d %T", "%y-%m-%d %T", "%Y-%m-%dT%T", "%y-%m-%dT%T", "%Y-%m-%dT%TZ", "%y-%m-%dT%TZ", "%Y-%m-%d %TZ", "%y-%m-%d %TZ", "%Y%m%dT%TZ", "%y%m%dT%TZ", "%Y%m%d %TZ", "%y%m%d %TZ", "%Y-%b-%d %T", "%Y-%b-%d %H:%M:%S", "%d-%b-%Y %T", "%d-%b-%Y %H:%M:%S", "%d-%b-%Y %H:%M:%S.%Q", /* //https://code.google.com/p/datejs/source/browse/trunk/src/globalization/en-US.js 'M/d/yyyy', 'dddd, MMMM dd, yyyy', "M/d/yyyy", "dddd, MMMM dd, yyyy", "h:mm tt", "h:mm:ss tt", "dddd, MMMM dd, yyyy h:mm:ss tt", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-dd HH:mm:ssZ", "ddd, dd MMM yyyy HH:mm:ss GMT", "MMMM dd", "MMMM, yyyy", //http://www.java2s.com/Code/Android/Date-Type/parseDateforlistofpossibleformats.htm "EEE, dd MMM yyyy HH:mm:ss z", // RFC_822 "EEE, dd MMM yyyy HH:mm zzzz", "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss.SSSzzzz", // Blogger Atom feed has millisecs also "yyyy-MM-dd'T'HH:mm:sszzzz", "yyyy-MM-dd'T'HH:mm:ss z", "yyyy-MM-dd'T'HH:mm:ssz", // ISO_8601 "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HHmmss.SSSz", //http://stackoverflow.com/a/21737848 "M/d/yyyy", "MM/dd/yyyy", "d/M/yyyy", "dd/MM/yyyy", "yyyy/M/d", "yyyy/MM/dd", "M-d-yyyy", "MM-dd-yyyy", "d-M-yyyy", "dd-MM-yyyy", "yyyy-M-d", "yyyy-MM-dd", "M.d.yyyy", "MM.dd.yyyy", "d.M.yyyy", "dd.MM.yyyy", "yyyy.M.d", "yyyy.MM.dd", "M,d,yyyy", "MM,dd,yyyy", "d,M,yyyy", "dd,MM,yyyy", "yyyy,M,d", "yyyy,MM,dd", "M d yyyy", "MM dd yyyy", "d M yyyy", "dd MM yyyy", "yyyy M d", "yyyy MM dd" */ ]; } }
Add a millisecond-resolution date format to the autodetection list.
Add a millisecond-resolution date format to the autodetection list.
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
120b06d59df00a0db58c2d47e610452fbadba5fd
frameworks/as/src/org/apache/flex/html/staticControls/beads/TextItemRendererFactoryForArrayData.as
frameworks/as/src/org/apache/flex/html/staticControls/beads/TextItemRendererFactoryForArrayData.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.staticControls.beads { import flash.display.DisplayObject; import flash.events.Event; import org.apache.flex.core.IBead; import org.apache.flex.core.IItemRendererClassFactory; import org.apache.flex.core.IItemRendererParent; import org.apache.flex.core.ISelectionModel; import org.apache.flex.core.IStrand; public class TextItemRendererFactoryForArrayData implements IBead { public function TextItemRendererFactoryForArrayData() { } private var selectionModel:ISelectionModel; private var _strand:IStrand; public function set strand(value:IStrand):void { _strand = value; selectionModel = value.getBeadByType(ISelectionModel) as ISelectionModel; var listBead:IListBead = value.getBeadByType(IListBead) as IListBead; dataGroup = listBead.dataGroup; selectionModel.addEventListener("dataProviderChange", dataProviderChangeHandler); dataProviderChangeHandler(null); } public var itemRendererFactory:IItemRendererClassFactory; public var dataGroup:IItemRendererParent; private function dataProviderChangeHandler(event:Event):void { var dp:Array = selectionModel.dataProvider as Array; var n:int = dp.length; for (var i:int = 0; i < n; i++) { var tf:ITextItemRenderer = itemRendererFactory.createItemRenderer(dataGroup) as ITextItemRenderer; tf.index = i; dataGroup.addChild(tf as DisplayObject); tf.text = dp[i]; } } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.staticControls.beads { import flash.display.DisplayObject; import flash.events.Event; import org.apache.flex.core.IBead; import org.apache.flex.core.IItemRendererClassFactory; import org.apache.flex.core.IItemRendererParent; import org.apache.flex.core.ISelectionModel; import org.apache.flex.core.IStrand; public class TextItemRendererFactoryForArrayData implements IBead { public function TextItemRendererFactoryForArrayData() { } private var selectionModel:ISelectionModel; private var _strand:IStrand; public function set strand(value:IStrand):void { _strand = value; selectionModel = value.getBeadByType(ISelectionModel) as ISelectionModel; var listBead:IListBead = value.getBeadByType(IListBead) as IListBead; dataGroup = listBead.dataGroup; selectionModel.addEventListener("dataProviderChanged", dataProviderChangeHandler); dataProviderChangeHandler(null); } public var itemRendererFactory:IItemRendererClassFactory; public var dataGroup:IItemRendererParent; private function dataProviderChangeHandler(event:Event):void { var dp:Array = selectionModel.dataProvider as Array; if (!dp) return; var n:int = dp.length; for (var i:int = 0; i < n; i++) { var tf:ITextItemRenderer = itemRendererFactory.createItemRenderer(dataGroup) as ITextItemRenderer; tf.index = i; dataGroup.addChild(tf as DisplayObject); tf.text = dp[i]; } } } }
handle null dataprovider
handle null dataprovider
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
f8ad5a386fa2cd7e839a8124191a4c6b1365248f
src/com/axis/audioclient/AxisTransmit.as
src/com/axis/audioclient/AxisTransmit.as
package com.axis.audioclient { import com.axis.audioclient.IAudioClient; import com.axis.codec.g711; import com.axis.ErrorManager; import com.axis.http.auth; import com.axis.http.request; import com.axis.http.url; import com.axis.Logger; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SampleDataEvent; import flash.events.SecurityErrorEvent; import flash.events.StatusEvent; import flash.external.ExternalInterface; import flash.media.Microphone; import flash.media.SoundCodec; import flash.net.Socket; import flash.utils.ByteArray; public class AxisTransmit implements IAudioClient { private static const EVENT_AUDIO_TRANSMIT_STARTED:String = "audioTransmitStarted"; private static const EVENT_AUDIO_TRANSMIT_STOPPED:String = "audioTransmitStopped"; private var urlParsed:Object = {}; private var conn:Socket = new Socket(); private var authState:String = 'none'; private var authOpts:Object = {}; private var savedUrl:String = null; private var mic:Microphone = Microphone.getMicrophone(); private var _microphoneVolume:Number; private var currentState:String = "stopped"; public function AxisTransmit() { /* Set default microphone volume */ this.microphoneVolume = 50; } private function onMicStatus(event:StatusEvent):void { if (conn.connected) { authState = 'none'; conn.close(); } if ('Microphone.Muted' === event.code) { ErrorManager.dispatchError(816); return; } if (urlParsed.host && urlParsed.port) { conn.connect(urlParsed.host, urlParsed.port); } } public function start(iurl:String = null):void { if (conn.connected) { ErrorManager.dispatchError(817); return; } var currentUrl:String = (iurl) ? iurl : savedUrl; if (!currentUrl) { ErrorManager.dispatchError(818); return; } this.savedUrl = currentUrl; var mic:Microphone = Microphone.getMicrophone(); if (null === mic) { ErrorManager.dispatchError(819); return; } mic.rate = 16; mic.setSilenceLevel(0, -1); mic.addEventListener(StatusEvent.STATUS, onMicStatus); mic.addEventListener(SampleDataEvent.SAMPLE_DATA, onMicSampleData); this.urlParsed = url.parse(currentUrl); conn = new Socket(); conn.addEventListener(Event.CONNECT, onConnected); conn.addEventListener(Event.CLOSE, onClosed); conn.addEventListener(ProgressEvent.SOCKET_DATA, onRequestData); conn.addEventListener(IOErrorEvent.IO_ERROR, onIOError); conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError); if (true === mic.muted) { ErrorManager.dispatchError(816); return; } conn.connect(urlParsed.host, urlParsed.port); } public function stop():void { if (!conn.connected) { ErrorManager.dispatchError(813); this.callAPI(EVENT_AUDIO_TRANSMIT_STOPPED); return; } if (mic) { mic.removeEventListener(StatusEvent.STATUS, onMicStatus); mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, onMicSampleData); } conn.close(); } private function writeAuthorizationHeader():void { var a:String = ''; switch (authState) { case "basic": a = auth.basic(this.urlParsed.user, this.urlParsed.pass) + "\r\n"; break; case "digest": a = auth.digest( this.urlParsed.user, this.urlParsed.pass, "POST", authOpts.digestRealm, urlParsed.urlpath, authOpts.qop, authOpts.nonce, 1 ); break; default: case "none": return; } conn.writeUTFBytes('Authorization: ' + a + "\r\n"); } private function onConnected(event:Event):void { conn.writeUTFBytes("POST " + this.urlParsed.urlpath + " HTTP/1.0\r\n"); conn.writeUTFBytes("Content-Type: audio/axis-mulaw-128\r\n"); conn.writeUTFBytes("Content-Length: 9999999\r\n"); conn.writeUTFBytes("Connection: Keep-Alive\r\n"); conn.writeUTFBytes("Cache-Control: no-cache\r\n"); writeAuthorizationHeader(); conn.writeUTFBytes("\r\n"); } public function onClosed(event:Event):void { if ("playing" === this.currentState) { this.currentState = "stopped"; this.callAPI(EVENT_AUDIO_TRANSMIT_STOPPED); } } private function onMicSampleData(event:SampleDataEvent):void { if (!conn.connected) { return; } if ("stopped" === this.currentState) { this.currentState = "playing"; this.callAPI(EVENT_AUDIO_TRANSMIT_STARTED); } while (event.data.bytesAvailable) { var encoded:uint = g711.linearToMulaw(event.data.readFloat()); conn.writeByte(encoded); } conn.flush(); } private function onRequestData(event:ProgressEvent):void { var data:ByteArray = new ByteArray(); var parsed:* = request.readHeaders(conn, data); if (false === parsed) { return; } if (401 === parsed.code) { /* Unauthorized, change authState and (possibly) try again */ authOpts = parsed.headers['www-authenticate']; var newAuthState:String = auth.nextMethod(authState, authOpts); if (authState === newAuthState) { ErrorManager.dispatchError(parsed.code); return; } Logger.log('AxisTransmit: switching http-authorization from ' + authState + ' to ' + newAuthState); authState = newAuthState; conn.close(); conn.connect(this.urlParsed.host, this.urlParsed.port); return; } } private function onIOError(event:IOErrorEvent):void { ErrorManager.dispatchError(732, [event.text]); } private function onSecurityError(event:SecurityErrorEvent):void { ErrorManager.dispatchError(731, [event.text]); } public function get microphoneVolume():Number { return _microphoneVolume; } public function set microphoneVolume(volume:Number):void { if (null === mic) { ErrorManager.dispatchError(819); return; } _microphoneVolume = volume; mic.gain = volume; if (volume && savedUrl) start(); } public function muteMicrophone():void { if (null === mic) { ErrorManager.dispatchError(819); return; } mic.gain = 0; stop(); } public function unmuteMicrophone():void { if (null === mic) { ErrorManager.dispatchError(819); return; } if (mic.gain !== 0) return; mic.gain = this.microphoneVolume; start(); } private function callAPI(eventName:String, data:Object = null):void { var functionName:String = "LocomoteMap['" + Player.locomoteID + "'].__playerEvent"; if (data) { ExternalInterface.call(functionName, eventName, data); } else { ExternalInterface.call(functionName, eventName); } } } }
package com.axis.audioclient { import com.axis.audioclient.IAudioClient; import com.axis.codec.g711; import com.axis.ErrorManager; import com.axis.http.auth; import com.axis.http.request; import com.axis.http.url; import com.axis.Logger; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SampleDataEvent; import flash.events.SecurityErrorEvent; import flash.events.StatusEvent; import flash.external.ExternalInterface; import flash.media.Microphone; import flash.media.SoundCodec; import flash.net.Socket; import flash.utils.ByteArray; public class AxisTransmit implements IAudioClient { private static const EVENT_AUDIO_TRANSMIT_STARTED:String = 'audioTransmitStarted'; private static const EVENT_AUDIO_TRANSMIT_STOPPED:String = 'audioTransmitStopped'; private var urlParsed:Object = {}; private var conn:Socket = new Socket(); private var authState:String = 'none'; private var authOpts:Object = {}; private var savedUrl:String = null; private var mic:Microphone = Microphone.getMicrophone(); private var _microphoneVolume:Number; private var currentState:String = 'stopped'; public function AxisTransmit() { /* Set default microphone volume */ this.microphoneVolume = 50; } private function onMicStatus(event:StatusEvent):void { if (conn.connected) { authState = 'none'; conn.close(); } if ('Microphone.Muted' === event.code) { ErrorManager.dispatchError(816); return; } if (urlParsed.host && urlParsed.port) { conn.connect(urlParsed.host, urlParsed.port); } } public function start(iurl:String = null):void { if (conn.connected) { ErrorManager.dispatchError(817); return; } var currentUrl:String = (iurl) ? iurl : savedUrl; if (!currentUrl) { ErrorManager.dispatchError(818); return; } this.savedUrl = currentUrl; var mic:Microphone = Microphone.getMicrophone(); if (null === mic) { ErrorManager.dispatchError(819); return; } mic.rate = 16; mic.setSilenceLevel(0, -1); mic.addEventListener(StatusEvent.STATUS, onMicStatus); mic.addEventListener(SampleDataEvent.SAMPLE_DATA, onMicSampleData); this.urlParsed = url.parse(currentUrl); conn = new Socket(); conn.addEventListener(Event.CONNECT, onConnected); conn.addEventListener(Event.CLOSE, onClosed); conn.addEventListener(ProgressEvent.SOCKET_DATA, onRequestData); conn.addEventListener(IOErrorEvent.IO_ERROR, onIOError); conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError); if (true === mic.muted) { ErrorManager.dispatchError(816); return; } conn.connect(urlParsed.host, urlParsed.port); } public function stop():void { if (!conn.connected) { ErrorManager.dispatchError(813); return; } if (mic) { mic.removeEventListener(StatusEvent.STATUS, onMicStatus); mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, onMicSampleData); } this.currentState = 'stopped'; this.callAPI(EVENT_AUDIO_TRANSMIT_STOPPED); conn.close(); } private function writeAuthorizationHeader():void { var a:String = ''; switch (authState) { case "basic": a = auth.basic(this.urlParsed.user, this.urlParsed.pass) + "\r\n"; break; case "digest": a = auth.digest( this.urlParsed.user, this.urlParsed.pass, "POST", authOpts.digestRealm, urlParsed.urlpath, authOpts.qop, authOpts.nonce, 1 ); break; default: case "none": return; } conn.writeUTFBytes('Authorization: ' + a + "\r\n"); } private function onConnected(event:Event):void { conn.writeUTFBytes("POST " + this.urlParsed.urlpath + " HTTP/1.0\r\n"); conn.writeUTFBytes("Content-Type: audio/axis-mulaw-128\r\n"); conn.writeUTFBytes("Content-Length: 9999999\r\n"); conn.writeUTFBytes("Connection: Keep-Alive\r\n"); conn.writeUTFBytes("Cache-Control: no-cache\r\n"); writeAuthorizationHeader(); conn.writeUTFBytes("\r\n"); } public function onClosed(event:Event):void { if ('playing' === this.currentState) { this.currentState = 'stopped'; this.callAPI(EVENT_AUDIO_TRANSMIT_STOPPED); } } private function onMicSampleData(event:SampleDataEvent):void { if (!conn.connected) { return; } if ('stopped' === this.currentState) { this.currentState = 'playing'; this.callAPI(EVENT_AUDIO_TRANSMIT_STARTED); } while (event.data.bytesAvailable) { var encoded:uint = g711.linearToMulaw(event.data.readFloat()); conn.writeByte(encoded); } conn.flush(); } private function onRequestData(event:ProgressEvent):void { var data:ByteArray = new ByteArray(); var parsed:* = request.readHeaders(conn, data); if (false === parsed) { return; } if (401 === parsed.code) { /* Unauthorized, change authState and (possibly) try again */ authOpts = parsed.headers['www-authenticate']; var newAuthState:String = auth.nextMethod(authState, authOpts); if (authState === newAuthState) { ErrorManager.dispatchError(parsed.code); return; } Logger.log('AxisTransmit: switching http-authorization from ' + authState + ' to ' + newAuthState); authState = newAuthState; conn.close(); conn.connect(this.urlParsed.host, this.urlParsed.port); return; } } private function onIOError(event:IOErrorEvent):void { ErrorManager.dispatchError(732, [event.text]); } private function onSecurityError(event:SecurityErrorEvent):void { ErrorManager.dispatchError(731, [event.text]); } public function get microphoneVolume():Number { return _microphoneVolume; } public function set microphoneVolume(volume:Number):void { if (null === mic) { ErrorManager.dispatchError(819); return; } _microphoneVolume = volume; mic.gain = volume; if (volume && savedUrl) start(); } public function muteMicrophone():void { if (null === mic) { ErrorManager.dispatchError(819); return; } mic.gain = 0; stop(); } public function unmuteMicrophone():void { if (null === mic) { ErrorManager.dispatchError(819); return; } if (mic.gain !== 0) return; mic.gain = this.microphoneVolume; start(); } private function callAPI(eventName:String, data:Object = null):void { var functionName:String = "LocomoteMap['" + Player.locomoteID + "'].__playerEvent"; if (data) { ExternalInterface.call(functionName, eventName, data); } else { ExternalInterface.call(functionName, eventName); } } } }
Fix AxisTransmit events
Fix AxisTransmit events
ActionScript
bsd-3-clause
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
92dda9bbab7911029974f6a889726fe3cdc983d1
src/aerys/minko/render/DrawCall.as
src/aerys/minko/render/DrawCall.as
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _center : Vector4 = null; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; private var _bindingsConsumer : DrawCallBindingsConsumer; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (_bindingsConsumer) _bindingsConsumer.enabled = value; } public function get depth() : Number { if (_invalidDepth && _enabled) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( _center, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { _invalidDepth = computeDepth; setProgram(program); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { if (_bindingsConsumer != null) { meshBindings.removeConsumer(_bindingsConsumer); sceneBindings.removeConsumer(_bindingsConsumer); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.slice(); _fsConstants = program._fsConstants.slice(); _fsTextures = program._fsTextures.slice(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; _bindingsConsumer = new DrawCallBindingsConsumer( _bindings, _cpuConstants, _vsConstants, _fsConstants, _fsTextures ); _bindingsConsumer.enabled = _enabled; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; var hasNormals : Boolean = vertexFormat.hasComponent(VertexComponent.NORMAL); if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(!hasNormals); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !hasNormals) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { if (!_vsInputComponents) return ; updateGeometry(geometry); _center = geometry.boundingSphere ? geometry.boundingSphere.center : Vector4.ZERO; _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { meshBindings.addConsumer(_bindingsConsumer); sceneBindings.addConsumer(_bindingsConsumer); if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { _bindingsConsumer.setProperty(name, value); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _center : Vector4 = null; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; private var _bindingsConsumer : DrawCallBindingsConsumer; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (_bindingsConsumer) _bindingsConsumer.enabled = value; } public function get depth() : Number { if (_invalidDepth && _enabled) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( _center, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { _invalidDepth = computeDepth; setProgram(program); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { if (_bindingsConsumer != null) { meshBindings.removeConsumer(_bindingsConsumer); sceneBindings.removeConsumer(_bindingsConsumer); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.slice(); _fsConstants = program._fsConstants.slice(); _fsTextures = program._fsTextures.slice(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; _bindingsConsumer = new DrawCallBindingsConsumer( _bindings, _cpuConstants, _vsConstants, _fsConstants, _fsTextures ); _bindingsConsumer.enabled = _enabled; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; var hasNormals : Boolean = vertexFormat.hasComponent(VertexComponent.NORMAL); if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(!hasNormals); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !hasNormals) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { if (!_vsInputComponents) return ; updateGeometry(geometry); _center = geometry.boundingSphere ? geometry.boundingSphere.center : Vector4.ZERO; _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { meshBindings.addConsumer(_bindingsConsumer); sceneBindings.addConsumer(_bindingsConsumer); if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { _bindingsConsumer.setProperty(name, value); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
remove test of _enabled because it should now be done before calling DrawCall.apply()
remove test of _enabled because it should now be done before calling DrawCall.apply()
ActionScript
mit
aerys/minko-as3
685aaf01c952b9bf66455d18dad26ab85a6ca52f
src/aerys/minko/scene/node/Mesh.as
src/aerys/minko/scene/node/Mesh.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.enum.FrustumCulling; import aerys.minko.type.math.Ray; use namespace minko_scene; /** * Mesh objects are a visible instance of a Geometry rendered using a specific * Effect with specific rendering properties. * * <p> * Those rendering properties are stored in a DataBindings object so they can * be directly used by the shaders in the rendering API. * </p> * * @author Jean-Marc Le Roux * */ public class Mesh extends AbstractSceneNode { public static const DEFAULT_MATERIAL : Material = new BasicMaterial(); private var _geometry : Geometry; private var _properties : DataProvider; private var _material : Material; private var _bindings : DataBindings; private var _visibility : MeshVisibilityController; private var _frame : uint; private var _cloned : Signal; private var _materialChanged : Signal; private var _frameChanged : Signal; private var _geometryChanged : Signal; /** * A DataProvider object already bound to the Mesh bindings. * * <pre> * // set the "diffuseColor" property to 0x0000ffff * mesh.properties.diffuseColor = 0x0000ffff; * * // animate the "diffuseColor" property * mesh.addController( * new AnimationController( * new &lt;ITimeline&gt;[new ColorTimeline( * "dataProvider.diffuseColor", * 5000, * new &lt;uint&gt;[0xffffffff, 0xffffff00, 0xffffffff] * )] * ) * ); * </pre> * * @return * */ public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get material() : Material { return _material; } public function set material(value : Material) : void { if (_material != value) { if (_material) _bindings.removeProvider(_material); var oldMaterial : Material = _material; _material = value; if (value) _bindings.addProvider(value); _materialChanged.execute(this, oldMaterial, value); } } /** * The rendering properties provided to the shaders to customize * how the mesh will appear on screen. * * @return * */ public function get bindings() : DataBindings { return _bindings; } /** * The Geometry of the mesh. * @return * */ public function get geometry() : Geometry { return _geometry; } public function set geometry(value : Geometry) : void { if (_geometry != value) { var oldGeometry : Geometry = _geometry; if (oldGeometry) oldGeometry.changed.remove(geometryChangedHandler); _geometry = value; if (value) _geometry.changed.add(geometryChangedHandler); _geometryChanged.execute(this, oldGeometry, value); } } /** * Whether the mesh in inside the camera frustum or not. * @return * */ public function get insideFrustum() : Boolean { return _visibility.insideFrustum; } override public function get computedVisibility() : Boolean { return scene ? _visibility.computedVisibility : super.computedVisibility; } public function get frustumCulling() : uint { return _visibility.frustumCulling; } public function set frustumCulling(value : uint) : void { _visibility.frustumCulling = value; } public function get cloned() : Signal { return _cloned; } public function get materialChanged() : Signal { return _materialChanged; } public function get frameChanged() : Signal { return _frameChanged; } public function get geometryChanged() : Signal { return _geometryChanged; } public function get frame() : uint { return _frame; } public function set frame(value : uint) : void { if (_frame != value) { var oldFrame : uint = _frame; _frame = value; _frameChanged.execute(this, oldFrame, value); } } public function Mesh(geometry : Geometry = null, material : Material = null, name : String = null) { super(); initialize(geometry, material, name); } private function initialize(geometry : Geometry, material : Material, name : String) : void { if (name) this.name = name; _cloned = new Signal('Mesh.clones'); _materialChanged = new Signal('Mesh.materialChanged'); _frameChanged = new Signal('Mesh.frameChanged'); _geometryChanged = new Signal('Mesh.geometryChanged'); _bindings = new DataBindings(this); this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE); this.geometry = geometry; this.material = material || DEFAULT_MATERIAL; _visibility = new MeshVisibilityController(); _visibility.frustumCulling = FrustumCulling.ENABLED; addController(_visibility); } public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number { return _geometry.boundingBox.testRay( ray, worldToLocal, maxDistance ); } // override protected function visibilityChangedHandler(node : AbstractSceneNode, // visibility : Boolean) : void // { // // nothing // } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Mesh = new Mesh(); clone.name = name; clone.geometry = _geometry; clone.properties = DataProvider(_properties.clone()); clone._bindings.copySharedProvidersFrom(_bindings); clone.transform.copyFrom(transform); clone.material = _material; this.cloned.execute(this, clone); return clone; } private function geometryChangedHandler(geometry : Geometry) : void { _geometryChanged.execute(this, _geometry, _geometry); } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.enum.FrustumCulling; import aerys.minko.type.math.Ray; use namespace minko_scene; /** * Mesh objects are a visible instance of a Geometry rendered using a specific * Effect with specific rendering properties. * * <p> * Those rendering properties are stored in a DataBindings object so they can * be directly used by the shaders in the rendering API. * </p> * * @author Jean-Marc Le Roux * */ public class Mesh extends AbstractSceneNode { public static const DEFAULT_MATERIAL : Material = new BasicMaterial(); private var _geometry : Geometry; private var _properties : DataProvider; private var _material : Material; private var _bindings : DataBindings; private var _visibility : MeshVisibilityController; private var _frame : uint; private var _cloned : Signal; private var _materialChanged : Signal; private var _frameChanged : Signal; private var _geometryChanged : Signal; /** * A DataProvider object already bound to the Mesh bindings. * * <pre> * // set the "diffuseColor" property to 0x0000ffff * mesh.properties.diffuseColor = 0x0000ffff; * * // animate the "diffuseColor" property * mesh.addController( * new AnimationController( * new &lt;ITimeline&gt;[new ColorTimeline( * "dataProvider.diffuseColor", * 5000, * new &lt;uint&gt;[0xffffffff, 0xffffff00, 0xffffffff] * )] * ) * ); * </pre> * * @return * */ public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get material() : Material { return _material; } public function set material(value : Material) : void { if (_material != value) { if (_material) _bindings.removeProvider(_material); var oldMaterial : Material = _material; _material = value; if (value) _bindings.addProvider(value); _materialChanged.execute(this, oldMaterial, value); } } /** * The rendering properties provided to the shaders to customize * how the mesh will appear on screen. * * @return * */ public function get bindings() : DataBindings { return _bindings; } /** * The Geometry of the mesh. * @return * */ public function get geometry() : Geometry { return _geometry; } public function set geometry(value : Geometry) : void { if (_geometry != value) { var oldGeometry : Geometry = _geometry; if (oldGeometry) oldGeometry.changed.remove(geometryChangedHandler); _geometry = value; if (value) _geometry.changed.add(geometryChangedHandler); _geometryChanged.execute(this, oldGeometry, value); } } /** * Whether the mesh in inside the camera frustum or not. * @return * */ public function get insideFrustum() : Boolean { return _visibility.insideFrustum; } override public function get computedVisibility() : Boolean { return scene ? _visibility.computedVisibility : super.computedVisibility; } public function get frustumCulling() : uint { return _visibility.frustumCulling; } public function set frustumCulling(value : uint) : void { _visibility.frustumCulling = value; } public function get cloned() : Signal { return _cloned; } public function get materialChanged() : Signal { return _materialChanged; } public function get frameChanged() : Signal { return _frameChanged; } public function get geometryChanged() : Signal { return _geometryChanged; } public function get frame() : uint { return _frame; } public function set frame(value : uint) : void { if (_frame != value) { var oldFrame : uint = _frame; _frame = value; _frameChanged.execute(this, oldFrame, value); } } public function Mesh(geometry : Geometry = null, material : Material = null, name : String = null) { super(); initialize(geometry, material, name); } private function initialize(geometry : Geometry, material : Material, name : String) : void { if (name) this.name = name; _cloned = new Signal('Mesh.cloned'); _materialChanged = new Signal('Mesh.materialChanged'); _frameChanged = new Signal('Mesh.frameChanged'); _geometryChanged = new Signal('Mesh.geometryChanged'); _bindings = new DataBindings(this); this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE); this.geometry = geometry; this.material = material || DEFAULT_MATERIAL; _visibility = new MeshVisibilityController(); _visibility.frustumCulling = FrustumCulling.ENABLED; addController(_visibility); } public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number { return _geometry.boundingBox.testRay( ray, worldToLocal, maxDistance ); } // override protected function visibilityChangedHandler(node : AbstractSceneNode, // visibility : Boolean) : void // { // // nothing // } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Mesh = new Mesh(); clone.name = name; clone.geometry = _geometry; clone.properties = DataProvider(_properties.clone()); clone._bindings.copySharedProvidersFrom(_bindings); clone.transform.copyFrom(transform); clone.material = _material; this.cloned.execute(this, clone); return clone; } private function geometryChangedHandler(geometry : Geometry) : void { _geometryChanged.execute(this, _geometry, _geometry); } } }
fix typo
fix typo
ActionScript
mit
aerys/minko-as3
8694da7bf41d73e20e865b22eba81d95c5e3020c
as3/com/netease/protobuf/SimpleWebRPC.as
as3/com/netease/protobuf/SimpleWebRPC.as
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.net.*; import flash.utils.*; import flash.events.*; public final class SimpleWebRPC { private var urlPrefix:String public function SimpleWebRPC(urlPrefix:String) { this.urlPrefix = urlPrefix; } private static const REF:Dictionary = new Dictionary(); public function send(qualifiedMethodName:String, input:IExternalizable, callback:Function, outputType:Class):void { const loader:URLLoader = new URLLoader REF[loader] = true; loader.dataFormat = URLLoaderDataFormat.BINARY loader.addEventListener(Event.COMPLETE, function(event:Event):void { delete REF[loader] const output:IExternalizable = new outputType output.readExternal(loader.data) callback(output) }) function errorEventHandler(event:Event):void { delete REF[loader] callback(event) } loader.addEventListener(IOErrorEvent.IO_ERROR, errorEventHandler) loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, errorEventHandler) const request:URLRequest = new URLRequest( urlPrefix + qualifiedMethodName) request.method = URLRequestMethod.POST const requestContent:ByteArray = new ByteArray input.writeExternal(requestContent) request.data = requestContent request.contentType = "application/x-protobuf" loader.load(request) } } }
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.net.*; import flash.utils.*; import flash.events.*; public final class SimpleWebRPC { private var urlPrefix:String public function SimpleWebRPC(urlPrefix:String) { this.urlPrefix = urlPrefix; } private static const REF:Dictionary = new Dictionary(); public function send(qualifiedMethodName:String, input:IExternalizable, rpcResult:Function, outputType:Class):void { const loader:URLLoader = new URLLoader REF[loader] = true; loader.dataFormat = URLLoaderDataFormat.BINARY loader.addEventListener(Event.COMPLETE, function(event:Event):void { delete REF[loader] const output:IExternalizable = new outputType output.readExternal(loader.data) rpcResult(output) }) function errorEventHandler(event:Event):void { delete REF[loader] rpcResult(event) } loader.addEventListener(IOErrorEvent.IO_ERROR, errorEventHandler) loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, errorEventHandler) const request:URLRequest = new URLRequest( urlPrefix + qualifiedMethodName) request.method = URLRequestMethod.POST const requestContent:ByteArray = new ByteArray input.writeExternal(requestContent) request.data = requestContent request.contentType = "application/x-protobuf" loader.load(request) } } }
把另一处 callback 也改成其他名字
把另一处 callback 也改成其他名字
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3
0b26fc9a08a8e616bb346203ca7ee288fba19836
tests/GAv4/com/google/analytics/core/BrowserInfoTest.as
tests/GAv4/com/google/analytics/core/BrowserInfoTest.as
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package com.google.analytics.core { import library.ASTUce.framework.TestCase; import com.google.analytics.utils.Environment; import com.google.analytics.utils.FakeEnvironment; import com.google.analytics.utils.Variables; import com.google.analytics.utils.Version; import com.google.analytics.v4.Configuration; public class BrowserInfoTest extends TestCase { private var _config:Configuration; private var _browserInfo0:BrowserInfo; private var _env0:Environment; public function BrowserInfoTest(name:String="") { super(name); } public function testHitId():void { assertEquals(1,1); } public function setUp():void { _config = new Configuration(); _env0 = new FakeEnvironment("",null,"","","","","","",new Version(9,0,115,0),"en-GB","UTF-8","","","",null,800,600,"24"); _browserInfo0 = new BrowserInfo( _config, _env0 ); } public function testFlashVersion():void { assertEquals( "9.0 r115", _browserInfo0.utmfl ); } public function testScreenInfo():void { assertEquals( "800x600", _browserInfo0.utmsr ); assertEquals( "24-bit", _browserInfo0.utmsc ); } public function testLangInfo():void { assertEquals( "en-gb", _browserInfo0.utmul ); assertEquals( "UTF-8", _browserInfo0.utmcs ); } public function testToVariables():void { var vars:Variables = _browserInfo0.toVariables(); assertEquals( "UTF-8", vars.utmcs ); assertEquals( "800x600", vars.utmsr ); assertEquals( "24-bit", vars.utmsc ); assertEquals( "en-gb", vars.utmul ); assertEquals( "0", vars.utmje ); assertEquals( "9.0 r115", vars.utmfl ); } public function testToURLString():void { var vars:Variables = _browserInfo0.toVariables(); var varsA:Variables = new Variables(); varsA.URIencode = true; varsA.utmcs = vars.utmcs; assertEquals( "utmcs=UTF-8", varsA.toString() ); var varsB:Variables = new Variables(); varsB.URIencode = true; varsB.utmsr = vars.utmsr; assertEquals( "utmsr=800x600", varsB.toString() ); var varsC:Variables = new Variables(); varsC.URIencode = true; varsC.utmsc = vars.utmsc; assertEquals( "utmsc=24-bit", varsC.toString() ); var varsD:Variables = new Variables(); varsD.URIencode = true; varsD.utmul = vars.utmul; assertEquals( "utmul=en-gb", varsD.toString() ); var varsE:Variables = new Variables(); varsE.URIencode = true; varsE.utmje = vars.utmje; assertEquals( "utmje=0", varsE.toString() ); var varsF:Variables = new Variables(); varsF.URIencode = true; varsF.utmfl = vars.utmfl; assertEquals( "utmfl=9.0%20r115", varsF.toString() ); } } }
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package com.google.analytics.core { import com.google.analytics.utils.Environment; import com.google.analytics.utils.FakeEnvironment; import com.google.analytics.utils.Variables; import com.google.analytics.v4.Configuration; import core.version; import library.ASTUce.framework.TestCase; public class BrowserInfoTest extends TestCase { private var _config:Configuration; private var _browserInfo0:BrowserInfo; private var _env0:Environment; public function BrowserInfoTest(name:String="") { super(name); } public function testHitId():void { assertEquals(1,1); } public function setUp():void { _config = new Configuration(); _env0 = new FakeEnvironment("",null,"","","","","","",new version(9,0,115,0),"en-GB","UTF-8","","","",null,800,600,"24"); _browserInfo0 = new BrowserInfo( _config, _env0 ); } public function testFlashVersion():void { assertEquals( "9.0 r115", _browserInfo0.utmfl ); } public function testScreenInfo():void { assertEquals( "800x600", _browserInfo0.utmsr ); assertEquals( "24-bit", _browserInfo0.utmsc ); } public function testLangInfo():void { assertEquals( "en-gb", _browserInfo0.utmul ); assertEquals( "UTF-8", _browserInfo0.utmcs ); } public function testToVariables():void { var vars:Variables = _browserInfo0.toVariables(); assertEquals( "UTF-8", vars.utmcs ); assertEquals( "800x600", vars.utmsr ); assertEquals( "24-bit", vars.utmsc ); assertEquals( "en-gb", vars.utmul ); assertEquals( "0", vars.utmje ); assertEquals( "9.0 r115", vars.utmfl ); } public function testToURLString():void { var vars:Variables = _browserInfo0.toVariables(); var varsA:Variables = new Variables(); varsA.URIencode = true; varsA.utmcs = vars.utmcs; assertEquals( "utmcs=UTF-8", varsA.toString() ); var varsB:Variables = new Variables(); varsB.URIencode = true; varsB.utmsr = vars.utmsr; assertEquals( "utmsr=800x600", varsB.toString() ); var varsC:Variables = new Variables(); varsC.URIencode = true; varsC.utmsc = vars.utmsc; assertEquals( "utmsc=24-bit", varsC.toString() ); var varsD:Variables = new Variables(); varsD.URIencode = true; varsD.utmul = vars.utmul; assertEquals( "utmul=en-gb", varsD.toString() ); var varsE:Variables = new Variables(); varsE.URIencode = true; varsE.utmje = vars.utmje; assertEquals( "utmje=0", varsE.toString() ); var varsF:Variables = new Variables(); varsF.URIencode = true; varsF.utmfl = vars.utmfl; assertEquals( "utmfl=9.0%20r115", varsF.toString() ); } } }
replace class Version by core.version
replace class Version by core.version
ActionScript
apache-2.0
nsdevaraj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash,minimedj/gaforflash
3dd4a9e39660a39acd1b6e904834078ea6bb0475
samples/plain_as/Sample.as
samples/plain_as/Sample.as
package { import flash.display.*; import flash.events.*; import flash.text.*; import flash.ui.Mouse; import flash.notifications.NotificationStyle; import com.juankpro.ane.localnotif.*; [SWF(backgroundColor="#FFFFFF", width="320", height="480", frameRate="30")] public class Sample extends Sprite { private var notificationManager:NotificationManager; private var postButton:SimpleButton; private var cancelButton:SimpleButton; private var codeButton:SimpleButton; private var badgeButton:SimpleButton; private var notificationTF:TextField; private var contentsScaleFactor:int = 2; private static const NOTIFICATION_CODE:String = "NOTIFICATION_CODE_001"; public function Sample() { addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler); } private function addedToStageHandler(event:Event):void { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; stage.quality = StageQuality.BEST; stage.addEventListener(Event.RESIZE, resizeHandler); } private var initialized:Boolean = false; private function resizeHandler(event:Event):void { initApp(); printMessage("Resized"); } private function initApp():void { if (initialized) return; initialized = true; if (NotificationManager.isSupported) { notificationManager = new NotificationManager(); if (NotificationManager.needsSubsciption) { var options:LocalNotifierSubscribeOptions = new LocalNotifierSubscribeOptions(); options.notificationStyles = NotificationManager.supportedNotificationStyles; notificationManager.addEventListener(NotificationEvent.SETTINGS_SUBSCRIBED, settingsSubscribedHandler); notificationManager.subscribe(options); } } initUI(); registerEvents(); } private function settingsSubscribedHandler(event:NotificationEvent):void { printMessage("Settings: " + event.subscribeOptions.notificationStyles.join("\n")); registerEvents(); } private function initUI():void { var top1:int = 20 * contentsScaleFactor; var top2:int = 80 * contentsScaleFactor; postButton = createButton("Post", 0, top1); cancelButton = createButton("Cancel", stage.stageWidth - 100 * contentsScaleFactor, top1); codeButton = createButton("By Code", 0, top2); badgeButton = createButton("Clear Badge", stage.stageWidth - 100 * contentsScaleFactor, top2); addChild(postButton); addChild(cancelButton); addChild(codeButton); addChild(badgeButton); notificationTF = createTextField(0, int(stage.stageHeight / 2), stage.stageWidth - 1, int(stage.stageHeight / 2) - 1); notificationTF.border = true; addChild(notificationTF); } private function printMessage(message:String, title:String = null):void { notificationTF.text += "-----\n" + (title? title + "\n" : "") + message + "\n"; notificationTF.scrollV = notificationTF.maxScrollV; } private function registerEvents():void { notificationManager.addEventListener(NotificationEvent.NOTIFICATION_ACTION, notificationActionHandler); postButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); cancelButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); codeButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); badgeButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); } private function buttonClickHandler(event:MouseEvent):void { switch(event.target) { case postButton: var notification:Notification = new Notification(); notification.title = "Sample Title"; notification.body = "Body sample"; notification.actionLabel = "Rumble"; notification.soundName = "fx05.caf"; notification.fireDate = new Date((new Date()).time + (15 * 1000)); notification.numberAnnotation = 3; notification.actionData = {sampleData:"Hello World!"}; notificationManager.notifyUser(NOTIFICATION_CODE, notification); printNotification('Posted Message', notification); break; case cancelButton: notificationManager.cancelAll(); printMessage("Cancelled all notifications"); break; case codeButton: notificationManager.cancel(NOTIFICATION_CODE); printMessage("Cancelled notification with code " + NOTIFICATION_CODE); break; case badgeButton: notificationManager.applicationBadgeNumber = 0; printMessage("Reset badge number to zero"); break; } } private function printNotification(title:String, notification:Notification):void { printMessage( '\nTitle: ' + notification.title + '\nBody: ' + notification.body + '\nAction: ' + notification.actionLabel + '\nCode: ' + NOTIFICATION_CODE + '\nData: {' + notification.actionData.sampleData + '}' + '\nAnnotation: ' + notification.numberAnnotation + '\nfireDate: ' + notification.fireDate + '\nsoundName: ' + notification.soundName, title); } private function notificationActionHandler(event:NotificationEvent):void { printMessage("Code: " + event.notificationCode + "\nSample Data: {" + event.actionData.sampleData + "}", "Received notification"); } private function createTextField(x:int, y:int, width:int, height:int):TextField { var textField:TextField = new TextField(); textField.width = width; textField.height = height; textField.x = x; textField.y = y; var tf:TextFormat = textField.getTextFormat(); tf.font = '_sans'; tf.size = 14 * contentsScaleFactor; textField.defaultTextFormat = tf; textField.setTextFormat(tf); return textField; } private function createButton(label:String, x:int, y:int):SimpleButton { var button:SimpleButton = new SimpleButton(); var w:int = 100 * contentsScaleFactor; var h:int = 30 * contentsScaleFactor; var buttonSprite:Sprite = new Sprite(); buttonSprite.graphics.lineStyle(1, 0x555555); buttonSprite.graphics.beginFill(0xff000, 1); buttonSprite.graphics.drawRect(0, 0, w, h); buttonSprite.graphics.endFill(); var buttonLabel:TextField = createTextField(0, 8 * contentsScaleFactor, w, h); var tf:TextFormat = buttonLabel.getTextFormat(); tf.align = TextFormatAlign.CENTER; tf.font = "Helvetica"; tf.size = 14 * contentsScaleFactor; buttonLabel.defaultTextFormat = tf; buttonLabel.setTextFormat(tf); buttonLabel.text = label; buttonSprite.addChild(buttonLabel); button.x = x; button.y = y; button.overState = button.downState = button.upState = button.hitTestState = buttonSprite; return button; } } }
package { import flash.display.*; import flash.events.*; import flash.text.*; import flash.ui.Mouse; import flash.notifications.NotificationStyle; import com.juankpro.ane.localnotif.*; [SWF(backgroundColor="#FFFFFF", width="320", height="480", frameRate="30")] public class Sample extends Sprite { private var notificationManager:NotificationManager; private var postButton:SimpleButton; private var cancelButton:SimpleButton; private var codeButton:SimpleButton; private var badgeButton:SimpleButton; private var clearButton:SimpleButton; private var notificationTF:TextField; private var contentsScaleFactor:int = 2; private static const NOTIFICATION_CODE:String = "NOTIFICATION_CODE_001"; public function Sample() { addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler); } private function addedToStageHandler(event:Event):void { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; stage.quality = StageQuality.BEST; stage.addEventListener(Event.RESIZE, resizeHandler); } private var initialized:Boolean = false; private function resizeHandler(event:Event):void { initApp(); printMessage("Resized"); } private function initApp():void { if (initialized) return; initialized = true; if (NotificationManager.isSupported) { notificationManager = new NotificationManager(); if (NotificationManager.needsSubsciption) { var options:LocalNotifierSubscribeOptions = new LocalNotifierSubscribeOptions(); options.notificationStyles = NotificationManager.supportedNotificationStyles; notificationManager.addEventListener(NotificationEvent.SETTINGS_SUBSCRIBED, settingsSubscribedHandler); notificationManager.subscribe(options); } } initUI(); registerEvents(); } private function settingsSubscribedHandler(event:NotificationEvent):void { printMessage("Settings: " + event.subscribeOptions.notificationStyles.join("\n")); registerEvents(); } private function initUI():void { var top1:int = 20 * contentsScaleFactor; var top2:int = 80 * contentsScaleFactor; postButton = createButton("Post", 0, top1); cancelButton = createButton("Cancel", stage.stageWidth - 100 * contentsScaleFactor, top1); codeButton = createButton("By Code", 0, top2); badgeButton = createButton("Clear Badge", stage.stageWidth - 100 * contentsScaleFactor, top2); clearButton = createButton("Clear", 0, int(stage.stageHeight / 2) - 30 * contentsScaleFactor); addChild(postButton); addChild(cancelButton); addChild(codeButton); addChild(badgeButton); addChild(clearButton); notificationTF = createTextField(0, int(stage.stageHeight / 2), stage.stageWidth - 1, int(stage.stageHeight / 2) - 1); notificationTF.border = true; addChild(notificationTF); } private function printMessage(message:String, title:String = null):void { notificationTF.text += "-----\n" + (title? title + "\n" : "") + message + "\n"; notificationTF.scrollV = notificationTF.maxScrollV; } private function clearMessages():void { notificationTF.text = ""; } private function registerEvents():void { notificationManager.addEventListener(NotificationEvent.NOTIFICATION_ACTION, notificationActionHandler); postButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); cancelButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); codeButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); badgeButton.addEventListener(MouseEvent.CLICK, buttonClickHandler); } private function buttonClickHandler(event:MouseEvent):void { switch(event.target) { case postButton: var notification:Notification = new Notification(); notification.title = "Sample Title"; notification.body = "Body sample"; notification.actionLabel = "Rumble"; notification.soundName = "fx05.caf"; notification.fireDate = new Date((new Date()).time + (15 * 1000)); notification.numberAnnotation = 3; notification.actionData = {sampleData:"Hello World!"}; notificationManager.notifyUser(NOTIFICATION_CODE, notification); printNotification('Posted Message', notification); break; case cancelButton: notificationManager.cancelAll(); printMessage("Cancelled all notifications"); break; case codeButton: notificationManager.cancel(NOTIFICATION_CODE); printMessage("Cancelled notification with code " + NOTIFICATION_CODE); break; case badgeButton: notificationManager.applicationBadgeNumber = 0; printMessage("Reset badge number to zero"); break; case clearButton: clearMessages(); break; } } private function printNotification(title:String, notification:Notification):void { printMessage( '\nTitle: ' + notification.title + '\nBody: ' + notification.body + '\nAction: ' + notification.actionLabel + '\nCode: ' + NOTIFICATION_CODE + '\nData: {' + notification.actionData.sampleData + '}' + '\nAnnotation: ' + notification.numberAnnotation + '\nfireDate: ' + notification.fireDate + '\nsoundName: ' + notification.soundName, title); } private function notificationActionHandler(event:NotificationEvent):void { printMessage("Code: " + event.notificationCode + "\nSample Data: {" + event.actionData.sampleData + "}", "Received notification"); } private function createTextField(x:int, y:int, width:int, height:int):TextField { var textField:TextField = new TextField(); textField.width = width; textField.height = height; textField.x = x; textField.y = y; var tf:TextFormat = textField.getTextFormat(); tf.font = '_sans'; tf.size = 14 * contentsScaleFactor; textField.defaultTextFormat = tf; textField.setTextFormat(tf); return textField; } private function createButton(label:String, x:int, y:int):SimpleButton { var button:SimpleButton = new SimpleButton(); var w:int = 100 * contentsScaleFactor; var h:int = 30 * contentsScaleFactor; var buttonSprite:Sprite = new Sprite(); buttonSprite.graphics.lineStyle(1, 0x555555); buttonSprite.graphics.beginFill(0xff000, 1); buttonSprite.graphics.drawRect(0, 0, w, h); buttonSprite.graphics.endFill(); var buttonLabel:TextField = createTextField(0, 8 * contentsScaleFactor, w, h); var tf:TextFormat = buttonLabel.getTextFormat(); tf.align = TextFormatAlign.CENTER; tf.font = "Helvetica"; tf.size = 14 * contentsScaleFactor; buttonLabel.defaultTextFormat = tf; buttonLabel.setTextFormat(tf); buttonLabel.text = label; buttonSprite.addChild(buttonLabel); button.x = x; button.y = y; button.overState = button.downState = button.upState = button.hitTestState = buttonSprite; return button; } } }
Add clear button to sample
Add clear button to sample
ActionScript
mit
juank-pa/JKLocalNotifications-ANE,juank-pa/JKLocalNotifications-ANE,juank-pa/JKLocalNotifications-ANE
8768ba419ab4373d922e457c6b4362afa018726c
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.CloneableClass; import dolly.data.CloneableSubclass; import dolly.data.ClassLevelCopyableCloneable; import dolly.data.PropertyLevelCloneable; import dolly.data.PropertyLevelCopyableCloneable; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNotNull; use namespace dolly_internal; public class ClonerTest { private var cloneableClass:CloneableClass; private var cloneableClassType:Type; private var cloneableSubclass:CloneableSubclass; private var cloneableSubclassType:Type; private var classLevelCopyableCloneable:ClassLevelCopyableCloneable; private var classLevelCopyableCloneableType:Type; private var propertyLevelCloneable:PropertyLevelCloneable; private var propertyLevelCloneableType:Type; private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable; private var propertyLevelCopyableCloneableType:Type; [Before] public function before():void { cloneableClass = new CloneableClass(); cloneableClass.property1 = "value 1"; cloneableClass.property2 = "value 2"; cloneableClass.property3 = "value 3"; cloneableClass.writableField = "value 4"; cloneableClassType = Type.forInstance(cloneableClass); classLevelCopyableCloneable = new ClassLevelCopyableCloneable(); classLevelCopyableCloneable.property1 = "value 1"; classLevelCopyableCloneable.property2 = "value 2"; classLevelCopyableCloneable.property3 = "value 3"; classLevelCopyableCloneable.writableField = "value 4"; classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable); cloneableSubclass = new CloneableSubclass(); cloneableSubclass.property1 = "value 1"; cloneableSubclass.property2 = "value 2"; cloneableSubclass.property3 = "value 3"; cloneableSubclass.property4 = "value 4"; cloneableSubclass.property5 = "value 5"; cloneableSubclass.writableField = "value 6"; cloneableSubclass.writableField2 = "value 7"; cloneableSubclassType = Type.forInstance(cloneableSubclass); propertyLevelCloneable = new PropertyLevelCloneable(); propertyLevelCloneable.property1 = "value 1"; propertyLevelCloneable.property2 = "value 2"; propertyLevelCloneable.property3 = "value 3"; propertyLevelCloneable.writableField = "value 4"; propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable); propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable(); propertyLevelCopyableCloneable.property1 = "value 1"; propertyLevelCopyableCloneable.property2 = "value 2"; propertyLevelCopyableCloneable.property3 = "value 3"; propertyLevelCopyableCloneable.writableField = "value 4"; propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable); } [After] public function after():void { cloneableClass = null; cloneableClassType = null; classLevelCopyableCloneable = null; classLevelCopyableCloneableType = null; cloneableSubclass = null; cloneableSubclassType = null; propertyLevelCloneable = null; propertyLevelCloneableType = null; propertyLevelCopyableCloneable = null; propertyLevelCopyableCloneableType = null; } [Test] public function testFindAllWritableFieldsForTypeClassLevelCloneable():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(cloneableClassType); assertNotNull(cloneableFields); assertEquals(4, cloneableFields.length); } [Test] public function testFindAllWritableFieldsForTypeClassLevelCloneableSubclass():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(cloneableSubclassType); assertNotNull(cloneableFields); assertEquals(7, cloneableFields.length); } [Test] public function testFindAllWritableFieldsForTypeClassLevelCopyableCloneable():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(classLevelCopyableCloneableType); assertNotNull(cloneableFields); assertEquals(4, cloneableFields.length); } [Test] public function testFindAllWritableFieldsForTypePropertyLevelCloneable():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(propertyLevelCloneableType); assertNotNull(cloneableFields); assertEquals(3, cloneableFields.length); } [Test] public function testFindAllWritableFieldsForTypePropertyLevelCopyableCloneable():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(propertyLevelCopyableCloneableType); assertNotNull(cloneableFields); assertEquals(4, cloneableFields.length); } [Test] public function testCloneClassLevelCloneable():void { const clone:CloneableClass = Cloner.clone(cloneableClass); assertNotNull(clone); assertNotNull(clone.property1); assertEquals(clone.property1, cloneableClass.property1); assertNotNull(clone.property2); assertEquals(clone.property2, cloneableClass.property2); assertNotNull(clone.property3); assertEquals(clone.property3, cloneableClass.property3); assertNotNull(clone.writableField); assertEquals(clone.writableField, cloneableClass.writableField); } [Test] public function testCloneClassLevelCloneableSubclass():void { const clone:CloneableSubclass = Cloner.clone(cloneableSubclass); assertNotNull(clone); assertNotNull(clone.property1); assertEquals(clone.property1, cloneableSubclass.property1); assertNotNull(clone.property2); assertEquals(clone.property2, cloneableSubclass.property2); assertNotNull(clone.property3); assertEquals(clone.property3, cloneableSubclass.property3); assertNotNull(clone.property4); assertEquals(clone.property4, cloneableSubclass.property4); assertNotNull(clone.property5); assertEquals(clone.property5, cloneableSubclass.property5); assertNotNull(clone.writableField); assertEquals(clone.writableField, cloneableSubclass.writableField); assertNotNull(clone.writableField2); assertEquals(clone.writableField2, cloneableSubclass.writableField2); } [Test] public function testCloneClassLevelCopyableCloneable():void { const clone:ClassLevelCopyableCloneable = Cloner.clone(classLevelCopyableCloneable); assertNotNull(clone); assertNotNull(clone.property1); assertEquals(clone.property1, cloneableClass.property1); assertNotNull(clone.property2); assertEquals(clone.property2, cloneableClass.property2); assertNotNull(clone.property3); assertEquals(clone.property3, cloneableClass.property3); assertNotNull(clone.writableField); assertEquals(clone.writableField, cloneableClass.writableField); } /** * <code>Cloner.clone()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function testClonePropertyLevelCloneable():void { Cloner.clone(propertyLevelCloneable); } /** * <code>Cloner.clone()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCopyableCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function testClonePropertyLevelCopyableCloneable():void { Cloner.clone(propertyLevelCopyableCloneable); } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.CloneableClass; import dolly.data.CloneableSubclass; import dolly.data.ClassLevelCopyableCloneable; import dolly.data.PropertyLevelCloneable; import dolly.data.PropertyLevelCopyableCloneable; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNotNull; use namespace dolly_internal; public class ClonerTest { private var cloneableClass:CloneableClass; private var cloneableClassType:Type; private var cloneableSubclass:CloneableSubclass; private var cloneableSubclassType:Type; private var classLevelCopyableCloneable:ClassLevelCopyableCloneable; private var classLevelCopyableCloneableType:Type; private var propertyLevelCloneable:PropertyLevelCloneable; private var propertyLevelCloneableType:Type; private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable; private var propertyLevelCopyableCloneableType:Type; [Before] public function before():void { cloneableClass = new CloneableClass(); cloneableClass.property1 = "value 1"; cloneableClass.property2 = "value 2"; cloneableClass.property3 = "value 3"; cloneableClass.writableField = "value 4"; cloneableClassType = Type.forInstance(cloneableClass); classLevelCopyableCloneable = new ClassLevelCopyableCloneable(); classLevelCopyableCloneable.property1 = "value 1"; classLevelCopyableCloneable.property2 = "value 2"; classLevelCopyableCloneable.property3 = "value 3"; classLevelCopyableCloneable.writableField = "value 4"; classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable); cloneableSubclass = new CloneableSubclass(); cloneableSubclass.property1 = "value 1"; cloneableSubclass.property2 = "value 2"; cloneableSubclass.property3 = "value 3"; cloneableSubclass.property4 = "value 4"; cloneableSubclass.property5 = "value 5"; cloneableSubclass.writableField = "value 6"; cloneableSubclass.writableField2 = "value 7"; cloneableSubclassType = Type.forInstance(cloneableSubclass); propertyLevelCloneable = new PropertyLevelCloneable(); propertyLevelCloneable.property1 = "value 1"; propertyLevelCloneable.property2 = "value 2"; propertyLevelCloneable.property3 = "value 3"; propertyLevelCloneable.writableField = "value 4"; propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable); propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable(); propertyLevelCopyableCloneable.property1 = "value 1"; propertyLevelCopyableCloneable.property2 = "value 2"; propertyLevelCopyableCloneable.property3 = "value 3"; propertyLevelCopyableCloneable.writableField = "value 4"; propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable); } [After] public function after():void { cloneableClass = null; cloneableClassType = null; classLevelCopyableCloneable = null; classLevelCopyableCloneableType = null; cloneableSubclass = null; cloneableSubclassType = null; propertyLevelCloneable = null; propertyLevelCloneableType = null; propertyLevelCopyableCloneable = null; propertyLevelCopyableCloneableType = null; } [Test] public function testFindAllWritableFieldsForTypeCloneableClass():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(cloneableClassType); assertNotNull(cloneableFields); assertEquals(4, cloneableFields.length); } [Test] public function testFindAllWritableFieldsForTypeCloneableSubclass():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(cloneableSubclassType); assertNotNull(cloneableFields); assertEquals(7, cloneableFields.length); } [Test] public function testFindAllWritableFieldsForTypeClassLevelCopyableCloneable():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(classLevelCopyableCloneableType); assertNotNull(cloneableFields); assertEquals(4, cloneableFields.length); } [Test] public function testFindAllWritableFieldsForTypePropertyLevelCloneable():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(propertyLevelCloneableType); assertNotNull(cloneableFields); assertEquals(3, cloneableFields.length); } [Test] public function testFindAllWritableFieldsForTypePropertyLevelCopyableCloneable():void { const cloneableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(propertyLevelCopyableCloneableType); assertNotNull(cloneableFields); assertEquals(4, cloneableFields.length); } [Test] public function testCloneClassLevelCloneable():void { const clone:CloneableClass = Cloner.clone(cloneableClass); assertNotNull(clone); assertNotNull(clone.property1); assertEquals(clone.property1, cloneableClass.property1); assertNotNull(clone.property2); assertEquals(clone.property2, cloneableClass.property2); assertNotNull(clone.property3); assertEquals(clone.property3, cloneableClass.property3); assertNotNull(clone.writableField); assertEquals(clone.writableField, cloneableClass.writableField); } [Test] public function testCloneClassLevelCloneableSubclass():void { const clone:CloneableSubclass = Cloner.clone(cloneableSubclass); assertNotNull(clone); assertNotNull(clone.property1); assertEquals(clone.property1, cloneableSubclass.property1); assertNotNull(clone.property2); assertEquals(clone.property2, cloneableSubclass.property2); assertNotNull(clone.property3); assertEquals(clone.property3, cloneableSubclass.property3); assertNotNull(clone.property4); assertEquals(clone.property4, cloneableSubclass.property4); assertNotNull(clone.property5); assertEquals(clone.property5, cloneableSubclass.property5); assertNotNull(clone.writableField); assertEquals(clone.writableField, cloneableSubclass.writableField); assertNotNull(clone.writableField2); assertEquals(clone.writableField2, cloneableSubclass.writableField2); } [Test] public function testCloneClassLevelCopyableCloneable():void { const clone:ClassLevelCopyableCloneable = Cloner.clone(classLevelCopyableCloneable); assertNotNull(clone); assertNotNull(clone.property1); assertEquals(clone.property1, cloneableClass.property1); assertNotNull(clone.property2); assertEquals(clone.property2, cloneableClass.property2); assertNotNull(clone.property3); assertEquals(clone.property3, cloneableClass.property3); assertNotNull(clone.writableField); assertEquals(clone.writableField, cloneableClass.writableField); } /** * <code>Cloner.clone()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function testClonePropertyLevelCloneable():void { Cloner.clone(propertyLevelCloneable); } /** * <code>Cloner.clone()</code> method will throw <code>CloningError</code> in this case * because <code>PropertyLevelCopyableCloneable</code> class is not cloneable indeed. */ [Test(expects="dolly.core.errors.CloningError")] public function testClonePropertyLevelCopyableCloneable():void { Cloner.clone(propertyLevelCopyableCloneable); } } }
Rename methods in tests.
Rename methods in tests.
ActionScript
mit
Yarovoy/dolly
38bcf60ff5c2679f1b23af4690059094329ade3c
src/flash/net/URLStream.as
src/flash/net/URLStream.as
/* * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package flash.net { import flash.events.EventDispatcher; import flash.utils.ByteArray; import flash.utils.IDataInput; public class URLStream extends EventDispatcher implements IDataInput { public function URLStream() { } public native function load(request:URLRequest):void; public native function readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void; public native function readBoolean():Boolean; public native function readByte():int; public native function readUnsignedByte():uint; public native function readShort():int; public native function readUnsignedShort():uint; public native function readUnsignedInt():uint; public native function readInt():int; public native function readFloat():Number; public native function readDouble():Number; public native function readMultiByte(length:uint, charSet:String):String; public native function readUTF():String; public native function readUTFBytes(length:uint):String; public native function get connected():Boolean; public native function get bytesAvailable():uint; public native function close():void; public native function readObject(); public native function get objectEncoding():uint; public native function set objectEncoding(version:uint):void; public native function get endian():String; public native function set endian(type:String):void; public native function get diskCacheEnabled():Boolean; public native function get position():Number; public native function set position(offset:Number):void; public native function get length():Number; public native function stop():void; } }
/* * Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package flash.net { import flash.events.EventDispatcher; import flash.utils.ByteArray; import flash.utils.IDataInput; [native(cls='URLStreamClass')] public class URLStream extends EventDispatcher implements IDataInput { public function URLStream() { } public native function get connected(): Boolean; public native function get bytesAvailable(): uint; public native function get objectEncoding(): uint; public native function set objectEncoding(version: uint): void; public native function get endian(): String; public native function set endian(type: String): void; public native function get diskCacheEnabled(): Boolean; public native function get position(): Number; public native function set position(offset: Number): void; public native function get length(): Number; public native function load(request: URLRequest): void; public native function readBytes(bytes: ByteArray, offset: uint = 0, length: uint = 0): void; public native function readBoolean(): Boolean; public native function readByte(): int; public native function readUnsignedByte(): uint; public native function readShort(): int; public native function readUnsignedShort(): uint; public native function readUnsignedInt(): uint; public native function readInt(): int; public native function readFloat(): Number; public native function readDouble(): Number; public native function readMultiByte(length: uint, charSet: String): String; public native function readUTF(): String; public native function readUTFBytes(length: uint): String; public native function close(): void; public native function readObject(); public native function stop(): void; } }
Add [native] metadata to flash.net.URLStream builtin
Add [native] metadata to flash.net.URLStream builtin
ActionScript
apache-2.0
tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway
afa0d9823a8e0dea810e166f7c2ebd15111907a2
com/segonquart/idiomesAnimation.as
com/segonquart/idiomesAnimation.as
import mx.transitions.easing.*; import com.mosesSupposes.fuse.*; class idiomesAnimation extends Movieclip { private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr"); function idiomesAnimation():Void { this.stop(); this.onEnterFrame = this.enterSlide; } private function enterSlide() { arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1); arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1); arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2); arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3); } public function IdiomesColour() { this.onRelease = this arrayColour; target = this.arrayLang_arr[i]; target._tint = 0x8DC60D; return this; } private function arrayColour() { for ( var:i:Number=0 ; arrayLang_arr[i] <4; i++) { this.colorTo("#628D22", 0.3, "easeOutCirc"); _parent.colorTo('#4b4b4b', 1, 'linear', .2); } } }
import mx.transitions.easing.*; import com.mosesSupposes.fuse.*; class com.segonquart.idiomesAnimation extends Movieclip { private var arrayLang_arr:Array = new Array ("cat", "es", "en", "fr"); function idiomesAnimation():Void { this.stop(); this.onEnterFrame = this.enterSlide; } private function enterSlide() { arrayLang_arr[0].slideTo('0', '-40', 0.6, 'easeInOutBack', 1); arrayLang_arr[1].slideTo('0', '-40', 0.8, 'easeInOutBack', 1.1); arrayLang_arr[2].slideTo('0', '-40', 0.9, 'easeInOutBack', 1.2); arrayLang_arr[3].slideTo('0', '-40', 1, 'easeInOutBack', 1.3); } public function IdiomesColour() { this.onRelease = this arrayColour; target = this.arrayLang_arr[i]; target._tint = 0x8DC60D; return this; } private function arrayColour() { for ( var:i:Number=0 ; arrayLang_arr[i].length <4; i++) { this.colorTo("#628D22", 0.3, "easeOutCirc"); _parent.colorTo('#4b4b4b', 1, 'linear', .2); } } }
Update idiomesAnimation.as
Update idiomesAnimation.as
ActionScript
bsd-3-clause
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
9dc56e21b7a880ba7084f655beb5411d7ddbd759
src/as/com/threerings/cast/CharacterManager.as
src/as/com/threerings/cast/CharacterManager.as
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.cast { import flash.geom.Point; import com.threerings.util.Hashable; import com.threerings.util.Log; import com.threerings.util.Map; import com.threerings.util.StringUtil; import com.threerings.util.Maps; import com.threerings.util.maps.LRMap; /** * The character manager provides facilities for constructing sprites that * are used to represent characters in a scene. It also handles the * compositing and caching of composited character animations. */ public class CharacterManager { private static var log :Log = Log.getLog(CharacterManager); /** * Constructs the character manager. */ public function CharacterManager (crepo :ComponentRepository) { // keep this around _crepo = crepo; for each (var action :ActionSequence in crepo.getActionSequences()) { _actions.put(action.name, action); } } /** * Returns a {@link CharacterSprite} representing the character * described by the given {@link CharacterDescriptor}, or * <code>null</code> if an error occurs. * * @param desc the character descriptor. */ public function getCharacter (desc :CharacterDescriptor, charClass :Class = null) :CharacterSprite { if (charClass == null) { charClass = _charClass; } try { var sprite :CharacterSprite = new charClass(); sprite.init(desc, this); return sprite; } catch (e :Error) { log.warning("Failed to instantiate character sprite.", e); return null; } return getCharacter(desc, charClass); } public function getActionSequence (action :String) :ActionSequence { return _actions.get(action); } public function getComponent (compId :int) :CharacterComponent { return _crepo.getComponent(compId); } public function getActionFrames (descrip :CharacterDescriptor, action :String) :ActionFrames { if (!isLoaded(descrip)) { return null; } var key :FrameKey = new FrameKey(descrip, action); var frames :ActionFrames = _actionFrames.get(key); if (frames == null) { // this doesn't actually composite the images, but prepares an // object to be able to do so frames = createCompositeFrames(descrip, action); _actionFrames.put(key, frames); } return frames; } /** * Returns whether all the components are loaded and ready to go. */ protected function isLoaded (descrip :CharacterDescriptor) :Boolean { var cids :Array = descrip.getComponentIds(); var ccount :int = cids.length; for (var ii :int = 0; ii < ccount; ii++) { var ccomp :CharacterComponent = _crepo.getComponent(cids[ii]); if (!ccomp.isLoaded()) { return false; } } return true; } public function load (descrip :CharacterDescriptor, notify :Function) :void { _crepo.load(descrip.getComponentIds(), notify); } protected function createCompositeFrames (descrip :CharacterDescriptor, action :String) :ActionFrames { var cids :Array = descrip.getComponentIds(); var ccount :int = cids.length; var zations :Array = descrip.getColorizations(); var xlations :Array = descrip.getTranslations(); log.debug("Compositing action [action=" + action + ", descrip=" + descrip + "]."); // this will be used to construct any shadow layers var shadows :Map = null; /* of String, Array<TranslatedComponent> */ // maps components by class name for masks var ccomps :Map = Maps.newMapOf(String); /* of String, ArrayList<TranslatedComponent> */ // create colorized versions of all of the source action frames var sources :Array = []; for (var ii :int = 0; ii < ccount; ii++) { var cframes :ComponentFrames = new ComponentFrames(); sources.push(cframes); var ccomp :CharacterComponent = cframes.ccomp = _crepo.getComponent(cids[ii]); // load up the main component images var source :ActionFrames = ccomp.getFrames(action, null); if (source == null) { var errmsg :String = "Cannot composite action frames; no such " + "action for component [action=" + action + ", desc=" + descrip + ", comp=" + ccomp + "]"; throw new Error(errmsg); } source = (zations == null || zations[ii] == null) ? source : source.cloneColorized(zations[ii]); var xlation :Point = (xlations == null) ? null : xlations[ii]; cframes.frames = (xlation == null) ? source : source.cloneTranslated(xlation.x, xlation.y); // store the component with its translation under its class for masking var tcomp :TranslatedComponent = new TranslatedComponent(ccomp, xlation); var tcomps :Array = ccomps.get(ccomp.componentClass.name); if (tcomps == null) { ccomps.put(ccomp.componentClass.name, tcomps = []); } tcomps.push(tcomp); // if this component has a shadow, make a note of it if (ccomp.componentClass.isShadowed()) { if (shadows == null) { shadows = Maps.newMapOf(String); } var shadlist :Array = shadows.get(ccomp.componentClass.shadow); if (shadlist == null) { shadows.put(ccomp.componentClass.shadow, shadlist = []); } shadlist.push(tcomp); } } /* TODO - Implement shadows & masks - I don't actually know if/where we use these, though. // now create any necessary shadow layers if (shadows != null) { for (Map.Entry<String, ArrayList<TranslatedComponent>> entry : shadows.entrySet()) { ComponentFrames scf = compositeShadow(action, entry.getKey(), entry.getValue()); if (scf != null) { sources.add(scf); } } } // add any necessary masks for (ComponentFrames cframes : sources) { ArrayList<TranslatedComponent> mcomps = ccomps.get(cframes.ccomp.componentClass.mask); if (mcomps != null) { cframes.frames = compositeMask(action, cframes.ccomp, cframes.frames, mcomps); } } */ // use those to create an entity that will lazily composite things // together as they are needed return new CompositedActionFrames(_frameCache, _actions.get(action), sources); } protected var _crepo :ComponentRepository; protected var _actions :Map = Maps.newMapOf(String); protected var _actionFrames :Map = Maps.newMapOf(FrameKey); protected var _frameCache :LRMap = new LRMap(Maps.newMapOf(CompositedFramesKey), MAX_FRAMES); protected var _charClass :Class; protected static const MAX_FRAMES :int = 1000; } } import com.threerings.util.Hashable; import com.threerings.util.StringUtil; import com.threerings.cast.CharacterDescriptor; class FrameKey implements Hashable { public var desc :CharacterDescriptor; public var action :String; public function FrameKey (desc :CharacterDescriptor, action :String) { this.desc = desc; this.action = action; } public function hashCode () :int { return desc.hashCode() ^ StringUtil.hashCode(action); } public function equals (other :Object) :Boolean { if (other is FrameKey) { var okey :FrameKey = FrameKey(other); return okey.desc.equals(desc) && okey.action == action; } else { return false; } } } import flash.geom.Point; import com.threerings.cast.ActionFrames; import com.threerings.cast.CharacterComponent; class TranslatedComponent { public var ccomp :CharacterComponent; public var xlation :Point; public function TranslatedComponent (ccomp :CharacterComponent, xlation :Point) { this.ccomp = ccomp; this.xlation = xlation; } public function getFrames (action :String, type :String) :ActionFrames { var frames :ActionFrames = ccomp.getFrames(action, type); return (frames == null || xlation == null) ? frames : frames.cloneTranslated(xlation.x, xlation.y); } }
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.cast { import flash.geom.Point; import com.threerings.util.Hashable; import com.threerings.util.Log; import com.threerings.util.Map; import com.threerings.util.StringUtil; import com.threerings.util.Maps; import com.threerings.util.maps.LRMap; /** * The character manager provides facilities for constructing sprites that * are used to represent characters in a scene. It also handles the * compositing and caching of composited character animations. */ public class CharacterManager { private static var log :Log = Log.getLog(CharacterManager); /** * Constructs the character manager. */ public function CharacterManager (crepo :ComponentRepository) { // keep this around _crepo = crepo; for each (var action :ActionSequence in crepo.getActionSequences()) { _actions.put(action.name, action); } } /** * Returns a {@link CharacterSprite} representing the character * described by the given {@link CharacterDescriptor}, or * <code>null</code> if an error occurs. * * @param desc the character descriptor. */ public function getCharacter (desc :CharacterDescriptor, charClass :Class = null) :CharacterSprite { if (charClass == null) { charClass = _charClass; } try { var sprite :CharacterSprite = new charClass(); sprite.init(desc, this); return sprite; } catch (e :Error) { log.warning("Failed to instantiate character sprite.", e); return null; } return getCharacter(desc, charClass); } public function getActionSequence (action :String) :ActionSequence { return _actions.get(action); } public function getComponent (compId :int) :CharacterComponent { return _crepo.getComponent(compId); } public function getComponentByName (cclass :String, cname :String) :CharacterComponent { return _crepo.getComponentByName(cclass, cname); } public function getActionFrames (descrip :CharacterDescriptor, action :String) :ActionFrames { if (!isLoaded(descrip)) { return null; } var key :FrameKey = new FrameKey(descrip, action); var frames :ActionFrames = _actionFrames.get(key); if (frames == null) { // this doesn't actually composite the images, but prepares an // object to be able to do so frames = createCompositeFrames(descrip, action); _actionFrames.put(key, frames); } return frames; } /** * Returns whether all the components are loaded and ready to go. */ protected function isLoaded (descrip :CharacterDescriptor) :Boolean { var cids :Array = descrip.getComponentIds(); var ccount :int = cids.length; for (var ii :int = 0; ii < ccount; ii++) { var ccomp :CharacterComponent = _crepo.getComponent(cids[ii]); if (!ccomp.isLoaded()) { return false; } } return true; } public function load (descrip :CharacterDescriptor, notify :Function) :void { _crepo.load(descrip.getComponentIds(), notify); } protected function createCompositeFrames (descrip :CharacterDescriptor, action :String) :ActionFrames { var cids :Array = descrip.getComponentIds(); var ccount :int = cids.length; var zations :Array = descrip.getColorizations(); var xlations :Array = descrip.getTranslations(); log.debug("Compositing action [action=" + action + ", descrip=" + descrip + "]."); // this will be used to construct any shadow layers var shadows :Map = null; /* of String, Array<TranslatedComponent> */ // maps components by class name for masks var ccomps :Map = Maps.newMapOf(String); /* of String, ArrayList<TranslatedComponent> */ // create colorized versions of all of the source action frames var sources :Array = []; for (var ii :int = 0; ii < ccount; ii++) { var cframes :ComponentFrames = new ComponentFrames(); sources.push(cframes); var ccomp :CharacterComponent = cframes.ccomp = _crepo.getComponent(cids[ii]); // load up the main component images var source :ActionFrames = ccomp.getFrames(action, null); if (source == null) { var errmsg :String = "Cannot composite action frames; no such " + "action for component [action=" + action + ", desc=" + descrip + ", comp=" + ccomp + "]"; throw new Error(errmsg); } source = (zations == null || zations[ii] == null) ? source : source.cloneColorized(zations[ii]); var xlation :Point = (xlations == null) ? null : xlations[ii]; cframes.frames = (xlation == null) ? source : source.cloneTranslated(xlation.x, xlation.y); // store the component with its translation under its class for masking var tcomp :TranslatedComponent = new TranslatedComponent(ccomp, xlation); var tcomps :Array = ccomps.get(ccomp.componentClass.name); if (tcomps == null) { ccomps.put(ccomp.componentClass.name, tcomps = []); } tcomps.push(tcomp); // if this component has a shadow, make a note of it if (ccomp.componentClass.isShadowed()) { if (shadows == null) { shadows = Maps.newMapOf(String); } var shadlist :Array = shadows.get(ccomp.componentClass.shadow); if (shadlist == null) { shadows.put(ccomp.componentClass.shadow, shadlist = []); } shadlist.push(tcomp); } } /* TODO - Implement shadows & masks - I don't actually know if/where we use these, though. // now create any necessary shadow layers if (shadows != null) { for (Map.Entry<String, ArrayList<TranslatedComponent>> entry : shadows.entrySet()) { ComponentFrames scf = compositeShadow(action, entry.getKey(), entry.getValue()); if (scf != null) { sources.add(scf); } } } // add any necessary masks for (ComponentFrames cframes : sources) { ArrayList<TranslatedComponent> mcomps = ccomps.get(cframes.ccomp.componentClass.mask); if (mcomps != null) { cframes.frames = compositeMask(action, cframes.ccomp, cframes.frames, mcomps); } } */ // use those to create an entity that will lazily composite things // together as they are needed return new CompositedActionFrames(_frameCache, _actions.get(action), sources); } protected var _crepo :ComponentRepository; protected var _actions :Map = Maps.newMapOf(String); protected var _actionFrames :Map = Maps.newMapOf(FrameKey); protected var _frameCache :LRMap = new LRMap(Maps.newMapOf(CompositedFramesKey), MAX_FRAMES); protected var _charClass :Class; protected static const MAX_FRAMES :int = 1000; } } import com.threerings.util.Hashable; import com.threerings.util.StringUtil; import com.threerings.cast.CharacterDescriptor; class FrameKey implements Hashable { public var desc :CharacterDescriptor; public var action :String; public function FrameKey (desc :CharacterDescriptor, action :String) { this.desc = desc; this.action = action; } public function hashCode () :int { return desc.hashCode() ^ StringUtil.hashCode(action); } public function equals (other :Object) :Boolean { if (other is FrameKey) { var okey :FrameKey = FrameKey(other); return okey.desc.equals(desc) && okey.action == action; } else { return false; } } } import flash.geom.Point; import com.threerings.cast.ActionFrames; import com.threerings.cast.CharacterComponent; class TranslatedComponent { public var ccomp :CharacterComponent; public var xlation :Point; public function TranslatedComponent (ccomp :CharacterComponent, xlation :Point) { this.ccomp = ccomp; this.xlation = xlation; } public function getFrames (action :String, type :String) :ActionFrames { var frames :ActionFrames = ccomp.getFrames(action, type); return (frames == null || xlation == null) ? frames : frames.cloneTranslated(xlation.x, xlation.y); } }
Add ability to access components by name as well as by ID via the manager.
Add ability to access components by name as well as by ID via the manager. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@995 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
edcac62ee6018a99bb30a98368dc12e7211de585
src/com/esri/viewer/WidgetTemplate.as
src/com/esri/viewer/WidgetTemplate.as
/////////////////////////////////////////////////////////////////////////// // Copyright (c) 2010-2011 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// package com.esri.viewer { import com.esri.viewer.components.FocusableImage; import com.esri.viewer.components.TitlebarButton; import com.esri.viewer.utils.LocalizationUtil; import flash.events.Event; import flash.events.MouseEvent; import mx.controls.Image; import mx.core.FlexGlobals; import mx.core.UIComponent; import mx.events.FlexEvent; import mx.managers.CursorManager; import mx.managers.DragManager; import spark.components.Application; import spark.components.Group; import spark.components.SkinnableContainer; [Event(name="open", type="flash.events.Event")] [Event(name="minimized", type="flash.events.Event")] [Event(name="closed", type="flash.events.Event")] [Event(name="startDrag", type="flash.events.Event")] [Event(name="stopDrag", type="flash.events.Event")] [SkinState("open")] [SkinState("minimized")] [SkinState("closed")] public class WidgetTemplate extends SkinnableContainer implements IWidgetTemplate { [SkinPart(required="false")] public var widgetFrame:Group; [SkinPart(required="false")] public var header:Group; [SkinPart(required="false")] public var headerToolGroup:Group; [SkinPart(required="false")] public var icon:FocusableImage; [SkinPart(required="false")] public var closeButton:FocusableImage; [SkinPart(required="false")] public var minimizeButton:FocusableImage; [SkinPart(required="false")] public var resizeButton:Image; [Bindable] public var enableCloseButton:Boolean = true; [Bindable] public var enableMinimizeButton:Boolean = true; [Bindable] public var enableDraging:Boolean = true; [Bindable] public var widgetWidth:Number; [Bindable] public var widgetHeight:Number; [Embed(source="/assets/images/w_resizecursor.png")] public var resizeCursor:Class; [Embed(source="/assets/images/w_resizecursor_rtl.png")] public var resizeCursor_rtl:Class; [Bindable] public var enableIcon:Boolean = true; private static const WIDGET_OPENED:String = "open"; private static const WIDGET_MINIMIZED:String = "minimized"; private static const WIDGET_CLOSED:String = "closed"; private static const WIDGET_START_DRAG:String = "startDrag"; private static const WIDGET_STOP_DRAG:String = "stopDrag"; private var _widgetId:Number; private var _widgetState:String; private var _cursorID:int = 0; private var _widgetTitle:String = ""; private var _widgetIcon:String = "assets/images/i_widget.png"; [Bindable] private var _draggable:Boolean = true; private var _resizable:Boolean = true; private var _baseWidget:IBaseWidget; private var _isPartOfPanel:Boolean; [Bindable(event="isPartOfPanelChanged")] public function get isPartOfPanel():Boolean { return _isPartOfPanel; } public function set baseWidget(value:IBaseWidget):void { _baseWidget = value; _isPartOfPanel = value.isPartOfPanel; dispatchEvent(new Event("isPartOfPanelChanged")); if (_isPartOfPanel) { this.enableIcon = this.enableCloseButton = this.enableMinimizeButton = this.enableDraging = false; } this.resizable = value.isResizeable; this.draggable = value.isDraggable; this.widgetId = value.widgetId; this.widgetTitle = value.widgetTitle; this.widgetIcon = value.widgetIcon; if (value.initialWidth != 0) { if (this.minWidth == 0 || isNaN(this.minWidth) || value.initialWidth > this.minWidth) { this.width = value.initialWidth; this.widgetWidth = value.initialWidth; } } if (value.initialHeight != 0) { if (this.minHeight == 0 || isNaN(this.minHeight) || value.initialHeight > this.minHeight) { this.height = value.initialHeight; this.widgetHeight = value.initialHeight; } } } public function get baseWidget():IBaseWidget { return _baseWidget; } public function set resizable(value:Boolean):void { _resizable = value; resizeButton.visible = _resizable; } [Bindable] public function get resizable():Boolean { return _resizable; } public function set draggable(value:Boolean):void { if (enableDraging) { _draggable = value; } else { _draggable = false; } } public function get widgetId():Number { return _widgetId; } public function set widgetId(value:Number):void { _widgetId = value; } [Bindable] public function get widgetTitle():String { return _widgetTitle; } public function set widgetTitle(value:String):void { _widgetTitle = value; } [Bindable] public function get widgetIcon():String { return _widgetIcon; } public function set widgetIcon(value:String):void { _widgetIcon = value; } public function set widgetState(value:String):void { this.widgetFrame.toolTip = ""; this.icon.toolTip = ""; _widgetState = value; if (_widgetState == WIDGET_MINIMIZED) { this.widgetFrame.toolTip = this.widgetTitle; this.icon.toolTip = this.widgetTitle; } invalidateSkinState(); dispatchEvent(new Event(value)); } public function get widgetState():String { return _widgetState; } private var _selectedTitlebarButtonIndex:int = -1; private var _selectedTitlebarButtonIndexChanged:Boolean = false; public function get selectedTitlebarButtonIndex():int { return _selectedTitlebarButtonIndex; } public function set selectedTitlebarButtonIndex(value:int):void { if (_selectedTitlebarButtonIndex != value) { _selectedTitlebarButtonIndex = value; _selectedTitlebarButtonIndexChanged = true; invalidateProperties(); } } public function WidgetTemplate() { super(); this.width = 300; this.height = 300; this.hasFocusableChildren = true; this.addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler); } private function creationCompleteHandler(event:Event):void { widgetWidth = width; widgetHeight = height; this.closeButton.toolTip = LocalizationUtil.getDefaultString("close"); this.minimizeButton.toolTip = LocalizationUtil.getDefaultString("minimize"); } protected override function partAdded(partName:String, instance:Object):void { super.partAdded(partName, instance); if (instance == icon) { icon.addEventListener(MouseEvent.CLICK, icon_clickHandler); } if (instance == widgetFrame) { widgetFrame.addEventListener(MouseEvent.MOUSE_DOWN, mouse_downHandler); widgetFrame.addEventListener(MouseEvent.MOUSE_UP, mouse_upHandler); widgetFrame.stage.addEventListener(MouseEvent.MOUSE_UP, mouse_upHandler); widgetFrame.stage.addEventListener(Event.MOUSE_LEAVE, stageout_Handler); } if (instance == header) { header.addEventListener(MouseEvent.MOUSE_DOWN, mouse_downHandler); header.addEventListener(MouseEvent.MOUSE_UP, mouse_upHandler); } if (instance == closeButton) { closeButton.addEventListener(MouseEvent.CLICK, close_clickHandler); } if (instance == minimizeButton) { minimizeButton.addEventListener(MouseEvent.CLICK, minimize_clickHandler); } if (instance == resizeButton) { resizeButton.addEventListener(MouseEvent.MOUSE_OVER, resize_overHandler); resizeButton.addEventListener(MouseEvent.MOUSE_OUT, resize_outHandler); resizeButton.addEventListener(MouseEvent.MOUSE_DOWN, resize_downHandler); } } override protected function getCurrentSkinState():String { return _widgetState; } override protected function commitProperties():void { super.commitProperties(); if (_selectedTitlebarButtonIndexChanged) { _selectedTitlebarButtonIndexChanged = false; for (var i:int = 0, n:int = headerToolGroup.numElements; i < n; i++) { var btn:TitlebarButton = TitlebarButton(headerToolGroup.getElementAt(i)); if (i == _selectedTitlebarButtonIndex) { btn.selected = true; } else { btn.selected = false; } } } } public function mouse_downHandler(event:MouseEvent):void { if (_draggable && enableDraging) { header.addEventListener(MouseEvent.MOUSE_MOVE, mouse_moveHandler); widgetFrame.addEventListener(MouseEvent.MOUSE_MOVE, mouse_moveHandler); } } private var widgetMoveStarted:Boolean = false; private var xResizeStart:Number; private var yResizeStart:Number; private function mouse_moveHandler(event:MouseEvent):void { if (!widgetMoveStarted) { widgetMoveStarted = true; //TODO: not for V2.0 //AppEvent.dispatch(AppEvent.CHANGE_LAYOUT, LAYOUT_BASIC)); if (_widgetState != WIDGET_MINIMIZED) { this.alpha = 0.7; } var widget:UIComponent = parent as UIComponent; if (!DragManager.isDragging) { widget.startDrag(); dispatchEvent(new Event(WIDGET_START_DRAG)); } if (_resizable) { AppEvent.dispatch(AppEvent.WIDGET_FOCUS, widgetId); } } } private function mouse_upHandler(event:MouseEvent):void { header.removeEventListener(MouseEvent.MOUSE_MOVE, mouse_moveHandler); widgetFrame.removeEventListener(MouseEvent.MOUSE_MOVE, mouse_moveHandler); if (_widgetState != WIDGET_MINIMIZED) { this.alpha = 1; } var widget:UIComponent = parent as UIComponent; widget.stopDrag(); dispatchEvent(new Event(WIDGET_STOP_DRAG)); var appHeight:Number = FlexGlobals.topLevelApplication.height; var appWidth:Number = FlexGlobals.topLevelApplication.width; if (widget.y < 0) { widget.y = 0; } if (widget.y > (appHeight - 40)) { widget.y = appHeight - 40; } if (widget.x < 0) { widget.x = 20; } if (widget.x > (appWidth - 40)) { widget.x = appWidth - 40; } // clear constraints since x and y have been set widget.left = widget.right = widget.top = widget.bottom = undefined; widgetMoveStarted = false; } private function stageout_Handler(event:Event):void { if (widgetMoveStarted) { mouse_upHandler(null); } } protected function icon_clickHandler(event:MouseEvent):void { if (_baseWidget) { _baseWidget.setState(WIDGET_OPENED); } this.widgetFrame.toolTip = ""; this.icon.toolTip = ""; } protected function close_clickHandler(event:MouseEvent):void { if (_baseWidget) { _baseWidget.setState(WIDGET_CLOSED); } } protected function minimize_clickHandler(event:MouseEvent):void { if (_baseWidget) { _baseWidget.setState(WIDGET_MINIMIZED); } this.widgetFrame.toolTip = this.widgetTitle; this.icon.toolTip = this.widgetTitle; } private function resize_overHandler(event:MouseEvent):void { if (isRtl()) { _cursorID = CursorManager.setCursor(resizeCursor_rtl, 2, -10, -10); } else { _cursorID = CursorManager.setCursor(resizeCursor, 2, -10, -10); } } private function resize_outHandler(event:MouseEvent):void { CursorManager.removeCursor(_cursorID); } private function resize_downHandler(event:MouseEvent):void { if (_resizable) { xResizeStart = event.stageX yResizeStart = event.stageY; /*TODO: for now, it can't be resized when is not basic layout*/ stage.addEventListener(MouseEvent.MOUSE_MOVE, resize_moveHandler); stage.addEventListener(MouseEvent.MOUSE_UP, resize_upHandler); } } public function isRtl():Boolean { var result:Boolean = false; try { result = (FlexGlobals.topLevelApplication as Application).layoutDirection == "rtl"; } catch (error:Error) { result = false; } return result; } private function resize_moveHandler(event:MouseEvent):void { // clear constraints var widget:UIComponent = parent as UIComponent; widget.left = widget.right = widget.top = widget.bottom = undefined; var xResizeEnd:Number = event.stageX; var yResizeEnd:Number = event.stageY; var isWithinVerticalBoundaries:Boolean = (stage.mouseY < stage.height - 20); var isWithinHorizontalBoundaries:Boolean = isRtl() ? stage.mouseX > 20 : stage.mouseX < stage.width - 20; if (isWithinHorizontalBoundaries && isWithinVerticalBoundaries) { // if there is minWidth and minHeight specified on the container, use them while resizing const minimumResizeWidth:Number = minWidth ? minWidth : 200; const minimumResizeHeight:Number = minHeight ? minHeight : 100; var deltaX:Number = xResizeEnd - xResizeStart; var deltaY:Number = yResizeEnd - yResizeStart; var calculatedWidth:Number = isRtl() ? widgetWidth - deltaX : widgetWidth + deltaX; var calculatedHeight:Number = widgetHeight + deltaY; if (calculatedWidth > minimumResizeWidth) { width = calculatedWidth; } if (calculatedHeight > minimumResizeHeight) { height = calculatedHeight; } } } private function resize_upHandler(event:MouseEvent):void { widgetWidth = width; widgetHeight = height; stage.removeEventListener(MouseEvent.MOUSE_MOVE, resize_moveHandler); stage.removeEventListener(MouseEvent.MOUSE_UP, resize_upHandler); var p:UIComponent = parent as UIComponent; p.stopDrag(); } /** * Adds a new titlebar button - which usually represent a "state" or "view" within the widget. * For example, the Search widget has three titlebar buttons: one for "Select features" (interactively), * one for "Select by attribute", and one for "Results". * Each button corresponds to a function * * @param btnIcon URL to icon to use for this button. * @param btnTip Tooltip for this button. * @param btnFunction The function to call when this button is clicked. * @param selectable Boolean. */ public function addTitlebarButton(btnIcon:String, btnTip:String, btnFunction:Function, selectable:Boolean = true):void { var btn:TitlebarButton = new TitlebarButton(); btn.callback = btnFunction; btn.selectable = selectable; btn.source = btnIcon; btn.toolTip = btnTip; if (selectable) { btn.addEventListener(MouseEvent.CLICK, titlebarButton_clickHandler); if (headerToolGroup.numElements == 0) { selectedTitlebarButtonIndex = 0; // automatically select the first button added } } headerToolGroup.addElement(btn); } private function titlebarButton_clickHandler(event:MouseEvent):void { selectedTitlebarButtonIndex = headerToolGroup.getElementIndex(TitlebarButton(event.currentTarget)); } } }
/////////////////////////////////////////////////////////////////////////// // Copyright (c) 2010-2011 Esri. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// package com.esri.viewer { import com.esri.viewer.components.FocusableImage; import com.esri.viewer.components.TitlebarButton; import com.esri.viewer.utils.LocalizationUtil; import flash.events.Event; import flash.events.MouseEvent; import mx.controls.Image; import mx.core.FlexGlobals; import mx.core.UIComponent; import mx.events.FlexEvent; import mx.managers.CursorManager; import mx.managers.DragManager; import spark.components.Application; import spark.components.Group; import spark.components.SkinnableContainer; [Event(name="open", type="flash.events.Event")] [Event(name="minimized", type="flash.events.Event")] [Event(name="closed", type="flash.events.Event")] [Event(name="startDrag", type="flash.events.Event")] [Event(name="stopDrag", type="flash.events.Event")] [SkinState("open")] [SkinState("minimized")] [SkinState("closed")] public class WidgetTemplate extends SkinnableContainer implements IWidgetTemplate { [SkinPart(required="false")] public var widgetFrame:Group; [SkinPart(required="false")] public var header:Group; [SkinPart(required="false")] public var headerToolGroup:Group; [SkinPart(required="false")] public var icon:FocusableImage; [SkinPart(required="false")] public var closeButton:FocusableImage; [SkinPart(required="false")] public var minimizeButton:FocusableImage; [SkinPart(required="false")] public var resizeButton:Image; [Bindable] public var enableCloseButton:Boolean = true; [Bindable] public var enableMinimizeButton:Boolean = true; [Bindable] public var enableDraging:Boolean = true; [Bindable] public var widgetWidth:Number; [Bindable] public var widgetHeight:Number; [Embed(source="/assets/images/w_resizecursor.png")] public var resizeCursor:Class; [Embed(source="/assets/images/w_resizecursor_rtl.png")] public var resizeCursor_rtl:Class; [Bindable] public var enableIcon:Boolean = true; private static const WIDGET_OPENED:String = "open"; private static const WIDGET_MINIMIZED:String = "minimized"; private static const WIDGET_CLOSED:String = "closed"; private static const WIDGET_START_DRAG:String = "startDrag"; private static const WIDGET_STOP_DRAG:String = "stopDrag"; private var _widgetId:Number; private var _widgetState:String; private var _cursorID:int = 0; private var _widgetTitle:String = ""; private var _widgetIcon:String = "assets/images/i_widget.png"; [Bindable] private var _draggable:Boolean = true; private var _resizable:Boolean = true; private var _baseWidget:IBaseWidget; private var _isPartOfPanel:Boolean; [Bindable(event="isPartOfPanelChanged")] public function get isPartOfPanel():Boolean { return _isPartOfPanel; } public function set baseWidget(value:IBaseWidget):void { _baseWidget = value; _isPartOfPanel = value.isPartOfPanel; dispatchEvent(new Event("isPartOfPanelChanged")); if (_isPartOfPanel) { this.enableIcon = this.enableCloseButton = this.enableMinimizeButton = this.enableDraging = false; } this.resizable = value.isResizeable; this.draggable = value.isDraggable; this.widgetId = value.widgetId; this.widgetTitle = value.widgetTitle; this.widgetIcon = value.widgetIcon; if (value.initialWidth != 0) { if (this.minWidth == 0 || isNaN(this.minWidth) || value.initialWidth > this.minWidth) { this.width = value.initialWidth; this.widgetWidth = value.initialWidth; } } if (value.initialHeight != 0) { if (this.minHeight == 0 || isNaN(this.minHeight) || value.initialHeight > this.minHeight) { this.height = value.initialHeight; this.widgetHeight = value.initialHeight; } } } public function get baseWidget():IBaseWidget { return _baseWidget; } public function set resizable(value:Boolean):void { _resizable = value; resizeButton.visible = _resizable; } [Bindable] public function get resizable():Boolean { return _resizable; } public function set draggable(value:Boolean):void { if (enableDraging) { _draggable = value; } else { _draggable = false; } } public function get widgetId():Number { return _widgetId; } public function set widgetId(value:Number):void { _widgetId = value; } [Bindable] public function get widgetTitle():String { return _widgetTitle; } public function set widgetTitle(value:String):void { _widgetTitle = value; } [Bindable] public function get widgetIcon():String { return _widgetIcon; } public function set widgetIcon(value:String):void { _widgetIcon = value; } public function set widgetState(value:String):void { this.widgetFrame.toolTip = ""; this.icon.toolTip = ""; _widgetState = value; if (_widgetState == WIDGET_MINIMIZED) { this.widgetFrame.toolTip = this.widgetTitle; this.icon.toolTip = this.widgetTitle; } invalidateSkinState(); dispatchEvent(new Event(value)); } public function get widgetState():String { return _widgetState; } private var _selectedTitlebarButtonIndex:int = -1; private var _selectedTitlebarButtonIndexChanged:Boolean = false; public function get selectedTitlebarButtonIndex():int { return _selectedTitlebarButtonIndex; } public function set selectedTitlebarButtonIndex(value:int):void { if (_selectedTitlebarButtonIndex != value) { _selectedTitlebarButtonIndex = value; _selectedTitlebarButtonIndexChanged = true; invalidateProperties(); } } public function WidgetTemplate() { super(); this.width = 300; this.height = 300; this.hasFocusableChildren = true; this.addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler); } private function creationCompleteHandler(event:Event):void { widgetWidth = width; widgetHeight = height; this.closeButton.toolTip = LocalizationUtil.getDefaultString("close"); this.minimizeButton.toolTip = LocalizationUtil.getDefaultString("minimize"); } protected override function partAdded(partName:String, instance:Object):void { super.partAdded(partName, instance); if (instance == icon) { icon.addEventListener(MouseEvent.CLICK, icon_clickHandler); } if (instance == widgetFrame) { widgetFrame.addEventListener(MouseEvent.MOUSE_DOWN, mouse_downHandler); widgetFrame.addEventListener(MouseEvent.MOUSE_UP, mouse_upHandler); widgetFrame.stage.addEventListener(MouseEvent.MOUSE_UP, mouse_upHandler); widgetFrame.stage.addEventListener(Event.MOUSE_LEAVE, stageout_Handler); } if (instance == header) { header.addEventListener(MouseEvent.MOUSE_DOWN, mouse_downHandler); header.addEventListener(MouseEvent.MOUSE_UP, mouse_upHandler); } if (instance == closeButton) { closeButton.addEventListener(MouseEvent.CLICK, close_clickHandler); } if (instance == minimizeButton) { minimizeButton.addEventListener(MouseEvent.CLICK, minimize_clickHandler); } if (instance == resizeButton) { resizeButton.addEventListener(MouseEvent.MOUSE_OVER, resize_overHandler); resizeButton.addEventListener(MouseEvent.MOUSE_OUT, resize_outHandler); resizeButton.addEventListener(MouseEvent.MOUSE_DOWN, resize_downHandler); } } override protected function getCurrentSkinState():String { return _widgetState; } override protected function commitProperties():void { super.commitProperties(); if (_selectedTitlebarButtonIndexChanged) { _selectedTitlebarButtonIndexChanged = false; for (var i:int = 0, n:int = headerToolGroup.numElements; i < n; i++) { var btn:TitlebarButton = TitlebarButton(headerToolGroup.getElementAt(i)); if (i == _selectedTitlebarButtonIndex) { btn.selected = true; } else { btn.selected = false; } } } } public function mouse_downHandler(event:MouseEvent):void { if (_draggable && enableDraging) { header.addEventListener(MouseEvent.MOUSE_MOVE, mouse_moveHandler); widgetFrame.addEventListener(MouseEvent.MOUSE_MOVE, mouse_moveHandler); } } private var widgetMoveStarted:Boolean = false; private var xResizeStart:Number; private var yResizeStart:Number; private function mouse_moveHandler(event:MouseEvent):void { if (!widgetMoveStarted) { widgetMoveStarted = true; //TODO: not for V2.0 //AppEvent.dispatch(AppEvent.CHANGE_LAYOUT, LAYOUT_BASIC)); if (_widgetState != WIDGET_MINIMIZED) { this.alpha = 0.7; } var widget:UIComponent = parent as UIComponent; if (!DragManager.isDragging) { widget.startDrag(); dispatchEvent(new Event(WIDGET_START_DRAG)); } if (_resizable) { AppEvent.dispatch(AppEvent.WIDGET_FOCUS, widgetId); } } } private function mouse_upHandler(event:MouseEvent):void { header.removeEventListener(MouseEvent.MOUSE_MOVE, mouse_moveHandler); widgetFrame.removeEventListener(MouseEvent.MOUSE_MOVE, mouse_moveHandler); if (_widgetState != WIDGET_MINIMIZED) { this.alpha = 1; } var widget:UIComponent = parent as UIComponent; widget.stopDrag(); dispatchEvent(new Event(WIDGET_STOP_DRAG)); var appHeight:Number = FlexGlobals.topLevelApplication.height; var appWidth:Number = FlexGlobals.topLevelApplication.width; if (widget.y < 0) { widget.y = 0; } if (widget.y > (appHeight - 40)) { widget.y = appHeight - 40; } if (widget.x < 0) { widget.x = 20; } if (widget.x > (appWidth - 40)) { widget.x = appWidth - 40; } // clear constraints since x and y have been set widget.left = widget.right = widget.top = widget.bottom = undefined; widgetMoveStarted = false; } private function stageout_Handler(event:Event):void { if (widgetMoveStarted) { mouse_upHandler(null); } } protected function icon_clickHandler(event:MouseEvent):void { if (_baseWidget) { _baseWidget.setState(WIDGET_OPENED); } this.widgetFrame.toolTip = ""; this.icon.toolTip = ""; } protected function close_clickHandler(event:MouseEvent):void { if (_baseWidget) { _baseWidget.setState(WIDGET_CLOSED); } } protected function minimize_clickHandler(event:MouseEvent):void { if (_baseWidget) { _baseWidget.setState(WIDGET_MINIMIZED); } this.widgetFrame.toolTip = this.widgetTitle; this.icon.toolTip = this.widgetTitle; } private function resize_overHandler(event:MouseEvent):void { if (isRtl()) { _cursorID = CursorManager.setCursor(resizeCursor_rtl, 2, -10, -10); } else { _cursorID = CursorManager.setCursor(resizeCursor, 2, -10, -10); } } private function resize_outHandler(event:MouseEvent):void { CursorManager.removeCursor(_cursorID); } private function resize_downHandler(event:MouseEvent):void { if (_resizable) { xResizeStart = event.stageX yResizeStart = event.stageY; /*TODO: for now, it can't be resized when is not basic layout*/ stage.addEventListener(MouseEvent.MOUSE_MOVE, resize_moveHandler); stage.addEventListener(MouseEvent.MOUSE_UP, resize_upHandler); } } public function isRtl():Boolean { var result:Boolean = false; try { result = (FlexGlobals.topLevelApplication as Application).layoutDirection == "rtl"; } catch (error:Error) { result = false; } return result; } private function resize_moveHandler(event:MouseEvent):void { // clear constraints var widget:UIComponent = parent as UIComponent; widget.left = widget.right = widget.top = widget.bottom = undefined; var xResizeEnd:Number = event.stageX; var yResizeEnd:Number = event.stageY; var isWithinVerticalBoundaries:Boolean = (stage.mouseY < stage.height - 20); var isWithinHorizontalBoundaries:Boolean = isRtl() ? stage.mouseX > 20 : stage.mouseX < stage.width - 20; if (isWithinHorizontalBoundaries && isWithinVerticalBoundaries) { // if there is minWidth and minHeight specified on the container, use them while resizing const minimumResizeWidth:Number = minWidth ? minWidth : 200; const minimumResizeHeight:Number = minHeight ? minHeight : 100; var deltaX:Number = xResizeEnd - xResizeStart; var deltaY:Number = yResizeEnd - yResizeStart; var calculatedWidth:Number = isRtl() ? widgetWidth - deltaX : widgetWidth + deltaX; var calculatedHeight:Number = widgetHeight + deltaY; if (calculatedWidth > minimumResizeWidth) { width = calculatedWidth; } if (calculatedHeight > minimumResizeHeight) { height = calculatedHeight; } } } private function resize_upHandler(event:MouseEvent):void { widgetWidth = width; widgetHeight = height; stage.removeEventListener(MouseEvent.MOUSE_MOVE, resize_moveHandler); stage.removeEventListener(MouseEvent.MOUSE_UP, resize_upHandler); var p:UIComponent = parent as UIComponent; p.stopDrag(); } /** * Adds a new titlebar button - which usually represent a "state" or "view" within the widget. * For example, the Search widget has three titlebar buttons: one for "Select features" (interactively), * one for "Select by attribute", and one for "Results". * Each button corresponds to a function * * @param btnIcon URL to icon to use for this button. * @param btnTip Tooltip for this button. * @param btnFunction The function to call when this button is clicked. * @param selectable Boolean. */ public function addTitlebarButton(btnIcon:String, btnTip:String, btnFunction:Function, selectable:Boolean = true):void { var btn:TitlebarButton = new TitlebarButton(); btn.callback = btnFunction; btn.selectable = selectable; btn.source = btnIcon; btn.toolTip = btnTip; if (selectable) { btn.addEventListener(MouseEvent.CLICK, titlebarButton_clickHandler); if (headerToolGroup.numElements == 0) { selectedTitlebarButtonIndex = 0; // automatically select the first button added } } headerToolGroup.addElement(btn); } private function titlebarButton_clickHandler(event:MouseEvent):void { selectedTitlebarButtonIndex = headerToolGroup.getElementIndex(TitlebarButton(event.currentTarget)); } } }
Clean up.
Clean up.
ActionScript
apache-2.0
CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex
3caf9d8b2d79a99fc50d010f747871b03c25b5d9
src/flash/Recorder.as
src/flash/Recorder.as
package { import flash.utils.ByteArray; import flash.display.Sprite; import flash.media.Microphone; import flash.media.SoundMixer; import flash.media.SoundTransform; import flash.system.Security; import flash.system.SecurityPanel; import org.bytearray.micrecorder.*; import org.bytearray.micrecorder.events.RecordingEvent; import org.bytearray.micrecorder.encoder.WaveEncoder; import flash.events.Event; import flash.events.ActivityEvent; import flash.net.FileReference; import flash.external.ExternalInterface; import flash.events.StatusEvent; import flash.media.Microphone; import Base64; public class Recorder extends Sprite { private var muted:Boolean = true; private var recording:Boolean = false; private var mic:Microphone; private var wavEncoder:WaveEncoder = new WaveEncoder(); private var micRecorder:MicRecorder = new MicRecorder(wavEncoder); private var fileReference:FileReference = new FileReference(); public function Recorder() { initializeMicRecorder(); addEventListeners(); Security.showSettings("2"); } // Methods public function isMuted():Boolean { return muted; } public function getActivityLevel():Number { return mic.activityLevel; } public function getDataURL():String { return 'data:audio/wav;base64,' + Base64.encode(micRecorder.output); } public function startRecording():void { if (!recording) { recording = true; micRecorder.record(); } } public function stopRecording():void { if (recording) { recording = false; micRecorder.stop(); mic.setLoopBack(false); } } // Event Handlers private function onRecording(e:RecordingEvent):void { dispatchEvent(new Event('Recorder.recording', true)); } private function onComplete(e:Event):void { dispatchEvent(new Event('Recorder.complete', true)); } private function onMicStatus(e:StatusEvent):void { if (e.code == "Microphone.Unmuted"){ muted = false; mic.removeEventListener(StatusEvent.STATUS, onMicStatus); dispatchEvent(new Event('Recorder.enabled', true)); } else if (e.code == "Microphone.Muted") { muted = true; mic.removeEventListener(StatusEvent.STATUS, onMicStatus); dispatchEvent(new Event('Recorder.disabled', true)); } } // Just Getting things out of the way private function muteSpeakers():void { var transform1:SoundTransform=new SoundTransform(); transform1.volume=0; // goes from 0 to 1 flash.media.SoundMixer.soundTransform=transform1; } private function initializeMicRecorder():void { muteSpeakers(); mic = Microphone.getMicrophone(); mic.setSilenceLevel(0); mic.gain = 100; mic.setLoopBack(true); mic.setUseEchoSuppression(true); } private function addEventListeners():void { mic.addEventListener(StatusEvent.STATUS, onMicStatus, false, 0, true); micRecorder.addEventListener(RecordingEvent.RECORDING, onRecording); micRecorder.addEventListener(Event.COMPLETE, onComplete); } } }
package { import flash.utils.ByteArray; import flash.display.Sprite; import flash.media.Microphone; import flash.media.SoundMixer; import flash.media.SoundTransform; import flash.system.Security; import flash.system.SecurityPanel; import org.bytearray.micrecorder.*; import org.bytearray.micrecorder.events.RecordingEvent; import org.bytearray.micrecorder.encoder.WaveEncoder; import flash.events.Event; import flash.events.ActivityEvent; import flash.net.FileReference; import flash.external.ExternalInterface; import flash.events.StatusEvent; import flash.media.Microphone; import Base64; import RecorderEvent; public class Recorder extends Sprite { private var muted:Boolean = true; private var recording:Boolean = false; private var time:int = 0; private var duration:int = 0; private var mic:Microphone; private var wavEncoder:WaveEncoder = new WaveEncoder(); private var micRecorder:MicRecorder = new MicRecorder(wavEncoder); private var fileReference:FileReference = new FileReference(); public function Recorder() { initializeMicRecorder(); addEventListeners(); Security.showSettings("2"); } private function addEventListeners():void { addEventListener(Event.ENTER_FRAME, onEnterFrame); mic.addEventListener(StatusEvent.STATUS, onMicStatus, false, 0, true); micRecorder.addEventListener(RecordingEvent.RECORDING, onRecording); micRecorder.addEventListener(Event.COMPLETE, onComplete); } // Methods public function isMuted():Boolean { return muted; } public function getActivityLevel():int { return mic.activityLevel; } public function getTime():int { return this.time; } public function getDuration():int { return this.duration; } public function getDataURL():String { return 'data:audio/wav;base64,' + Base64.encode(micRecorder.output); } public function startRecording():void { if (!recording) { recording = true; micRecorder.record(); } } public function stopRecording():void { if (recording) { recording = false; micRecorder.stop(); mic.setLoopBack(false); } } // Event Handlers private function onEnterFrame(e:Event):void { var data:Object = {muted: this.muted, recording: this.recording, volume: mic.activityLevel}; if (this.time) data.time = this.time; dispatchEvent(new RecorderEvent(RecorderEvent.STATUS, data, true)); } private function onRecording(e:RecordingEvent):void { var data:Object = {time: e.time, volume: mic.activityLevel}; dispatchEvent(new RecorderEvent(RecorderEvent.RECORDING, data, true)); } private function onComplete(e:Event):void { var data:Object = {}; dispatchEvent(new RecorderEvent(RecorderEvent.COMPLETE, data, true)); } private function onMicStatus(e:StatusEvent):void { if (e.code == "Microphone.Unmuted"){ muted = false; mic.removeEventListener(StatusEvent.STATUS, onMicStatus); dispatchEvent(new RecorderEvent(RecorderEvent.ENABLED, true)); } else if (e.code == "Microphone.Muted") { mic.removeEventListener(StatusEvent.STATUS, onMicStatus); dispatchEvent(new RecorderEvent(RecorderEvent.DISABLED, true)); } } // Just Getting things out of the way private function muteSpeakers():void { var transform1:SoundTransform=new SoundTransform(); transform1.volume=0; // goes from 0 to 1 flash.media.SoundMixer.soundTransform=transform1; } private function initializeMicRecorder():void { muteSpeakers(); mic = Microphone.getMicrophone(); mic.setSilenceLevel(0); mic.gain = 100; mic.setLoopBack(true); mic.setUseEchoSuppression(true); } } }
Update Recorder to dispatch only RecorderEvents
Update Recorder to dispatch only RecorderEvents
ActionScript
mit
mhotwagner/anachrony
673e330d4cb9017d1a3840199798a28ac94d2347
WEB-INF/lps/lfc/kernel/swf9/LzKeyboardKernel.as
WEB-INF/lps/lfc/kernel/swf9/LzKeyboardKernel.as
/** * LzKeyboardKernel.lzs * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ // Receives keyboard events from the runtime class LzKeyboardKernelClass { function __keyboardEvent ( e, t ){ var delta = {}; var s, k = e.keyCode; s = String.fromCharCode(k).toLowerCase(); delta[s] = (t == "onkeydown"); if (this.__callback) this.__scope[this.__callback](delta, k, t); } var __callback = null; var __scope = null; function setCallback (scope, funcname) { this.__scope = scope; this.__callback = funcname; } // Called by lz.Keys when the last focusable element was reached. function gotLastFocus() { } } // End of LzKeyboardKernelClass var LzKeyboardKernel = new LzKeyboardKernelClass ();
/** * LzKeyboardKernel.lzs * * @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic AS2 */ // Receives keyboard events from the runtime class LzKeyboardKernelClass { function __keyboardEvent ( e, t ){ var delta = {}; var s, k = e.keyCode; var keyisdown = t == 'onkeydown'; s = String.fromCharCode(k).toLowerCase(); if (keyisdown) { // prevent duplicate onkeydown events - see LPP-7432 if (k == __lastkeydown) return; __lastkeydown = k; } else { __lastkeydown = null; } delta[s] = keyisdown; if (this.__callback) this.__scope[this.__callback](delta, k, t); } var __callback = null; var __scope = null; var __lastkeydown = null; function setCallback (scope, funcname) { this.__scope = scope; this.__callback = funcname; } // Called by lz.Keys when the last focusable element was reached. function gotLastFocus() { } } // End of LzKeyboardKernelClass var LzKeyboardKernel = new LzKeyboardKernelClass ();
Change 20081209-maxcarlson-K by [email protected] on 2008-12-09 05:03:02 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20081209-maxcarlson-K by [email protected] on 2008-12-09 05:03:02 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk Summary: swf9: prevent duplicate onkeydown events Bugs Fixed: LPP-7432 - onkeydown event keep firing Technical Reviewer: [email protected] QA Reviewer: promanik Details: Cache last value of onkeydown to prevent duplicate events from being sent Tests: See LPP-7432 git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12035 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
f3319cf3837ec01a94fa9e8466a13d52efc69839
src/org/mangui/osmf/plugins/traits/HLSDynamicStreamTrait.as
src/org/mangui/osmf/plugins/traits/HLSDynamicStreamTrait.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.osmf.plugins.traits { import org.mangui.hls.HLS; import org.mangui.hls.event.HLSEvent; import org.osmf.traits.DynamicStreamTrait; import org.osmf.utils.OSMFStrings; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class HLSDynamicStreamTrait extends DynamicStreamTrait { private var _hls : HLS; public function HLSDynamicStreamTrait(hls : HLS) { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait()"); } _hls = hls; _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); super(true, _hls.startLevel, hls.levels.length); } override public function dispose() : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:dispose"); } _hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); super.dispose(); } override public function getBitrateForIndex(index : int) : Number { if (index > numDynamicStreams - 1 || index < 0) { throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX)); } var bitrate : Number = _hls.levels[index].bitrate / 1000; CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:getBitrateForIndex(" + index + ")=" + bitrate); } return bitrate; } override public function switchTo(index : int) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:switchTo(" + index + ")/max:" + maxAllowedIndex); } if (index < 0 || index > maxAllowedIndex) { throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX)); } autoSwitch = false; if (!switching) { setSwitching(true, index); } } override protected function autoSwitchChangeStart(value : Boolean) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:autoSwitchChangeStart:" + value); } if (value == true && _hls.autoLevel == false) { _hls.loadLevel = -1; // only seek if position is set if (!isNaN(_hls.position)) { _hls.stream.seek(_hls.position); } } } override protected function switchingChangeStart(newSwitching : Boolean, index : int) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:switchingChangeStart(newSwitching/index):" + newSwitching + "/" + index); } if (newSwitching) { _hls.loadLevel = index; } } /** Update playback position/duration **/ private function _levelSwitchHandler(event : HLSEvent) : void { var newLevel : int = event.level; CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:_qualitySwitchHandler:" + newLevel); } setCurrentIndex(newLevel); setSwitching(false, newLevel); }; } }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.osmf.plugins.traits { import org.mangui.hls.HLS; import org.mangui.hls.event.HLSEvent; import org.osmf.traits.DynamicStreamTrait; import org.osmf.utils.OSMFStrings; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class HLSDynamicStreamTrait extends DynamicStreamTrait { private var _hls : HLS; public function HLSDynamicStreamTrait(hls : HLS) { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait()"); } _hls = hls; _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); super(true, _hls.startLevel, hls.levels.length); } override public function dispose() : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:dispose"); } _hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); super.dispose(); } override public function getBitrateForIndex(index : int) : Number { if (index > numDynamicStreams - 1 || index < 0) { throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX)); } var bitrate : Number = _hls.levels[index].bitrate / 1000; CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:getBitrateForIndex(" + index + ")=" + bitrate); } return bitrate; } override public function switchTo(index : int) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:switchTo(" + index + ")/max:" + maxAllowedIndex); } if (index < 0 || index > maxAllowedIndex) { throw new RangeError(OSMFStrings.getString(OSMFStrings.STREAMSWITCH_INVALID_INDEX)); } autoSwitch = false; if (!switching) { setSwitching(true, index); } } override protected function autoSwitchChangeStart(value : Boolean) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:autoSwitchChangeStart:" + value); } if (value == true && _hls.autoLevel == false) { _hls.nextLevel = -1; } } override protected function switchingChangeStart(newSwitching : Boolean, index : int) : void { CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:switchingChangeStart(newSwitching/index):" + newSwitching + "/" + index); } if (newSwitching) { _hls.currentLevel = index; } } /** Update playback position/duration **/ private function _levelSwitchHandler(event : HLSEvent) : void { var newLevel : int = event.level; CONFIG::LOGGING { Log.debug("HLSDynamicStreamTrait:_qualitySwitchHandler:" + newLevel); } setCurrentIndex(newLevel); setSwitching(false, newLevel); }; } }
speed up level switching
flashlsOSMF: speed up level switching
ActionScript
mpl-2.0
thdtjsdn/flashls,Corey600/flashls,Corey600/flashls,aevange/flashls,Peer5/flashls,suuhas/flashls,neilrackett/flashls,vidible/vdb-flashls,codex-corp/flashls,suuhas/flashls,jlacivita/flashls,vidible/vdb-flashls,JulianPena/flashls,aevange/flashls,jlacivita/flashls,hola/flashls,aevange/flashls,fixedmachine/flashls,NicolasSiver/flashls,clappr/flashls,dighan/flashls,fixedmachine/flashls,aevange/flashls,hola/flashls,Boxie5/flashls,Peer5/flashls,Peer5/flashls,tedconf/flashls,suuhas/flashls,Boxie5/flashls,JulianPena/flashls,mangui/flashls,loungelogic/flashls,loungelogic/flashls,codex-corp/flashls,suuhas/flashls,Peer5/flashls,NicolasSiver/flashls,tedconf/flashls,mangui/flashls,clappr/flashls,neilrackett/flashls,thdtjsdn/flashls,dighan/flashls
29525d54d92d27bd1c80ae6038efba68be79e08b
src/org/mangui/osmf/plugins/utils/ErrorManager.as
src/org/mangui/osmf/plugins/utils/ErrorManager.as
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.osmf.plugins.utils { import org.mangui.hls.event.HLSError; import org.mangui.hls.event.HLSEvent; import org.osmf.events.MediaErrorCodes; public class ErrorManager { public static function getMediaErrorCode(event : HLSEvent) : int { var errorCode : int = MediaErrorCodes.NETSTREAM_PLAY_FAILED; if (event && event.error) { switch (event.error.code) { case HLSError.FRAGMENT_LOADING_ERROR: case HLSError.FRAGMENT_LOADING_CROSSDOMAIN_ERROR: case HLSError.KEY_LOADING_ERROR: case HLSError.KEY_LOADING_CROSSDOMAIN_ERROR: case HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR: case HLSError.MANIFEST_LOADING_IO_ERROR: errorCode = MediaErrorCodes.IO_ERROR; break; case org.mangui.hls.event.HLSError.FRAGMENT_PARSING_ERROR: case org.mangui.hls.event.HLSError.KEY_PARSING_ERROR: case org.mangui.hls.event.HLSError.MANIFEST_PARSING_ERROR: errorCode = MediaErrorCodes.NETSTREAM_FILE_STRUCTURE_INVALID; break; case org.mangui.hls.event.HLSError.TAG_APPENDING_ERROR: errorCode = MediaErrorCodes.ARGUMENT_ERROR; break; } } return errorCode; }; public static function getMediaErrorMessage(event : HLSEvent) : String { return (event && event.error) ? event.error.msg : "Unknown error"; }; }; }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mangui.osmf.plugins.utils { import org.mangui.hls.event.HLSError; import org.mangui.hls.event.HLSEvent; import org.osmf.events.MediaErrorCodes; public class ErrorManager { public static function getMediaErrorCode(event : HLSEvent) : int { var errorCode : int = MediaErrorCodes.NETSTREAM_PLAY_FAILED; if (event && event.error) { switch (event.error.code) { case HLSError.FRAGMENT_LOADING_ERROR: case HLSError.KEY_LOADING_ERROR: case HLSError.MANIFEST_LOADING_IO_ERROR: errorCode = MediaErrorCodes.IO_ERROR; break; case HLSError.FRAGMENT_LOADING_CROSSDOMAIN_ERROR: case HLSError.KEY_LOADING_CROSSDOMAIN_ERROR: case HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR: errorCode = MediaErrorCodes.SECURITY_ERROR break; case org.mangui.hls.event.HLSError.FRAGMENT_PARSING_ERROR: case org.mangui.hls.event.HLSError.KEY_PARSING_ERROR: case org.mangui.hls.event.HLSError.MANIFEST_PARSING_ERROR: errorCode = MediaErrorCodes.NETSTREAM_FILE_STRUCTURE_INVALID; break; case org.mangui.hls.event.HLSError.TAG_APPENDING_ERROR: errorCode = MediaErrorCodes.ARGUMENT_ERROR; break; } } return errorCode; }; public static function getMediaErrorMessage(event : HLSEvent) : String { return (event && event.error) ? event.error.msg : "Unknown error"; }; }; }
Fix mapping of HLSError.FRAGMENT_LOADING_CROSSDOMAIN_ERROR, HLSError.KEY_LOADING_CROSSDOMAIN_ERROR, HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR to MediaErrorCodes.SECURITY_ERROR instead of MediaErrorCodes.IO_ERROR
Fix mapping of HLSError.FRAGMENT_LOADING_CROSSDOMAIN_ERROR, HLSError.KEY_LOADING_CROSSDOMAIN_ERROR, HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR to MediaErrorCodes.SECURITY_ERROR instead of MediaErrorCodes.IO_ERROR
ActionScript
mpl-2.0
vidible/vdb-flashls,JulianPena/flashls,tedconf/flashls,hola/flashls,codex-corp/flashls,NicolasSiver/flashls,dighan/flashls,loungelogic/flashls,mangui/flashls,tedconf/flashls,vidible/vdb-flashls,jlacivita/flashls,thdtjsdn/flashls,Corey600/flashls,neilrackett/flashls,fixedmachine/flashls,clappr/flashls,neilrackett/flashls,jlacivita/flashls,hola/flashls,fixedmachine/flashls,NicolasSiver/flashls,loungelogic/flashls,Corey600/flashls,codex-corp/flashls,mangui/flashls,thdtjsdn/flashls,JulianPena/flashls,dighan/flashls,clappr/flashls
bb0113ae398d24a519006d4816fa9a0f5d07c2d2
ApplicationDemo/src/main/flex/sk/yoz/ycanvas/demo/simple/Partition.as
ApplicationDemo/src/main/flex/sk/yoz/ycanvas/demo/simple/Partition.as
package sk.yoz.ycanvas.demo.simple { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.IBitmapDrawable; import flash.display.Loader; import flash.display.LoaderInfo; import flash.events.Event; import flash.events.IOErrorEvent; import flash.geom.Matrix; import flash.net.URLRequest; import flash.system.LoaderContext; import sk.yoz.ycanvas.interfaces.ILayer; import sk.yoz.ycanvas.stage3D.interfaces.IPartitionStage3D; import starling.display.DisplayObject; import starling.display.Image; import starling.textures.Texture; public class Partition implements IPartitionStage3D { private var _x:int; private var _y:int; private var _content:starling.display.DisplayObject; private var _layer:ILayer; private var bitmapData:BitmapData; private var error:Boolean; private var loader:Loader; public function Partition(layer:ILayer, x:int, y:int) { _layer = layer; _x = x; _y = y; _content = new Image(Texture.fromBitmapData(new BitmapData(256, 256, true, 0x0))); content.x = x; content.y = y; } public function get content():starling.display.DisplayObject { return _content; } public function get x():int { return _x; } public function get y():int { return _y; } public function get expectedWidth():uint { return 256; } public function get expectedHeight():uint { return 256; } public function get concatenatedMatrix():Matrix { return content.getTransformationMatrix(content.stage);; } public function get loading():Boolean { return loader != null; } public function get loaded():Boolean { return bitmapData || error; } private function get layer():ILayer { return _layer; } private function get url():String { var level:uint = 18 - getPow(layer.level); var x:int = this.x / expectedWidth / layer.level; var y:int = this.y / expectedHeight / layer.level; var server:String = getServer(Math.abs(x + y) % 3); var result:String = "http://" + server + ".tile.openstreetmap.org/" + level + "/" + x + "/" + y + ".png"; return result; } public function load():void { loader = new Loader; var request:URLRequest = new URLRequest(url); var context:LoaderContext = new LoaderContext(true); loader.load(request, context); var loaderInfo:LoaderInfo = loader.contentLoaderInfo; loaderInfo.addEventListener(Event.COMPLETE, onComplete); loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError); } public function stopLoading():void { if(!loading) return; try { loader.close(); } catch(error:Error){} try { loader.unload(); } catch(error:Error){} var loaderInfo:LoaderInfo = loader.loaderInfo; if(loaderInfo) { loaderInfo.removeEventListener(Event.COMPLETE, onComplete); loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError); } loader = null; } public function applyIBitmapDrawable(source:IBitmapDrawable, matrix:Matrix):void { } public function toString():String { return "Partition: [x:" + x + ", y:" + y + "]"; } public function dispose():void { stopLoading(); bitmapData && bitmapData.dispose(); bitmapData = null; if(content) { Image(content).texture.base.dispose(); Image(content).texture.dispose(); content.dispose(); } } private function getPow(value:uint):uint { var i:uint = 0; while(value > 1) { value /= 2; i++; } return i; } private function getServer(value:uint):String { if(value == 1) return "a"; if(value == 2) return "b"; return "c"; } private function onComplete(event:Event):void { var loaderInfo:LoaderInfo = LoaderInfo(event.target); bitmapData = Bitmap(loaderInfo.content).bitmapData; Image(content).texture = Texture.fromBitmapData(bitmapData); stopLoading(); } private function onError(event:Event):void { error = true; stopLoading(); } } }
package sk.yoz.ycanvas.demo.simple { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.IBitmapDrawable; import flash.display.Loader; import flash.display.LoaderInfo; import flash.events.Event; import flash.events.IOErrorEvent; import flash.geom.Matrix; import flash.net.URLRequest; import flash.system.LoaderContext; import sk.yoz.ycanvas.interfaces.ILayer; import sk.yoz.ycanvas.stage3D.interfaces.IPartitionStage3D; import starling.display.DisplayObject; import starling.display.Image; import starling.textures.Texture; public class Partition implements IPartitionStage3D { private var _x:int; private var _y:int; private var _content:starling.display.DisplayObject; private var _layer:ILayer; private var bitmapData:BitmapData; private var error:Boolean; private var loader:Loader; public function Partition(layer:ILayer, x:int, y:int) { _layer = layer; _x = x; _y = y; _content = new Image(Texture.fromBitmapData(new BitmapData(256, 256, true, 0x0))); content.x = x; content.y = y; } public function get content():starling.display.DisplayObject { return _content; } public function get x():int { return _x; } public function get y():int { return _y; } public function get expectedWidth():uint { return 256; } public function get expectedHeight():uint { return 256; } public function get concatenatedMatrix():Matrix { return content.getTransformationMatrix(content.stage);; } public function get loading():Boolean { return loader != null; } public function get loaded():Boolean { return bitmapData || error; } private function get layer():ILayer { return _layer; } private function get url():String { var level:uint = 18 - getPow(layer.level); var x:int = this.x / expectedWidth / layer.level; var y:int = this.y / expectedHeight / layer.level; var server:String = getServer(Math.abs(x + y) % 3); var result:String = "http://" + server + ".tile.openstreetmap.org/" + level + "/" + x + "/" + y + ".png"; return result; } public function load():void { loader = new Loader; var request:URLRequest = new URLRequest(url); var context:LoaderContext = new LoaderContext(true); loader.load(request, context); var loaderInfo:LoaderInfo = loader.contentLoaderInfo; loaderInfo.addEventListener(Event.COMPLETE, onComplete); loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError); } public function stopLoading():void { if(!loading) return; try { loader.close(); } catch(error:Error){} try { loader.unload(); } catch(error:Error){} var loaderInfo:LoaderInfo = loader.loaderInfo; if(loaderInfo) { loaderInfo.removeEventListener(Event.COMPLETE, onComplete); loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError); } loader = null; } public function applyIBitmapDrawable(source:IBitmapDrawable, matrix:Matrix):void { } public function toString():String { return "Partition: [x:" + x + ", y:" + y + "]"; } public function dispose():void { stopLoading(); bitmapData && bitmapData.dispose(); bitmapData = null; if(content) { Image(content).texture.base.dispose(); Image(content).texture.dispose(); content.dispose(); } } private function getPow(value:uint):uint { var i:uint = 0; while(value > 1) { value /= 2; i++; } return i; } private function getServer(value:uint):String { if(value == 1) return "a"; if(value == 2) return "b"; return "c"; } private function onComplete(event:Event):void { var loaderInfo:LoaderInfo = LoaderInfo(event.target); bitmapData = Bitmap(loaderInfo.content).bitmapData; (content as Image).texture.base.dispose(); (content as Image).texture.dispose(); (content as Image).texture = Texture.fromBitmapData(bitmapData); stopLoading(); } private function onError(event:Event):void { error = true; stopLoading(); } } }
Update ApplicationDemo/src/main/flex/sk/yoz/ycanvas/demo/simple/Partition.as
Update ApplicationDemo/src/main/flex/sk/yoz/ycanvas/demo/simple/Partition.as Memory leak eliminated in case of several map creations and destructions .
ActionScript
mit
wubaodong/YCanvas,jozefchutka/YCanvas,wubaodong/YCanvas
f1ab0ae51b2453106b19e4bf4e0a320835edca25
src/SoundManager2_SMSound_AS3.as
src/SoundManager2_SMSound_AS3.as
/* SoundManager 2: Javascript Sound for the Web ---------------------------------------------- http://schillmania.com/projects/soundmanager2/ Copyright (c) 2007, Scott Schiller. All rights reserved. Code licensed under the BSD License: http://www.schillmania.com/projects/soundmanager2/license.txt Flash 9 / ActionScript 3 version */ package { import flash.external.*; import flash.events.*; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.display.StageScaleMode; import flash.display.StageAlign; import flash.geom.Rectangle; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundLoaderContext; import flash.media.SoundTransform; import flash.media.SoundMixer; import flash.media.Video; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.net.NetConnection; import flash.net.NetStream; public class SoundManager2_SMSound_AS3 extends Sound { public var sm: SoundManager2_AS3 = null; // externalInterface references (for Javascript callbacks) public var baseJSController: String = "soundManager"; public var baseJSObject: String = baseJSController + ".sounds"; public var soundChannel: SoundChannel = new SoundChannel(); public var urlRequest: URLRequest; public var soundLoaderContext: SoundLoaderContext; public var waveformData: ByteArray = new ByteArray(); public var waveformDataArray: Array = []; public var eqData: ByteArray = new ByteArray(); public var eqDataArray: Array = []; public var usePeakData: Boolean = false; public var useWaveformData: Boolean = false; public var useEQData: Boolean = false; public var sID: String; public var sURL: String; public var justBeforeFinishOffset: int; public var didJustBeforeFinish: Boolean; public var didFinish: Boolean; public var loaded: Boolean; public var connected: Boolean; public var failed: Boolean; public var paused: Boolean; public var duration: Number; public var totalBytes: Number; public var handledDataError: Boolean = false; public var ignoreDataError: Boolean = false; public var lastValues: Object = { bytes: 0, position: 0, volume: 100, pan: 0, nLoops: 1, leftPeak: 0, rightPeak: 0, waveformDataArray: null, eqDataArray: null, isBuffering: null }; public var didLoad: Boolean = false; public var sound: Sound = new Sound(); public var cc: Object; public var nc: NetConnection; public var ns: NetStream; public var st: SoundTransform; public var useNetstream: Boolean; public var useVideo: Boolean = false; public var bufferTime: Number = -1; public var lastNetStatus: String = null; public var serverUrl: String = null; public var oVideo: Video = null; public var videoWidth: Number = 0; public var videoHeight: Number = 0; public function SoundManager2_SMSound_AS3(oSoundManager: SoundManager2_AS3, sIDArg: String = null, sURLArg: String = null, usePeakData: Boolean = false, useWaveformData: Boolean = false, useEQData: Boolean = false, useNetstreamArg: Boolean = false, useVideo: Boolean = false, netStreamBufferTime: Number = -1, serverUrl: String = null, duration: Number = 0, totalBytes: Number = 0) { this.sm = oSoundManager; this.sID = sIDArg; this.sURL = sURLArg; this.usePeakData = usePeakData; this.useWaveformData = useWaveformData; this.useEQData = useEQData; this.urlRequest = new URLRequest(sURLArg); this.justBeforeFinishOffset = 0; this.didJustBeforeFinish = false; this.didFinish = false; // non-MP3 formats only this.loaded = false; this.connected = false; this.failed = false; this.soundChannel = null; this.lastNetStatus = null; this.useNetstream = useNetstreamArg; this.serverUrl = serverUrl; this.duration = duration; this.totalBytes = totalBytes; this.useVideo = useVideo; this.bufferTime = netStreamBufferTime; writeDebug('in SoundManager2_SMSound_AS3, got duration '+duration+' and totalBytes '+totalBytes); if (this.useNetstream) { this.cc = new Object(); this.nc = new NetConnection(); // Handle FMS bandwidth check callback. // @see onBWDone // @see http://www.adobe.com/devnet/flashmediaserver/articles/dynamic_stream_switching_04.html // @see http://www.johncblandii.com/index.php/2007/12/fms-a-quick-fix-for-missing-onbwdone-onfcsubscribe-etc.html this.nc.client = this; // TODO: security/IO error handling // this.nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doSecurityError); // this.nc.addEventListener(IOErrorEvent.IO_ERROR, doIOError); nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); writeDebug('Got server URL: '+ this.serverUrl); if (this.serverUrl != null) { writeDebug('NetConnection: connecting to server ' + this.serverUrl + '...'); } this.nc.connect(serverUrl); } else { this.connected = true; } } private function netStatusHandler(event:NetStatusEvent):void { switch (event.info.code) { case "NetConnection.Connect.Success": writeDebug('NetConnection: connected'); try { this.ns = new NetStream(this.nc); this.ns.checkPolicyFile = true; // bufferTime reference: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/NetStream.html#bufferTime if (this.bufferTime != -1) { this.ns.bufferTime = this.bufferTime; // set to 0.1 or higher. 0 is reported to cause playback issues with static files. } this.st = new SoundTransform(); this.cc.onMetaData = this.metaDataHandler; this.ns.client = this.cc; this.ns.receiveAudio(true); if (this.useVideo) { this.oVideo = new Video(); this.ns.receiveVideo(true); this.sm.stage.addEventListener(Event.RESIZE, this.resizeHandler); this.oVideo.smoothing = true; // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html#smoothing this.oVideo.visible = false; // hide until metadata received this.sm.addChild(this.oVideo); this.oVideo.attachNetStream(this.ns); writeDebug('setting video w/h to stage: ' + this.sm.stage.stageWidth + 'x' + this.sm.stage.stageHeight); this.oVideo.width = this.sm.stage.stageWidth; this.oVideo.height = this.sm.stage.stageHeight; } this.connected = true; ExternalInterface.call(this.sm.baseJSObject + "['" + this.sID + "']._onconnect", 1); } catch(e: Error) { this.failed = true; writeDebug('netStream error: ' + e.toString()); } break; case "NetStream.Play.StreamNotFound": this.failed = true; writeDebug("NetConnection: Stream not found!"); break; case "NetConnection.Connect.Closed": this.failed = true; writeDebug("NetConnection: Connection closed!"); break; default: this.failed = true; writeDebug("NetConnection: got unhandled code '" + event.info.code + "'!"); ExternalInterface.call(this.sm.baseJSObject + "['" + this.sID + "']._onconnect", 0); break; } } public function resizeHandler(e: Event) : void { // scale video to stage dimensions // probably less performant than using native flash scaling, but that doesn't quite seem to work. I'm probably missing something simple. this.oVideo.width = this.sm.stage.stageWidth; this.oVideo.height = this.sm.stage.stageHeight; } public function writeDebug(s: String, bTimestamp: Boolean = false) : Boolean { return this.sm.writeDebug(s, bTimestamp); // defined in main SM object } public function doNetStatus(e: NetStatusEvent) : void { writeDebug('netStatusEvent: ' + e.info.code); } public function metaDataHandler(infoObject: Object) : void { /* var data:String = new String(); for (var prop:* in infoObject) { data += prop+': '+infoObject[prop]+' '; } ExternalInterface.call('soundManager._writeDebug','Metadata: '+data); */ if (this.oVideo) { // set dimensions accordingly if (!infoObject.width && !infoObject.height) { writeDebug('No width/height specified'); infoObject.width = 0; infoObject.height = 0; } writeDebug('video dimensions: ' + infoObject.width + 'x' + infoObject.height + ' (w/h)'); this.videoWidth = infoObject.width; this.videoHeight = infoObject.height; // implement a subset of metadata to pass over EI bridge // some formats have extra stuff, eg. "aacaot", "avcprofile" // http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html var oMeta: Object = new Object(); var item: Object = null; for (item in infoObject) { // exclude seekpoints for now, presumed not useful and overly large. if (item != 'seekpoints') { oMeta[item] = infoObject[item]; } } ExternalInterface.call(baseJSObject + "['" + this.sID + "']._onmetadata", oMeta); writeDebug('showing video for ' + this.sID); this.oVideo.visible = true; // show ze video! } if (!this.loaded) { ExternalInterface.call(baseJSObject + "['" + this.sID + "']._whileloading", this.bytesLoaded, (this.bytesTotal || this.totalBytes), (infoObject.duration || this.duration)); } this.duration = infoObject.duration * 1000; // null this out for the duration of this object's existence. // it may be called multiple times. this.cc.onMetaData = function (infoObject: Object) : void {} } public function getWaveformData() : void { // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html#computeSpectrum() SoundMixer.computeSpectrum(this.waveformData, false, 0); // sample wave data at 44.1 KHz this.waveformDataArray = []; for (var i: int = 0, j: int = this.waveformData.length / 4; i < j; i++) { // get all 512 values (256 per channel) this.waveformDataArray.push(int(this.waveformData.readFloat() * 1000) / 1000); } } public function getEQData() : void { // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html#computeSpectrum() SoundMixer.computeSpectrum(this.eqData, true, 0); // sample EQ data at 44.1 KHz this.eqDataArray = []; for (var i: int = 0, j: int = this.eqData.length / 4; i < j; i++) { // get all 512 values (256 per channel) this.eqDataArray.push(int(this.eqData.readFloat() * 1000) / 1000); } } public function start(nMsecOffset: int, nLoops: int) : void { writeDebug("Called start nMsecOffset "+ nMsecOffset+ ' nLoops '+nLoops); this.sm.currentObject = this; // reference for video, full-screen if (this.useNetstream) { writeDebug('start: seeking to ' + nMsecOffset); this.cc.onMetaData = this.metaDataHandler; this.ns.seek(nMsecOffset); if (this.paused) { this.ns.resume(); // get the sound going again if (!this.didLoad) this.didLoad = true; } else if (!this.didLoad) { this.ns.play(this.sURL); this.didLoad = true; } // this.ns.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } else { this.soundChannel = this.play(nMsecOffset, nLoops); this.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } } private function _onfinish() : void { this.removeEventListener(Event.SOUND_COMPLETE, _onfinish); } public function loadSound(sURL: String, bStream: Boolean) : void { if (this.useNetstream) { if (this.didLoad != true) { ExternalInterface.call('loadSound(): loading ' + this.sURL); this.ns.play(this.sURL); this.didLoad = true; } // this.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } else { try { this.didLoad = true; this.urlRequest = new URLRequest(sURL); this.soundLoaderContext = new SoundLoaderContext(1000, true); // check for policy (crossdomain.xml) file on remote domains - http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundLoaderContext.html this.load(this.urlRequest, this.soundLoaderContext); } catch(e: Error) { writeDebug('error during loadSound(): ' + e.toString()); } } } public function setVolume(nVolume: Number) : void { this.lastValues.volume = nVolume / 100; this.applyTransform(); } public function setPan(nPan: Number) : void { this.lastValues.pan = nPan / 100; this.applyTransform(); } public function applyTransform() : void { var st: SoundTransform = new SoundTransform(this.lastValues.volume, this.lastValues.pan); if (this.useNetstream) { this.ns.soundTransform = st; } else if (this.soundChannel) { this.soundChannel.soundTransform = st; // new SoundTransform(this.lastValues.volume, this.lastValues.pan); } } // Handle FMS bandwidth check callback. // @see http://www.adobe.com/devnet/flashmediaserver/articles/dynamic_stream_switching_04.html // @see http://www.johncblandii.com/index.php/2007/12/fms-a-quick-fix-for-missing-onbwdone-onfcsubscribe-etc.html public function onBWDone():void{ writeDebug('onBWDone: called and ignored'); } } }
/* SoundManager 2: Javascript Sound for the Web ---------------------------------------------- http://schillmania.com/projects/soundmanager2/ Copyright (c) 2007, Scott Schiller. All rights reserved. Code licensed under the BSD License: http://www.schillmania.com/projects/soundmanager2/license.txt Flash 9 / ActionScript 3 version */ package { import flash.external.*; import flash.events.*; import flash.display.Sprite; import flash.display.StageDisplayState; import flash.display.StageScaleMode; import flash.display.StageAlign; import flash.geom.Rectangle; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundLoaderContext; import flash.media.SoundTransform; import flash.media.SoundMixer; import flash.media.Video; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.net.NetConnection; import flash.net.NetStream; public class SoundManager2_SMSound_AS3 extends Sound { public var sm: SoundManager2_AS3 = null; // externalInterface references (for Javascript callbacks) public var baseJSController: String = "soundManager"; public var baseJSObject: String = baseJSController + ".sounds"; public var soundChannel: SoundChannel = new SoundChannel(); public var urlRequest: URLRequest; public var soundLoaderContext: SoundLoaderContext; public var waveformData: ByteArray = new ByteArray(); public var waveformDataArray: Array = []; public var eqData: ByteArray = new ByteArray(); public var eqDataArray: Array = []; public var usePeakData: Boolean = false; public var useWaveformData: Boolean = false; public var useEQData: Boolean = false; public var sID: String; public var sURL: String; public var justBeforeFinishOffset: int; public var didJustBeforeFinish: Boolean; public var didFinish: Boolean; public var loaded: Boolean; public var connected: Boolean; public var failed: Boolean; public var paused: Boolean; public var duration: Number; public var totalBytes: Number; public var handledDataError: Boolean = false; public var ignoreDataError: Boolean = false; public var lastValues: Object = { bytes: 0, position: 0, volume: 100, pan: 0, nLoops: 1, leftPeak: 0, rightPeak: 0, waveformDataArray: null, eqDataArray: null, isBuffering: null }; public var didLoad: Boolean = false; public var sound: Sound = new Sound(); public var cc: Object; public var nc: NetConnection; public var ns: NetStream; public var st: SoundTransform; public var useNetstream: Boolean; public var useVideo: Boolean = false; public var bufferTime: Number = -1; public var lastNetStatus: String = null; public var serverUrl: String = null; public var oVideo: Video = null; public var videoWidth: Number = 0; public var videoHeight: Number = 0; public function SoundManager2_SMSound_AS3(oSoundManager: SoundManager2_AS3, sIDArg: String = null, sURLArg: String = null, usePeakData: Boolean = false, useWaveformData: Boolean = false, useEQData: Boolean = false, useNetstreamArg: Boolean = false, useVideo: Boolean = false, netStreamBufferTime: Number = -1, serverUrl: String = null, duration: Number = 0, totalBytes: Number = 0) { this.sm = oSoundManager; this.sID = sIDArg; this.sURL = sURLArg; this.usePeakData = usePeakData; this.useWaveformData = useWaveformData; this.useEQData = useEQData; this.urlRequest = new URLRequest(sURLArg); this.justBeforeFinishOffset = 0; this.didJustBeforeFinish = false; this.didFinish = false; // non-MP3 formats only this.loaded = false; this.connected = false; this.failed = false; this.soundChannel = null; this.lastNetStatus = null; this.useNetstream = useNetstreamArg; this.serverUrl = serverUrl; this.duration = duration; this.totalBytes = totalBytes; this.useVideo = useVideo; this.bufferTime = netStreamBufferTime; writeDebug('in SoundManager2_SMSound_AS3, got duration '+duration+' and totalBytes '+totalBytes); if (this.useNetstream) { this.cc = new Object(); this.nc = new NetConnection(); // Handle FMS bandwidth check callback. // @see onBWDone // @see http://www.adobe.com/devnet/flashmediaserver/articles/dynamic_stream_switching_04.html // @see http://www.johncblandii.com/index.php/2007/12/fms-a-quick-fix-for-missing-onbwdone-onfcsubscribe-etc.html this.nc.client = this; // TODO: security/IO error handling // this.nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doSecurityError); // this.nc.addEventListener(IOErrorEvent.IO_ERROR, doIOError); nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); writeDebug('Got server URL: '+ this.serverUrl); if (this.serverUrl != null) { writeDebug('NetConnection: connecting to server ' + this.serverUrl + '...'); } this.nc.connect(serverUrl); } else { this.connected = true; } } private function netStatusHandler(event:NetStatusEvent):void { switch (event.info.code) { case "NetConnection.Connect.Success": writeDebug('NetConnection: connected'); try { this.ns = new NetStream(this.nc); this.ns.checkPolicyFile = true; // bufferTime reference: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/NetStream.html#bufferTime if (this.bufferTime != -1) { this.ns.bufferTime = this.bufferTime; // set to 0.1 or higher. 0 is reported to cause playback issues with static files. } this.st = new SoundTransform(); this.cc.onMetaData = this.metaDataHandler; this.ns.client = this.cc; this.ns.receiveAudio(true); if (this.useVideo) { this.oVideo = new Video(); this.ns.receiveVideo(true); this.sm.stage.addEventListener(Event.RESIZE, this.resizeHandler); this.oVideo.smoothing = true; // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html#smoothing this.oVideo.visible = false; // hide until metadata received this.sm.addChild(this.oVideo); this.oVideo.attachNetStream(this.ns); writeDebug('setting video w/h to stage: ' + this.sm.stage.stageWidth + 'x' + this.sm.stage.stageHeight); this.oVideo.width = this.sm.stage.stageWidth; this.oVideo.height = this.sm.stage.stageHeight; } this.connected = true; ExternalInterface.call(this.sm.baseJSObject + "['" + this.sID + "']._onconnect", 1); } catch(e: Error) { this.failed = true; writeDebug('netStream error: ' + e.toString()); } break; case "NetStream.Play.StreamNotFound": this.failed = true; writeDebug("NetConnection: Stream not found!"); break; case "NetConnection.Connect.Closed": this.failed = true; writeDebug("NetConnection: Connection closed!"); break; default: this.failed = true; writeDebug("NetConnection: got unhandled code '" + event.info.code + "'!"); ExternalInterface.call(this.sm.baseJSObject + "['" + this.sID + "']._onconnect", 0); break; } } public function resizeHandler(e: Event) : void { // scale video to stage dimensions // probably less performant than using native flash scaling, but that doesn't quite seem to work. I'm probably missing something simple. this.oVideo.width = this.sm.stage.stageWidth; this.oVideo.height = this.sm.stage.stageHeight; } public function writeDebug(s: String, bTimestamp: Boolean = false) : Boolean { return this.sm.writeDebug(s, bTimestamp); // defined in main SM object } public function doNetStatus(e: NetStatusEvent) : void { writeDebug('netStatusEvent: ' + e.info.code); } public function metaDataHandler(infoObject: Object) : void { /* var data:String = new String(); for (var prop:* in infoObject) { data += prop+': '+infoObject[prop]+' '; } ExternalInterface.call('soundManager._writeDebug','Metadata: '+data); */ if (this.oVideo) { // set dimensions accordingly if (!infoObject.width && !infoObject.height) { writeDebug('No width/height specified'); infoObject.width = 0; infoObject.height = 0; } writeDebug('video dimensions: ' + infoObject.width + 'x' + infoObject.height + ' (w/h)'); this.videoWidth = infoObject.width; this.videoHeight = infoObject.height; // implement a subset of metadata to pass over EI bridge // some formats have extra stuff, eg. "aacaot", "avcprofile" // http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000267.html var oMeta: Object = new Object(); var item: Object = null; for (item in infoObject) { // exclude seekpoints for now, presumed not useful and overly large. if (item != 'seekpoints') { oMeta[item] = infoObject[item]; } } ExternalInterface.call(baseJSObject + "['" + this.sID + "']._onmetadata", oMeta); writeDebug('showing video for ' + this.sID); this.oVideo.visible = true; // show ze video! } if (!this.loaded) { ExternalInterface.call(baseJSObject + "['" + this.sID + "']._whileloading", this.bytesLoaded, (this.bytesTotal || this.totalBytes), (infoObject.duration || this.duration)); } this.duration = infoObject.duration * 1000; // null this out for the duration of this object's existence. // it may be called multiple times. this.cc.onMetaData = function (infoObject: Object) : void {} } public function getWaveformData() : void { // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html#computeSpectrum() SoundMixer.computeSpectrum(this.waveformData, false, 0); // sample wave data at 44.1 KHz this.waveformDataArray = []; for (var i: int = 0, j: int = this.waveformData.length / 4; i < j; i++) { // get all 512 values (256 per channel) this.waveformDataArray.push(int(this.waveformData.readFloat() * 1000) / 1000); } } public function getEQData() : void { // http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundMixer.html#computeSpectrum() SoundMixer.computeSpectrum(this.eqData, true, 0); // sample EQ data at 44.1 KHz this.eqDataArray = []; for (var i: int = 0, j: int = this.eqData.length / 4; i < j; i++) { // get all 512 values (256 per channel) this.eqDataArray.push(int(this.eqData.readFloat() * 1000) / 1000); } } public function start(nMsecOffset: int, nLoops: int) : void { writeDebug("Called start nMsecOffset "+ nMsecOffset+ ' nLoops '+nLoops); this.sm.currentObject = this; // reference for video, full-screen if (this.useNetstream) { writeDebug('start: seeking to ' + nMsecOffset); this.cc.onMetaData = this.metaDataHandler; this.ns.seek(nMsecOffset); if (this.paused) { this.ns.resume(); // get the sound going again if (!this.didLoad) this.didLoad = true; } else if (!this.didLoad) { this.ns.play(this.sURL); this.didLoad = true; } // this.ns.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } else { this.soundChannel = this.play(nMsecOffset, nLoops); this.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } } private function _onfinish() : void { this.removeEventListener(Event.SOUND_COMPLETE, _onfinish); } public function loadSound(sURL: String, bStream: Boolean) : void { if (this.useNetstream) { if (this.didLoad != true) { ExternalInterface.call('loadSound(): loading ' + this.sURL); this.ns.play(this.sURL); this.didLoad = true; } // this.addEventListener(Event.SOUND_COMPLETE, _onfinish); this.applyTransform(); } else { try { this.didLoad = true; this.urlRequest = new URLRequest(sURL); this.soundLoaderContext = new SoundLoaderContext(1000, true); // check for policy (crossdomain.xml) file on remote domains - http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/SoundLoaderContext.html this.load(this.urlRequest, this.soundLoaderContext); } catch(e: Error) { writeDebug('error during loadSound(): ' + e.toString()); } } } public function setVolume(nVolume: Number) : void { this.lastValues.volume = nVolume / 100; this.applyTransform(); } public function setPan(nPan: Number) : void { this.lastValues.pan = nPan / 100; this.applyTransform(); } public function applyTransform() : void { var st: SoundTransform = new SoundTransform(this.lastValues.volume, this.lastValues.pan); if (this.useNetstream) { this.ns.soundTransform = st; } else if (this.soundChannel) { this.soundChannel.soundTransform = st; // new SoundTransform(this.lastValues.volume, this.lastValues.pan); } } // Handle FMS bandwidth check callback. // @see http://www.adobe.com/devnet/flashmediaserver/articles/dynamic_stream_switching_04.html // @see http://www.johncblandii.com/index.php/2007/12/fms-a-quick-fix-for-missing-onbwdone-onfcsubscribe-etc.html public function onBWDone():void{ writeDebug('onBWDone: called and ignored'); } // NetStream client callback. Invoked when the song is complete public function onPlayStatus(info:Object):void { writeDebug('onPlayStatus called with '+info); switch(info.code) { case "NetStream.Play.Complete": writeDebug('Song has finished!'); break; } } } }
Add an onPlayStatus method to capture the callback...but it's never called.
Add an onPlayStatus method to capture the callback...but it's never called.
ActionScript
bsd-3-clause
Shinobi881/SoundManager2,usergit/SoundManager2,thecocce/SoundManager2,oceanho/SoundManager2,Zarel/SoundManager2,ali2mdj/SoundManager2,2947721120/SoundManager2,kyroskoh/SoundManager2,relax/SoundManager2,Nona-Creative/SoundManager2,Zarel/SoundManager2,usergit/SoundManager2,Erbolking/SoundManager2,snowman1ng/SoundManager2-Seek-Reverse,snowman1ng/SoundManager2-Seek-Reverse,minorgod/SoundManager2,minorgod/SoundManager2,usergit/SoundManager2,kidaa/SoundManager2,kyroskoh/SoundManager2,2947721120/SoundManager2,thecocce/SoundManager2,josephsavona/SoundManager2,josephsavona/SoundManager2,minorgod/SoundManager2,thecocce/SoundManager2,Shinobi881/SoundManager2,snowman1ng/SoundManager2-Seek-Reverse,ubergrafik/SoundManager2,oceanho/SoundManager2,oceanho/SoundManager2,tchoulihan/SoundManager2,kidaa/SoundManager2,ali2mdj/SoundManager2,relax/SoundManager2,ubergrafik/SoundManager2,tchoulihan/SoundManager2,Nona-Creative/SoundManager2,kidaa/SoundManager2,ali2mdj/SoundManager2,acchoblues/SoundManager2,acchoblues/SoundManager2,2947721120/SoundManager2,ubergrafik/SoundManager2,tchoulihan/SoundManager2,Erbolking/SoundManager2,Erbolking/SoundManager2,relax/SoundManager2,Nona-Creative/SoundManager2,kyroskoh/SoundManager2,Shinobi881/SoundManager2
f42b008df2451cbad8bafe2c2c5a851e4bd5ed84
exporter/src/main/as/flump/xfl/XflLayer.as
exporter/src/main/as/flump/xfl/XflLayer.as
// // Flump - Copyright 2013 Flump Authors package flump.xfl { import aspire.util.XmlUtil; import flump.mold.KeyframeMold; import flump.mold.LayerMold; public class XflLayer { public static const NAME :String = "name"; public static const TYPE :String = "layerType"; public static const TYPE_GUIDE :String = "guide"; public static const TYPE_FOLDER :String = "folder"; public static const TYPE_MASK :String = "mask"; use namespace xflns; public static function parse (lib :XflLibrary, baseLocation :String, xml :XML, flipbook :Boolean,mask:String=null) :LayerMold { const layer :LayerMold = new LayerMold(); layer.name = XmlUtil.getStringAttr(xml, NAME); layer.flipbook = flipbook; // mask if (mask!=null) layer.mask = mask; const location :String = baseLocation + ":" + layer.name; var frameXmlList :XMLList = xml.frames.DOMFrame; for each (var frameXml :XML in frameXmlList) { layer.keyframes.push(XflKeyframe.parse(lib, location, frameXml, flipbook)); } if (layer.keyframes.length == 0) lib.addError(location, ParseError.INFO, "No keyframes on layer"); var ii :int; var kf :KeyframeMold; var nextKf :KeyframeMold; // normalize skews, so that we always skew the shortest distance between // two angles (we don't want to skew more than Math.PI) for (ii = 0; ii < layer.keyframes.length - 1; ++ii) { kf = layer.keyframes[ii]; nextKf = layer.keyframes[ii+1]; frameXml = frameXmlList[ii]; if (kf.skewX + Math.PI < nextKf.skewX) { nextKf.skewX += -Math.PI * 2; } else if (kf.skewX - Math.PI > nextKf.skewX) { nextKf.skewX += Math.PI * 2; } if (kf.skewY + Math.PI < nextKf.skewY) { nextKf.skewY += -Math.PI * 2; } else if (kf.skewY - Math.PI > nextKf.skewY) { nextKf.skewY += Math.PI * 2; } } // apply additional rotations var additionalRotation :Number = 0; for (ii = 0; ii < layer.keyframes.length - 1; ++ii) { kf = layer.keyframes[ii]; nextKf = layer.keyframes[ii+1]; frameXml = frameXmlList[ii]; var motionTweenRotate :String = XmlUtil.getStringAttr(frameXml, XflKeyframe.MOTION_TWEEN_ROTATE, XflKeyframe.MOTION_TWEEN_ROTATE_NONE); // If a direction is specified, take it into account if (motionTweenRotate != XflKeyframe.MOTION_TWEEN_ROTATE_NONE) { var direction :Number = (motionTweenRotate == XflKeyframe.MOTION_TWEEN_ROTATE_CLOCKWISE ? 1 : -1); // negative scales affect rotation direction direction *= sign(nextKf.scaleX) * sign(nextKf.scaleY); while (direction < 0 && kf.skewX < nextKf.skewX) { nextKf.skewX -= Math.PI * 2; } while (direction > 0 && kf.skewX > nextKf.skewX) { nextKf.skewX += Math.PI * 2; } while (direction < 0 && kf.skewY < nextKf.skewY) { nextKf.skewY -= Math.PI * 2; } while (direction > 0 && kf.skewY > nextKf.skewY) { nextKf.skewY += Math.PI * 2; } // additional rotations specified? var motionTweenRotateTimes :Number = XmlUtil.getNumberAttr(frameXml, XflKeyframe.MOTION_TWEEN_ROTATE_TIMES, 0); var thisRotation :Number = motionTweenRotateTimes * Math.PI * 2 * direction; additionalRotation += thisRotation; } nextKf.rotate(additionalRotation); } return layer; } protected static function sign (n :Number) :Number { return (n > 0 ? 1 : (n < 0 ? -1 : 0)); } } }
// // Flump - Copyright 2013 Flump Authors package flump.xfl { import aspire.util.XmlUtil; import flump.mold.KeyframeMold; import flump.mold.LayerMold; public class XflLayer { public static const NAME :String = "name"; public static const TYPE :String = "layerType"; public static const TYPE_GUIDE :String = "guide"; public static const TYPE_FOLDER :String = "folder"; public static const TYPE_MASK :String = "mask"; use namespace xflns; public static function parse (lib :XflLibrary, baseLocation :String, xml :XML, flipbook :Boolean) :LayerMold { const layer :LayerMold = new LayerMold(); layer.name = XmlUtil.getStringAttr(xml, NAME); layer.flipbook = flipbook; // mask if (mask!=null) layer.mask = mask; const location :String = baseLocation + ":" + layer.name; var frameXmlList :XMLList = xml.frames.DOMFrame; for each (var frameXml :XML in frameXmlList) { layer.keyframes.push(XflKeyframe.parse(lib, location, frameXml, flipbook)); } if (layer.keyframes.length == 0) lib.addError(location, ParseError.INFO, "No keyframes on layer"); var ii :int; var kf :KeyframeMold; var nextKf :KeyframeMold; // normalize skews, so that we always skew the shortest distance between // two angles (we don't want to skew more than Math.PI) for (ii = 0; ii < layer.keyframes.length - 1; ++ii) { kf = layer.keyframes[ii]; nextKf = layer.keyframes[ii+1]; frameXml = frameXmlList[ii]; if (kf.skewX + Math.PI < nextKf.skewX) { nextKf.skewX += -Math.PI * 2; } else if (kf.skewX - Math.PI > nextKf.skewX) { nextKf.skewX += Math.PI * 2; } if (kf.skewY + Math.PI < nextKf.skewY) { nextKf.skewY += -Math.PI * 2; } else if (kf.skewY - Math.PI > nextKf.skewY) { nextKf.skewY += Math.PI * 2; } } // apply additional rotations var additionalRotation :Number = 0; for (ii = 0; ii < layer.keyframes.length - 1; ++ii) { kf = layer.keyframes[ii]; nextKf = layer.keyframes[ii+1]; frameXml = frameXmlList[ii]; var motionTweenRotate :String = XmlUtil.getStringAttr(frameXml, XflKeyframe.MOTION_TWEEN_ROTATE, XflKeyframe.MOTION_TWEEN_ROTATE_NONE); // If a direction is specified, take it into account if (motionTweenRotate != XflKeyframe.MOTION_TWEEN_ROTATE_NONE) { var direction :Number = (motionTweenRotate == XflKeyframe.MOTION_TWEEN_ROTATE_CLOCKWISE ? 1 : -1); // negative scales affect rotation direction direction *= sign(nextKf.scaleX) * sign(nextKf.scaleY); while (direction < 0 && kf.skewX < nextKf.skewX) { nextKf.skewX -= Math.PI * 2; } while (direction > 0 && kf.skewX > nextKf.skewX) { nextKf.skewX += Math.PI * 2; } while (direction < 0 && kf.skewY < nextKf.skewY) { nextKf.skewY -= Math.PI * 2; } while (direction > 0 && kf.skewY > nextKf.skewY) { nextKf.skewY += Math.PI * 2; } // additional rotations specified? var motionTweenRotateTimes :Number = XmlUtil.getNumberAttr(frameXml, XflKeyframe.MOTION_TWEEN_ROTATE_TIMES, 0); var thisRotation :Number = motionTweenRotateTimes * Math.PI * 2 * direction; additionalRotation += thisRotation; } nextKf.rotate(additionalRotation); } return layer; } protected static function sign (n :Number) :Number { return (n > 0 ? 1 : (n < 0 ? -1 : 0)); } } }
Revert "fix XflLayer parse signature"
Revert "fix XflLayer parse signature" This reverts commit 47388cac329edc12b6a57798a59f27b37b2923b1.
ActionScript
mit
mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump
abc8f42f6a2e5e39bf7daee869b6aa618a567a7a
common1/src/nt/lib/util/assert.as
common1/src/nt/lib/util/assert.as
package nt.lib.util { import flash.system.Capabilities; [Inline] public function assert(b:Boolean, m:String = "", errorClass:Class = null):void { if (Capabilities.isDebugger) { if (!b) { throw new (errorClass ||= Error)(m); } } } }
package nt.lib.util { import flash.system.Capabilities; /** *debug异常抛出类 *@param b 值为flase则抛出异常 *@param m 如果错误类为空则抛出该错误信息 *@param errorClass 错误类 */ [Inline] public function assert(b:Boolean, m:String = "", errorClass:Class = null):void { if (Capabilities.isDebugger) { if (!b) { throw new (errorClass ||= Error)(m); } } } }
add annotate
add annotate
ActionScript
mit
nexttouches/age_client
777adf453e6198d4595af1491104c812d9ef5de2
src/aerys/minko/render/DrawCall.as
src/aerys/minko/render/DrawCall.as
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _center : Vector4 = null; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; private var _bindingsConsumer : DrawCallBindingsConsumer; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (_bindingsConsumer) _bindingsConsumer.enabled = value; } public function get depth() : Number { if (_invalidDepth && _enabled) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( _center, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { _invalidDepth = computeDepth; setProgram(program); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { if (_bindingsConsumer != null) { meshBindings.removeConsumer(_bindingsConsumer); sceneBindings.removeConsumer(_bindingsConsumer); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.slice(); _fsConstants = program._fsConstants.slice(); _fsTextures = program._fsTextures.slice(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; _bindingsConsumer = new DrawCallBindingsConsumer( _bindings, _cpuConstants, _vsConstants, _fsConstants, _fsTextures ); _bindingsConsumer.enabled = _enabled; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; var hasNormals : Boolean = vertexFormat.hasComponent(VertexComponent.NORMAL); if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(!hasNormals); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !hasNormals) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { if (!_vsInputComponents) return ; updateGeometry(geometry); _center = geometry.boundingSphere ? geometry.boundingSphere.center : Vector4.ZERO; _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { meshBindings.addConsumer(_bindingsConsumer); sceneBindings.addConsumer(_bindingsConsumer); if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { _bindingsConsumer.setProperty(name, value); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _center : Vector4 = null; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; private var _bindingsConsumer : DrawCallBindingsConsumer; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (_bindingsConsumer) _bindingsConsumer.enabled = value; } public function get depth() : Number { if (_invalidDepth && _enabled) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( _center, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { _invalidDepth = computeDepth; setProgram(program); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { if (_bindingsConsumer != null) { meshBindings.removeConsumer(_bindingsConsumer); sceneBindings.removeConsumer(_bindingsConsumer); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); _bindingsConsumer = null; } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.slice(); _fsConstants = program._fsConstants.slice(); _fsTextures = program._fsTextures.slice(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; _bindingsConsumer = new DrawCallBindingsConsumer( _bindings, _cpuConstants, _vsConstants, _fsConstants, _fsTextures ); _bindingsConsumer.enabled = _enabled; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; var hasNormals : Boolean = vertexFormat.hasComponent(VertexComponent.NORMAL); if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(!hasNormals); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !hasNormals) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { if (!_vsInputComponents) return ; updateGeometry(geometry); _center = geometry.boundingSphere ? geometry.boundingSphere.center : Vector4.ZERO; _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { meshBindings.addConsumer(_bindingsConsumer); sceneBindings.addConsumer(_bindingsConsumer); if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { _bindingsConsumer.setProperty(name, value); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
set _bindingConsumer to null when the bindings are unset
set _bindingConsumer to null when the bindings are unset
ActionScript
mit
aerys/minko-as3
80ba685b325595f957eb25b57dc138e69ce62e1d
frameworks/projects/spark/src/spark/utils/MultiDPIBitmapSource.as
frameworks/projects/spark/src/spark/utils/MultiDPIBitmapSource.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.utils { import mx.core.DPIClassification; /** * This class provides a list of bitmaps for various runtime densities. It is supplied * as the source to BitmapImage or Image and as the icon of a Button. The components * will use the Application.runtimeDPI to choose which image to display. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public class MultiDPIBitmapSource { include "../core/Version.as"; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_120</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion ApacheFlex 4.11 */ public var source120dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_160</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public var source160dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_240</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public var source240dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_320</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public var source320dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_480</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion ApacheFlex 4.10 */ public var source640dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_640</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion ApacheFlex 4.11 */ public var source640dpi:Object; /** * Select one of the sourceXXXdpi properties based on the given DPI. This * function handles the fallback to different sourceXXXdpi properties * if the given one is null. * The strategy is to try to choose the next highest * property if it is not null, then return a lower property if not null, then * just return null. * * @param The desired DPI. * * @return One of the sourceXXXdpi properties based on the desired DPI. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public function getSource(desiredDPI:Number):Object { var source:Object = source160dpi; switch (desiredDPI) { case DPIClassification.DPI_640: source = source640dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_480: source = source480dpi; if (!source || source == "") source = source640dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_320: source = source320dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source640dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_240: source = source240dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source640dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_160: source = source160dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source640dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_120: source = source120dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source640dpi; break; } return source; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.utils { import mx.core.DPIClassification; /** * This class provides a list of bitmaps for various runtime densities. It is supplied * as the source to BitmapImage or Image and as the icon of a Button. The components * will use the Application.runtimeDPI to choose which image to display. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public class MultiDPIBitmapSource { include "../core/Version.as"; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_120</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion ApacheFlex 4.11 */ public var source120dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_160</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public var source160dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_240</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public var source240dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_320</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public var source320dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_480</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion ApacheFlex 4.10 */ public var source480dpi:Object; /** * The source to use if the <code>Application.runtimeDPI</code> * is <code>DPIClassification.DPI_640</code>. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion ApacheFlex 4.11 */ public var source640dpi:Object; /** * Select one of the sourceXXXdpi properties based on the given DPI. This * function handles the fallback to different sourceXXXdpi properties * if the given one is null. * The strategy is to try to choose the next highest * property if it is not null, then return a lower property if not null, then * just return null. * * @param The desired DPI. * * @return One of the sourceXXXdpi properties based on the desired DPI. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Flex 4.5 */ public function getSource(desiredDPI:Number):Object { var source:Object = source160dpi; switch (desiredDPI) { case DPIClassification.DPI_640: source = source640dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_480: source = source480dpi; if (!source || source == "") source = source640dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_320: source = source320dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source640dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_240: source = source240dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source640dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_160: source = source160dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source640dpi; if (!source || source == "") source = source120dpi; break; case DPIClassification.DPI_120: source = source120dpi; if (!source || source == "") source = source160dpi; if (!source || source == "") source = source240dpi; if (!source || source == "") source = source320dpi; if (!source || source == "") source = source480dpi; if (!source || source == "") source = source640dpi; break; } return source; } } }
fix 480 dpi bitmap source
fix 480 dpi bitmap source
ActionScript
apache-2.0
adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk
e7132a127f5a76e2ced598ad1702764ef0243ac7
src/as/com/threerings/flex/CommandComboBox.as
src/as/com/threerings/flex/CommandComboBox.as
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.flex { import flash.events.Event; import mx.controls.ComboBox; import mx.events.ListEvent; import com.threerings.util.CommandEvent; import com.threerings.util.Util; /** * A combo box that dispatches a command (or calls a callback) when an item is selected. * The argument will be the 'data' value of the selected item. * NOTE: Unlike the other Command* controls, CommandComboBox allows a null cmd/callback * to be specified. */ public class CommandComboBox extends ComboBox { /** The field of the selectedItem object used as the 'data'. If this property is null, * then the item is the data. */ public var dataField :String = "data"; /** * Create a command combobox. * * @param cmdOrFn either a String, which will be the CommandEvent command to dispatch, * or a function, which will be called when changed. */ public function CommandComboBox (cmdOrFn :* = null) { CommandButton.validateCmd(cmdOrFn); _cmdOrFn = cmdOrFn; addEventListener(ListEvent.CHANGE, handleChange, false, int.MIN_VALUE); } /** * Set the command and argument to be issued when this button is pressed. */ public function setCommand (cmd :String) :void { _cmdOrFn = cmd; } /** * Set a callback function to call when the button is pressed. */ public function setCallback (fn :Function) :void { _cmdOrFn = fn; } /** * Set the selectedItem based on the data field. */ public function set selectedData (data :Object) :void { for (var ii :int = 0; ii < dataProvider.length; ++ii) { if (Util.equals(data, itemToData(dataProvider[ii]))) { this.selectedIndex = ii; return; } } // not found, clear the selection this.selectedIndex = -1; } /** * The value that will be passed to the command or function based on dataField and the * current selected item. */ public function get selectedData () :Object { return itemToData(this.selectedItem); } /** * Extract the data from the specified item. This can be expanded in the future * if we provide a 'dataFunction'. */ protected function itemToData (item :Object) :Object { return (item == null || dataField == null) ? item : item[dataField]; } protected function handleChange (event :ListEvent) :void { if (_cmdOrFn != null && this.selectedIndex != -1) { CommandEvent.dispatch(this, _cmdOrFn, selectedData); } } /** The command (String) to submit, or the function (Function) to call * when changed, */ protected var _cmdOrFn :Object; } }
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.flex { import flash.events.Event; import mx.controls.ComboBox; import mx.events.ListEvent; import com.threerings.util.CommandEvent; import com.threerings.util.Util; /** * A combo box that dispatches a command (or calls a callback) when an item is selected. * The argument will be the 'data' value of the selected item. * NOTE: Unlike the other Command* controls, CommandComboBox allows a null cmd/callback * to be specified. */ public class CommandComboBox extends ComboBox { /** The field of the selectedItem object used as the 'data'. If this property is null, * then the item is the data. */ public var dataField :String = "data"; /** * Create a command combobox. * * @param cmdOrFn either a String, which will be the CommandEvent command to dispatch, * or a function, which will be called when changed. */ public function CommandComboBox (cmdOrFn :* = null) { CommandButton.validateCmd(cmdOrFn); _cmdOrFn = cmdOrFn; addEventListener(ListEvent.CHANGE, handleChange, false, int.MIN_VALUE); } /** * Set the command and argument to be issued when this button is pressed. */ public function setCommand (cmd :String) :void { _cmdOrFn = cmd; } /** * Set a callback function to call when the button is pressed. */ public function setCallback (fn :Function) :void { _cmdOrFn = fn; } /** * Set the selectedItem based on the data field. */ public function set selectedData (data :Object) :void { for (var ii :int = 0; ii < dataProvider.length; ++ii) { if (Util.equals(data, itemToData(dataProvider[ii]))) { this.selectedIndex = ii; return; } } // not found, clear the selection this.selectedIndex = -1; } /** * The value that will be passed to the command or function based on dataField and the * current selected item. */ public function get selectedData () :Object { return itemToData(this.selectedItem); } /** * Extract the data from the specified item. This can be expanded in the future * if we provide a 'dataFunction'. */ protected function itemToData (item :Object) :Object { if (item != null && dataField != null) { try { return item[dataField]; } catch (re :ReferenceError) { // fallback to just returning the item } } return item; } protected function handleChange (event :ListEvent) :void { if (_cmdOrFn != null && this.selectedIndex != -1) { CommandEvent.dispatch(this, _cmdOrFn, selectedData); } } /** The command (String) to submit, or the function (Function) to call * when changed, */ protected var _cmdOrFn :Object; } }
Fix for when the items don't have a 'data' property.
Fix for when the items don't have a 'data' property. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@756 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
d713f8a221ebf954255ed7d0a2bc3900a5ecbf7f
examples/web/app/classes/server/FMSClient.as
examples/web/app/classes/server/FMSClient.as
package server { dynamic public class FMSClient extends Object { public function FMSClient() { super(); } public function onRegisterUser(user:String, result:Object):void { trace('FMSClient.onRegisterUser:', user, result); } public function onStartGame(user:String):void { trace('FMSClient.onStartGame:', user); } public function onChangePlayer(user:String, player:uint):void { trace('FMSClient.onChangePlayer:', user, player); } public function onDisconnect(user:String):void { trace('FMSClient.onDisconnect:', user); } } }
package server { dynamic public class FMSClient extends Object { public function FMSClient() { super(); } public function onRegisterUser(user:String, result:Object):void { trace('FMSClient.onRegisterUser:', user, result); } public function onSigninUser(user:String, result:Object):void { trace('FMSClient.onSigninUser:', user, result); } public function onStartGame(user:String):void { trace('FMSClient.onStartGame:', user); } public function onChangePlayer(user:String, player:uint):void { trace('FMSClient.onChangePlayer:', user, player); } public function onDisconnect(user:String):void { trace('FMSClient.onDisconnect:', user); } } }
Update FMSClient.as
Update FMSClient.as
ActionScript
apache-2.0
adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler
d63b447b614c8ac83aebccf34150e1fafb7c2d07
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSValuesImpl.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleCSSValuesImpl.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.system.ApplicationDomain; import flash.utils.getQualifiedClassName; import flash.utils.getQualifiedSuperclassName; import flash.utils.getDefinitionByName; import org.apache.flex.events.ValueChangeEvent; import org.apache.flex.events.EventDispatcher; public class SimpleCSSValuesImpl extends EventDispatcher implements IValuesImpl { public function SimpleCSSValuesImpl() { super(); } private var mainClass:Object; private var conditionCombiners:Object; public function init(mainClass:Object):void { var styleClassName:String; var c:Class; if (!values) { values = {}; this.mainClass = mainClass; var mainClassName:String = getQualifiedClassName(mainClass); styleClassName = "_" + mainClassName + "_Styles"; c = ApplicationDomain.currentDomain.getDefinition(styleClassName) as Class; } else { var className:String = getQualifiedClassName(mainClass); c = ApplicationDomain.currentDomain.getDefinition(className) as Class; } generateCSSStyleDeclarations(c["factoryFunctions"], c["data"]); } public function generateCSSStyleDeclarations(factoryFunctions:Object, arr:Array):void { if (factoryFunctions == null) return; if (arr == null) return; var declarationName:String = ""; var segmentName:String = ""; var n:int = arr.length; for (var i:int = 0; i < n; i++) { var className:int = arr[i]; if (className == CSSClass.CSSSelector) { var selectorName:String = arr[++i]; segmentName = selectorName + segmentName; if (declarationName != "") declarationName += " "; declarationName += segmentName; segmentName = ""; } else if (className == CSSClass.CSSCondition) { if (!conditionCombiners) { conditionCombiners = {}; conditionCombiners["class"] = "."; conditionCombiners["id"] = "#"; conditionCombiners["pseudo"] = ':'; } var conditionType:String = arr[++i]; var conditionName:String = arr[++i]; segmentName = segmentName + conditionCombiners[conditionType] + conditionName; } else if (className == CSSClass.CSSStyleDeclaration) { var factoryName:int = arr[++i]; // defaultFactory or factory var defaultFactory:Boolean = factoryName == CSSFactory.DefaultFactory; /* if (defaultFactory) { mergedStyle = styleManager.getMergedStyleDeclaration(declarationName); style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); } else { style = styleManager.getStyleDeclaration(declarationName); if (!style) { style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); if (factoryName == CSSFactory.Override) newSelectors.push(style); } } */ var finalName:String; var valuesFunction:Function; var valuesObject:Object; if (defaultFactory) { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); finalName = fixNames(declarationName); values[finalName] = valuesObject; } else { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); var o:Object = values[declarationName]; finalName = fixNames(declarationName); if (o == null) values[finalName] = valuesObject; else { valuesFunction.prototype = o; values[finalName] = new valuesFunction(); } } declarationName = ""; } } } private function fixNames(s:String):String { if (s == "") return "*"; var arr:Array = s.split(" "); var n:int = arr.length; for (var i:int = 0; i < n; i++) { var segmentName:String = arr[i]; if (segmentName.charAt(0) == "#" || segmentName.charAt(0) == ".") continue; var c:int = segmentName.lastIndexOf("."); if (c > -1) // it is 0 for class selectors { segmentName = segmentName.substr(0, c) + "::" + segmentName.substr(c + 1); arr[i] = segmentName; } } return arr.join(" "); } public var values:Object; public function getValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):* { var c:int = valueName.indexOf("-"); while (c != -1) { valueName = valueName.substr(0, c) + valueName.charAt(c + 1).toUpperCase() + valueName.substr(c + 2); c = valueName.indexOf("-"); } var value:*; var o:Object; var className:String; var selectorName:String; if ("className" in thisObject) { className = thisObject.className; if (state) { selectorName = className + ":" + state; o = values["." + selectorName]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } o = values["." + className]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } className = getQualifiedClassName(thisObject); while (className != "Object") { if (state) { selectorName = className + ":" + state; o = values[selectorName]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } o = values[className]; if (o) { value = o[valueName]; if (value !== undefined) return value; } className = getQualifiedSuperclassName(thisObject); thisObject = getDefinitionByName(className); } o = values["global"]; if (o) { value = o[valueName]; if (value !== undefined) return value; } o = values["*"]; if(o) { return o[valueName]; } return null; } public function setValue(thisObject:Object, valueName:String, value:*):void { var c:int = valueName.indexOf("-"); while (c != -1) { valueName = valueName.substr(0, c) + valueName.charAt(c + 1).toUpperCase() + valueName..substr(c + 2); c = valueName.indexOf("-"); } var oldValue:Object = values[valueName]; if (oldValue != value) { values[valueName] = value; dispatchEvent(new ValueChangeEvent(ValueChangeEvent.VALUE_CHANGE, false, false, oldValue, value)); } } public function getInstance(valueName:String):Object { var o:Object = values["global"]; if (o is Class) { o[valueName] = new o[valueName](); if (o[valueName] is IDocument) o[valueName].setDocument(mainClass); } return o[valueName]; } } } class CSSClass { public static const CSSSelector:int = 0; public static const CSSCondition:int = 1; public static const CSSStyleDeclaration:int = 2; } class CSSFactory { public static const DefaultFactory:int = 0; public static const Factory:int = 1; public static const Override:int = 2; } class CSSDataType { public static const Native:int = 0; public static const Definition:int = 1; }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.core { import flash.system.ApplicationDomain; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; import flash.utils.getQualifiedSuperclassName; import org.apache.flex.events.EventDispatcher; import org.apache.flex.events.ValueChangeEvent; public class SimpleCSSValuesImpl extends EventDispatcher implements IValuesImpl { public function SimpleCSSValuesImpl() { super(); } private var mainClass:Object; private var conditionCombiners:Object; public function init(mainClass:Object):void { var styleClassName:String; var c:Class; if (!values) { values = {}; this.mainClass = mainClass; var mainClassName:String = getQualifiedClassName(mainClass); styleClassName = "_" + mainClassName + "_Styles"; c = ApplicationDomain.currentDomain.getDefinition(styleClassName) as Class; } else { var className:String = getQualifiedClassName(mainClass); c = ApplicationDomain.currentDomain.getDefinition(className) as Class; } generateCSSStyleDeclarations(c["factoryFunctions"], c["data"]); } public function generateCSSStyleDeclarations(factoryFunctions:Object, arr:Array):void { if (factoryFunctions == null) return; if (arr == null) return; var declarationName:String = ""; var segmentName:String = ""; var n:int = arr.length; for (var i:int = 0; i < n; i++) { var className:int = arr[i]; if (className == CSSClass.CSSSelector) { var selectorName:String = arr[++i]; segmentName = selectorName + segmentName; if (declarationName != "") declarationName += " "; declarationName += segmentName; segmentName = ""; } else if (className == CSSClass.CSSCondition) { if (!conditionCombiners) { conditionCombiners = {}; conditionCombiners["class"] = "."; conditionCombiners["id"] = "#"; conditionCombiners["pseudo"] = ':'; } var conditionType:String = arr[++i]; var conditionName:String = arr[++i]; segmentName = segmentName + conditionCombiners[conditionType] + conditionName; } else if (className == CSSClass.CSSStyleDeclaration) { var factoryName:int = arr[++i]; // defaultFactory or factory var defaultFactory:Boolean = factoryName == CSSFactory.DefaultFactory; /* if (defaultFactory) { mergedStyle = styleManager.getMergedStyleDeclaration(declarationName); style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); } else { style = styleManager.getStyleDeclaration(declarationName); if (!style) { style = new CSSStyleDeclaration(selector, styleManager, mergedStyle == null); if (factoryName == CSSFactory.Override) newSelectors.push(style); } } */ var mq:String = null; var o:Object; if (i < n - 2) { // peek ahead to see if there is a media query if (arr[i + 1] == CSSClass.CSSMediaQuery) { mq = arr[i + 2]; i += 2; declarationName = mq + "_" + declarationName; } } var finalName:String; var valuesFunction:Function; var valuesObject:Object; if (defaultFactory) { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); } else { valuesFunction = factoryFunctions[declarationName]; valuesObject = new valuesFunction(); } if (isValidStaticMediaQuery(mq)) { finalName = fixNames(declarationName, mq); o = values[finalName]; if (o == null) values[finalName] = valuesObject; else { valuesFunction.prototype = o; values[finalName] = new valuesFunction(); } } declarationName = ""; } } } private function isValidStaticMediaQuery(mq:String):Boolean { if (mq == null) return true; if (mq == "-flex-flash") return true; // TODO: (aharui) other media query return false; } private function fixNames(s:String, mq:String):String { if (mq != null) s = s.substr(mq.length + 1); // 1 more for the hyphen if (s == "") return "*"; var arr:Array = s.split(" "); var n:int = arr.length; for (var i:int = 0; i < n; i++) { var segmentName:String = arr[i]; if (segmentName.charAt(0) == "#" || segmentName.charAt(0) == ".") continue; var c:int = segmentName.lastIndexOf("."); if (c > -1) // it is 0 for class selectors { segmentName = segmentName.substr(0, c) + "::" + segmentName.substr(c + 1); arr[i] = segmentName; } } return arr.join(" "); } public var values:Object; public function getValue(thisObject:Object, valueName:String, state:String = null, attrs:Object = null):* { var c:int = valueName.indexOf("-"); while (c != -1) { valueName = valueName.substr(0, c) + valueName.charAt(c + 1).toUpperCase() + valueName.substr(c + 2); c = valueName.indexOf("-"); } var value:*; var o:Object; var className:String; var selectorName:String; if ("className" in thisObject) { className = thisObject.className; if (state) { selectorName = className + ":" + state; o = values["." + selectorName]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } o = values["." + className]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } className = getQualifiedClassName(thisObject); while (className != "Object") { if (state) { selectorName = className + ":" + state; o = values[selectorName]; if (o) { value = o[valueName]; if (value !== undefined) return value; } } o = values[className]; if (o) { value = o[valueName]; if (value !== undefined) return value; } className = getQualifiedSuperclassName(thisObject); thisObject = getDefinitionByName(className); } o = values["global"]; if (o) { value = o[valueName]; if (value !== undefined) return value; } o = values["*"]; if(o) { return o[valueName]; } return null; } public function setValue(thisObject:Object, valueName:String, value:*):void { var c:int = valueName.indexOf("-"); while (c != -1) { valueName = valueName.substr(0, c) + valueName.charAt(c + 1).toUpperCase() + valueName..substr(c + 2); c = valueName.indexOf("-"); } var oldValue:Object = values[valueName]; if (oldValue != value) { values[valueName] = value; dispatchEvent(new ValueChangeEvent(ValueChangeEvent.VALUE_CHANGE, false, false, oldValue, value)); } } public function getInstance(valueName:String):Object { var o:Object = values["global"]; if (o is Class) { o[valueName] = new o[valueName](); if (o[valueName] is IDocument) o[valueName].setDocument(mainClass); } return o[valueName]; } } } class CSSClass { public static const CSSSelector:int = 0; public static const CSSCondition:int = 1; public static const CSSStyleDeclaration:int = 2; public static const CSSMediaQuery:int = 3; } class CSSFactory { public static const DefaultFactory:int = 0; public static const Factory:int = 1; public static const Override:int = 2; } class CSSDataType { public static const Native:int = 0; public static const Definition:int = 1; }
add limited media query check for -flex-flash. More MQ processing needed eventually
add limited media query check for -flex-flash. More MQ processing needed eventually
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
5b82579d738c39f961f291dd75c848334fac5f73
as3/xobjas3/src/com/rpath/xobj/FilterTerm.as
as3/xobjas3/src/com/rpath/xobj/FilterTerm.as
/* # Copyright (c) 2008-2010 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program is distributed in the hope that it will be useful, but # without any warranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the MIT License for full details. # */ package com.rpath.xobj { import flash.events.EventDispatcher; public class FilterTerm extends EventDispatcher { public function FilterTerm(name:String, value:String, operator:String = EQUAL) { super(); this.name = name; this.operator = operator; this.value = value; } /** * The field/property to filter on (LHS) */ public var name:String; /** * The logical operator to apply (see static consts below) */ public var operator:String; /** * The value to test the field against (RHS) */ public var value:String; public static const EQUAL:String = "EQUALS"; public static const NOT_EQUAL:String = "NOT_EQUALS"; public static const LESS_THAN:String = "LESS_THAN"; public static const LESS_THAN_OR_EQUAL:String = "LESS_THAN_OR_EQUAL"; public static const GREATER_THAN:String = "GREATER_THAN"; public static const GREATER_THAN_OR_EQUAL:String = "GREATER_THAN_OR_EQUAL"; public static const LIKE:String = "LIKE"; public static const NOT_LIKE:String = "NOT_LIKE"; public static const IN:String = "IN"; public static const NOT_IN:String = "NOT_IN"; public static const MATCHING:String = "MATCHING"; public static const NOT_MATCHING:String = "NOT_MATCHING"; public static const IS:String = "IS"; public static const IS_NOT:String = "IS_NOT"; public static const CONTAINS:String = "CONTAINS"; public static const YES:String = "YES"; public static const NO:String = "NO"; } }
/* # Copyright (c) 2008-2010 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program is distributed in the hope that it will be useful, but # without any warranty; without even the implied warranty of merchantability # or fitness for a particular purpose. See the MIT License for full details. # */ package com.rpath.xobj { import flash.events.EventDispatcher; [Bindable] public class FilterTerm { public function FilterTerm(name:String, value:String, operator:String = EQUAL) { super(); this.name = name; this.operator = operator; this.value = value; } /** * The field/property to filter on (LHS) */ public var name:String; /** * The logical operator to apply (see static consts below) */ public var operator:String; /** * The value to test the field against (RHS) */ public var value:String; public static const EQUAL:String = "EQUALS"; public static const NOT_EQUAL:String = "NOT_EQUALS"; public static const LESS_THAN:String = "LESS_THAN"; public static const LESS_THAN_OR_EQUAL:String = "LESS_THAN_OR_EQUAL"; public static const GREATER_THAN:String = "GREATER_THAN"; public static const GREATER_THAN_OR_EQUAL:String = "GREATER_THAN_OR_EQUAL"; public static const LIKE:String = "LIKE"; public static const NOT_LIKE:String = "NOT_LIKE"; public static const IN:String = "IN"; public static const NOT_IN:String = "NOT_IN"; public static const MATCHING:String = "MATCHING"; public static const NOT_MATCHING:String = "NOT_MATCHING"; public static const IS:String = "IS"; public static const IS_NOT:String = "IS_NOT"; public static const CONTAINS:String = "CONTAINS"; public static const YES:String = "YES"; public static const NO:String = "NO"; } }
Make FilterTerm bindable
Make FilterTerm bindable
ActionScript
apache-2.0
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
78bc8c5bed49ad73d749d48d6254540295ff8706
plugins/omniturePlugin/src/com/kaltura/kdpfl/plugin/component/OmnitureMediator.as
plugins/omniturePlugin/src/com/kaltura/kdpfl/plugin/component/OmnitureMediator.as
package com.kaltura.kdpfl.plugin.component { import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.ExternalInterfaceProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.SequenceProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.media.KMediaPlayerMediator; import com.kaltura.vo.KalturaPlayableEntry; import com.omniture.AppMeasurement; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.EventDispatcher; import flash.external.ExternalInterface; import mx.utils.ObjectProxy; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.facade.Facade; import org.puremvc.as3.patterns.mediator.Mediator; public class OmnitureMediator extends Mediator { /** * mediator name */ public static const NAME:String = "omnitureMediator"; private var _ready:Boolean = false; private var _inSeek:Boolean = false; private var _inDrag:Boolean = false; private var _inFF:Boolean = false; private var _p25Once:Boolean = false; private var _p50Once:Boolean = false; private var _p75Once:Boolean = false; private var _p100Once:Boolean = false; private var _played:Boolean = false; private var _wasBuffering:Boolean = false; private var _hasSeeked:Boolean = false; private var _isReplay:Boolean = false; private var _mediaIsLoaded:Boolean=false; private var _fullScreen:Boolean=false; private var _normalScreen:Boolean=false; private var _lastSeek:Number=0; private var _playheadPosition:Number=0; private var _lastId : String = ""; private var _isNewLoad : Boolean = false; public var _mediaName : String; private var _duration : Number; public var dynamicConfig:String; public var debugMode:String; public var charSet:String = "UTF-8"; public var currencyCode:String = "USD"; public var dc:String = "122"; public var eventDispatcher : EventDispatcher = new EventDispatcher(); public static const VIDEO_VIEW_EVENT:String = "videoViewEvent"; public static const VIDEO_AUTOPLAY_EVENT:String = "videoAutoPlayEvent"; public static const SHARE_EVENT:String = "shareEvent"; public static const OPEN_FULL_SCREEN_EVENT:String = "openFullscreenEvent"; public static const CLOSE_FULL_SCREEN_EVENT:String = "closefullscreenEvent"; public static const SAVE_EVENT:String = "saveEvent"; public static const REPLAY_EVENT:String = "replayEvent"; public static const PERCENT_50:String = "percent50"; public static const SEEK_EVENT:String = "seekEvent"; public static const CHANGE_MEDIA_EVENT:String = "changeMediaEvent"; public static const GOTO_CONTRIBUTOR_WINDOW_EVENT:String = "gotoContributorWindowEvent"; public static const GOTO_EDITOR_WINDOW_EVENT:String = "gotoEditorWindowEvent"; public static const PLAYER_PLAY_END_EVENT:String = "playerPlayEndEvent"; public static const MEDIA_READY_EVENT:String = "mediaReadyEvent"; public static const WATERMARK_CLICK:String = "watermarkClick"; private var eip:ExternalInterfaceProxy = Facade.getInstance().retrieveProxy("externalInterfaceProxy") as ExternalInterfaceProxy; private var _isReady:Boolean = false; private var _autoplayed:Boolean = false; /** * disable statistics */ public var statsDis : Boolean; /** * Omniture account */ public var account :String; /** * Omniture visitor namespace */ public var visitorNamespace :String; /** * Omniture tracking server */ public var trackingServer :String; /** * entry percents to track */ public var trackMilestones :String; /** * Custom general events */ public var customEvents:Array = new Array(); public var s:AppMeasurement; private var cp:Object; /** * Constructor. */ public function OmnitureMediator(customEvents:Array) { if (customEvents) { this.customEvents = customEvents; } super(NAME); } /** * External interface to extract the suit from the page */ private function getOmniVar(omnivar:String):String { //TODO - pass this through the ExternalInterfaceProxy once it will return ExternalInterface.call("function() { return "+omnivar+";}"); } /** * After all parameters are set - init the AppMeasurement object */ public function init():void { cp = Facade.getInstance().retrieveProxy("configProxy"); var f:Object = Facade.getInstance(); s = new AppMeasurement(); //this feature allows to extract the configuration from the page if(dynamicConfig == "true") { eip.addCallback("omnitureKdpJsReady",omnitureKdpJsReady); return; } else { if(visitorNamespace.indexOf("*")>-1) visitorNamespace.split("*").join("."); s.visitorNamespace = visitorNamespace; s.trackingServer = trackingServer; s.account = account; s.charSet = charSet; s.currencyCode = currencyCode; } prepareAppMeasurement(); } public function omnitureKdpJsReady():void { s.visitorNamespace = getOmniVar("com.TI.Metrics.tcNameSpace"); s.trackingServer = getOmniVar("com.TI.Metrics.tcTrackingServer"); s.account = getOmniVar("com.TI.Metrics.tcReportSuiteID"); s.charSet = getOmniVar("com.TI.Metrics.tcCharSet"); s.currencyCode = getOmniVar("com.TI.Metrics.tcCurrencyCode"); prepareAppMeasurement(); } /** * Prepare the AppMeasurement attributes and turn on the flag that sais that this is ready. */ private function prepareAppMeasurement():void { s.dc = dc; s.debugTracking = debugMode =="true" ? true : false ; s.trackLocal = true; s.Media.trackWhilePlaying = true; s.pageName = cp.vo.flashvars.referer; s.pageURL = cp.vo.flashvars.referer; s.Media.trackMilestones = trackMilestones; s.trackClickMap = true; if(cp.vo.kuiConf && cp.vo.kuiConf.name) s.Media.playerName= cp.vo.kuiConf.name; else s.Media.playerName= 'localPlayer'; _isReady = true; } private function onAddedToStage(evt:Event):void { (viewComponent as DisplayObjectContainer).addChild(s); } /** * Hook to the relevant KDP notifications */ override public function listNotificationInterests():Array { var notificationsArray:Array = [ NotificationType.HAS_OPENED_FULL_SCREEN, NotificationType.HAS_CLOSED_FULL_SCREEN, NotificationType.PLAYER_UPDATE_PLAYHEAD, NotificationType.PLAYER_READY, NotificationType.PLAYER_PLAYED, NotificationType.MEDIA_READY, NotificationType.DURATION_CHANGE, NotificationType.PLAYER_SEEK_START, NotificationType.PLAYER_SEEK_END, NotificationType.SCRUBBER_DRAG_START, NotificationType.SCRUBBER_DRAG_END, NotificationType.PLAYER_PAUSED, NotificationType.PLAYER_PLAY_END, NotificationType.CHANGE_MEDIA, "doGigya", "doDownload", "watermarkClick", NotificationType.DO_PLAY, NotificationType.DO_REPLAY, NotificationType.KDP_READY, NotificationType.DO_SEEK ]; notificationsArray = notificationsArray.concat(customEvents); return notificationsArray; } /** * @inheritDocs */ override public function handleNotification(note:INotification):void { if (statsDis) return; //trace("in handle notification: ", note.getName()); var kc: Object = facade.retrieveProxy("servicesProxy")["kalturaClient"]; var data:Object = note.getBody(); var sequenceProxy : SequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy; switch(note.getName()) { case NotificationType.PLAYER_READY: //this is useless since the event happens before the OmniturePlugin is ready for use //TOCHECK - do we neeed this ? ANswer - not at the current! //sendGeneralNotification("widgetLoaded"); break; case NotificationType.HAS_OPENED_FULL_SCREEN: if(_fullScreen==false) { sendGeneralNotification(OPEN_FULL_SCREEN_EVENT); } _fullScreen=true; _normalScreen=false; break; case NotificationType.HAS_CLOSED_FULL_SCREEN: if(_normalScreen==false) { sendGeneralNotification(CLOSE_FULL_SCREEN_EVENT); } _fullScreen=false; _normalScreen=true; break; case "watermarkClick": sendGeneralNotification(WATERMARK_CLICK); break; case "playerPlayEnd": s.Media.close(cp.vo.kuiConf.name); sendGeneralNotification(PLAYER_PLAY_END_EVENT); break; case NotificationType.PLAYER_PLAYED: if (!sequenceProxy.vo.isInSequence && !_played ) { s.Media.play(_mediaName,_playheadPosition); //seperate in case of autoplay: _played = true; if(cp.vo.flashvars.hasOwnProperty('autoPlay') && cp.vo.flashvars.autoPlay == "true" && !_autoplayed) { _autoplayed = true; sendGeneralNotification(VIDEO_AUTOPLAY_EVENT); } else sendGeneralNotification(VIDEO_VIEW_EVENT); } break; case "doDownload": sendGeneralNotification(SAVE_EVENT); break; case "doGigya": sendGeneralNotification(SHARE_EVENT); break; case NotificationType.MEDIA_READY: var bla:Object = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry; if((facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.id){ if (_lastId != (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.id) { _mediaName = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.name; var media:KalturaPlayableEntry = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry as KalturaPlayableEntry; if (media) _duration = media.duration; _played = false; _lastId = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.id; _isNewLoad = true; sendGeneralNotification(MEDIA_READY_EVENT); _p50Once = false; _autoplayed = false; } else { _isNewLoad = false; _lastSeek = 0; } _mediaIsLoaded=true; } s.movieID = _lastId; if(media) { s.Media.close(cp.vo.kuiConf.name); s.Media.open(_mediaName,media.duration, cp.vo.kuiConf.name); } break; case NotificationType.DURATION_CHANGE: if(_isNewLoad){ _hasSeeked = false; } return; break; case NotificationType.PLAYER_SEEK_END: _inSeek = false; var kmpm:KMediaPlayerMediator = (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator); trace("sent ",kmpm.player.currentTime); s.Media.play(_mediaName,kmpm.player.currentTime); //to see if we are passed 50% or not return; break; case NotificationType.SCRUBBER_DRAG_START: _inDrag = true; return; break; case NotificationType.SCRUBBER_DRAG_END: _inDrag = false; _inSeek = false; return; break; case NotificationType.PLAYER_UPDATE_PLAYHEAD: _playheadPosition = data as Number; // add a 50% notification trace(_playheadPosition , (_duration/2)) if(!_p50Once && _playheadPosition > (_duration/2)) { _p50Once = true; sendGeneralNotification(PERCENT_50); } break; case NotificationType.KDP_READY: //Ready should not occur more than once if (_ready) return; _ready = true; break; case NotificationType.DO_SEEK: _lastSeek = Number(note.getBody()); s.Media.stop(_mediaName,_playheadPosition); if(_inDrag && !_inSeek && !_isReplay) { sendGeneralNotification(SEEK_EVENT); } _inSeek = true; _hasSeeked = true; _isReplay = false; break; case NotificationType.DO_REPLAY: s.Media.open(_mediaName, _duration , cp.vo.kuiConf.name); sendGeneralNotification(REPLAY_EVENT); //TODO, fix the seek event being sent after replay. at the current this relies on the replay command happening before the seek _isReplay = true; break; /*case "doPlay": s.Media.play(_mediaName,_playheadPosition); break;*/ case NotificationType.PLAYER_PAUSED: var currentTime : Number = (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentTime; s.Media.stop(_mediaName,currentTime); break; default: //make sure we use the default only to the custom events for (var o:Object in customEvents) { if (note.getName() == customEvents[o].toString()) { sendGeneralNotification(note.getName()) break; } } break; } } /** * Send a general notification. let the code handle the logic * */ private function sendGeneralNotification(evt:String):void { eventDispatcher.dispatchEvent(new Event(evt)); } /** * view component */ public function get view() : DisplayObject { return viewComponent as DisplayObject; } // unique } }
package com.kaltura.kdpfl.plugin.component { import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.ExternalInterfaceProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.SequenceProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.view.media.KMediaPlayerMediator; import com.kaltura.vo.KalturaPlayableEntry; import com.omniture.AppMeasurement; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.EventDispatcher; import flash.external.ExternalInterface; import mx.utils.ObjectProxy; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.facade.Facade; import org.puremvc.as3.patterns.mediator.Mediator; public class OmnitureMediator extends Mediator { /** * mediator name */ public static const NAME:String = "omnitureMediator"; private var _ready:Boolean = false; private var _inSeek:Boolean = false; private var _inDrag:Boolean = false; private var _inFF:Boolean = false; private var _p25Once:Boolean = false; private var _p50Once:Boolean = false; private var _p75Once:Boolean = false; private var _p100Once:Boolean = false; private var _played:Boolean = false; private var _wasBuffering:Boolean = false; private var _hasSeeked:Boolean = false; private var _isReplay:Boolean = false; private var _mediaIsLoaded:Boolean=false; private var _fullScreen:Boolean=false; private var _normalScreen:Boolean=false; private var _lastSeek:Number=0; private var _playheadPosition:Number=0; private var _lastId : String = ""; private var _isNewLoad : Boolean = false; public var _mediaName : String; private var _duration : Number; public var dynamicConfig:String; public var debugMode:String; public var charSet:String = "UTF-8"; public var currencyCode:String = "USD"; public var dc:String = "122"; public var eventDispatcher : EventDispatcher = new EventDispatcher(); public static const VIDEO_VIEW_EVENT:String = "videoViewEvent"; public static const VIDEO_AUTOPLAY_EVENT:String = "videoAutoPlayEvent"; public static const SHARE_EVENT:String = "shareEvent"; public static const OPEN_FULL_SCREEN_EVENT:String = "openFullscreenEvent"; public static const CLOSE_FULL_SCREEN_EVENT:String = "closefullscreenEvent"; public static const SAVE_EVENT:String = "saveEvent"; public static const REPLAY_EVENT:String = "replayEvent"; public static const PERCENT_50:String = "percent50"; public static const SEEK_EVENT:String = "seekEvent"; public static const CHANGE_MEDIA_EVENT:String = "changeMediaEvent"; public static const GOTO_CONTRIBUTOR_WINDOW_EVENT:String = "gotoContributorWindowEvent"; public static const GOTO_EDITOR_WINDOW_EVENT:String = "gotoEditorWindowEvent"; public static const PLAYER_PLAY_END_EVENT:String = "playerPlayEndEvent"; public static const MEDIA_READY_EVENT:String = "mediaReadyEvent"; public static const WATERMARK_CLICK:String = "watermarkClick"; private var eip:ExternalInterfaceProxy = Facade.getInstance().retrieveProxy("externalInterfaceProxy") as ExternalInterfaceProxy; private var _isReady:Boolean = false; private var _autoplayed:Boolean = false; /** * disable statistics */ public var statsDis : Boolean; /** * Omniture account */ public var account :String; /** * Omniture visitor namespace */ public var visitorNamespace :String; /** * Omniture tracking server */ public var trackingServer :String; /** * entry percents to track */ public var trackMilestones :String; /** * Custom general events */ public var customEvents:Array = new Array(); public var s:AppMeasurement; private var cp:Object; /** * Constructor. */ public function OmnitureMediator(customEvents:Array) { if (customEvents) { this.customEvents = customEvents; } super(NAME); } /** * External interface to extract the suit from the page */ private function getOmniVar(omnivar:String):String { //TODO - pass this through the ExternalInterfaceProxy once it will return ExternalInterface.call("function() { return "+omnivar+";}"); } /** * After all parameters are set - init the AppMeasurement object */ public function init():void { cp = Facade.getInstance().retrieveProxy("configProxy"); var f:Object = Facade.getInstance(); s = new AppMeasurement(); //this feature allows to extract the configuration from the page if(dynamicConfig == "true") { eip.addCallback("omnitureKdpJsReady",omnitureKdpJsReady); return; } else { if(visitorNamespace.indexOf("*")>-1) visitorNamespace.split("*").join("."); s.visitorNamespace = visitorNamespace; s.trackingServer = trackingServer; s.account = account; s.charSet = charSet; s.currencyCode = currencyCode; } prepareAppMeasurement(); } public function omnitureKdpJsReady():void { s.visitorNamespace = getOmniVar("com.TI.Metrics.tcNameSpace"); s.trackingServer = getOmniVar("com.TI.Metrics.tcTrackingServer"); s.account = getOmniVar("com.TI.Metrics.tcReportSuiteID"); s.charSet = getOmniVar("com.TI.Metrics.tcCharSet"); s.currencyCode = getOmniVar("com.TI.Metrics.tcCurrencyCode"); prepareAppMeasurement(); } /** * Prepare the AppMeasurement attributes and turn on the flag that sais that this is ready. */ private function prepareAppMeasurement():void { s.dc = dc; s.debugTracking = debugMode =="true" ? true : false ; s.trackLocal = true; s.Media.trackWhilePlaying = true; s.pageName = cp.vo.flashvars.referer; s.pageURL = cp.vo.flashvars.referer; s.Media.trackMilestones = trackMilestones; s.trackClickMap = true; if(cp.vo.kuiConf && cp.vo.kuiConf.name) s.Media.playerName= cp.vo.kuiConf.name; else s.Media.playerName= 'localPlayer'; _isReady = true; } private function onAddedToStage(evt:Event):void { (viewComponent as DisplayObjectContainer).addChild(s); } /** * Hook to the relevant KDP notifications */ override public function listNotificationInterests():Array { var notificationsArray:Array = [ NotificationType.HAS_OPENED_FULL_SCREEN, NotificationType.HAS_CLOSED_FULL_SCREEN, NotificationType.PLAYER_UPDATE_PLAYHEAD, NotificationType.PLAYER_READY, NotificationType.PLAYER_PLAYED, NotificationType.MEDIA_READY, NotificationType.DURATION_CHANGE, NotificationType.PLAYER_SEEK_START, NotificationType.PLAYER_SEEK_END, NotificationType.SCRUBBER_DRAG_START, NotificationType.SCRUBBER_DRAG_END, NotificationType.PLAYER_PAUSED, NotificationType.PLAYER_PLAY_END, NotificationType.CHANGE_MEDIA, "doGigya", "showAdvancedShare", "doDownload", "watermarkClick", NotificationType.DO_PLAY, NotificationType.DO_REPLAY, NotificationType.KDP_READY, NotificationType.DO_SEEK ]; notificationsArray = notificationsArray.concat(customEvents); return notificationsArray; } /** * @inheritDocs */ override public function handleNotification(note:INotification):void { if (statsDis) return; //trace("in handle notification: ", note.getName()); var kc: Object = facade.retrieveProxy("servicesProxy")["kalturaClient"]; var data:Object = note.getBody(); var sequenceProxy : SequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy; switch(note.getName()) { case NotificationType.PLAYER_READY: //this is useless since the event happens before the OmniturePlugin is ready for use //TOCHECK - do we neeed this ? ANswer - not at the current! //sendGeneralNotification("widgetLoaded"); break; case NotificationType.HAS_OPENED_FULL_SCREEN: if(_fullScreen==false) { sendGeneralNotification(OPEN_FULL_SCREEN_EVENT); } _fullScreen=true; _normalScreen=false; break; case NotificationType.HAS_CLOSED_FULL_SCREEN: if(_normalScreen==false) { sendGeneralNotification(CLOSE_FULL_SCREEN_EVENT); } _fullScreen=false; _normalScreen=true; break; case "watermarkClick": sendGeneralNotification(WATERMARK_CLICK); break; case "playerPlayEnd": s.Media.close(cp.vo.kuiConf.name); sendGeneralNotification(PLAYER_PLAY_END_EVENT); break; case NotificationType.PLAYER_PLAYED: if (!sequenceProxy.vo.isInSequence && !_played ) { s.Media.play(_mediaName,_playheadPosition); //seperate in case of autoplay: _played = true; if(cp.vo.flashvars.hasOwnProperty('autoPlay') && cp.vo.flashvars.autoPlay == "true" && !_autoplayed) { _autoplayed = true; sendGeneralNotification(VIDEO_AUTOPLAY_EVENT); } else sendGeneralNotification(VIDEO_VIEW_EVENT); } break; case "doDownload": sendGeneralNotification(SAVE_EVENT); break; case "doGigya": case "showAdvancedShare": sendGeneralNotification(SHARE_EVENT); break; case NotificationType.MEDIA_READY: var bla:Object = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry; if((facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.id){ if (_lastId != (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.id) { _mediaName = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.name; var media:KalturaPlayableEntry = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry as KalturaPlayableEntry; if (media) _duration = media.duration; _played = false; _lastId = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.entry.id; _isNewLoad = true; sendGeneralNotification(MEDIA_READY_EVENT); _p50Once = false; _autoplayed = false; } else { _isNewLoad = false; _lastSeek = 0; } _mediaIsLoaded=true; } s.movieID = _lastId; if(media) { s.Media.close(cp.vo.kuiConf.name); s.Media.open(_mediaName,media.duration, cp.vo.kuiConf.name); } break; case NotificationType.DURATION_CHANGE: if(_isNewLoad){ _hasSeeked = false; } return; break; case NotificationType.PLAYER_SEEK_END: _inSeek = false; var kmpm:KMediaPlayerMediator = (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator); trace("sent ",kmpm.player.currentTime); s.Media.play(_mediaName,kmpm.player.currentTime); //to see if we are passed 50% or not return; break; case NotificationType.SCRUBBER_DRAG_START: _inDrag = true; return; break; case NotificationType.SCRUBBER_DRAG_END: _inDrag = false; _inSeek = false; return; break; case NotificationType.PLAYER_UPDATE_PLAYHEAD: _playheadPosition = data as Number; // add a 50% notification trace(_playheadPosition , (_duration/2)) if(!_p50Once && _playheadPosition > (_duration/2)) { _p50Once = true; sendGeneralNotification(PERCENT_50); } break; case NotificationType.KDP_READY: //Ready should not occur more than once if (_ready) return; _ready = true; break; case NotificationType.DO_SEEK: _lastSeek = Number(note.getBody()); s.Media.stop(_mediaName,_playheadPosition); if(_inDrag && !_inSeek && !_isReplay) { sendGeneralNotification(SEEK_EVENT); } _inSeek = true; _hasSeeked = true; _isReplay = false; break; case NotificationType.DO_REPLAY: s.Media.open(_mediaName, _duration , cp.vo.kuiConf.name); sendGeneralNotification(REPLAY_EVENT); //TODO, fix the seek event being sent after replay. at the current this relies on the replay command happening before the seek _isReplay = true; break; /*case "doPlay": s.Media.play(_mediaName,_playheadPosition); break;*/ case NotificationType.PLAYER_PAUSED: var currentTime : Number = (facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentTime; s.Media.stop(_mediaName,currentTime); break; default: //make sure we use the default only to the custom events for (var o:Object in customEvents) { if (note.getName() == customEvents[o].toString()) { sendGeneralNotification(note.getName()) break; } } break; } } /** * Send a general notification. let the code handle the logic * */ private function sendGeneralNotification(evt:String):void { eventDispatcher.dispatchEvent(new Event(evt)); } /** * view component */ public function get view() : DisplayObject { return viewComponent as DisplayObject; } // unique } }
add "showAdvancedShare" event
qnd: add "showAdvancedShare" event git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@86972 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
ActionScript
agpl-3.0
kaltura/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp
08b32927c416cd36fb7f609424624b18e671ae52
src/aerys/minko/scene/controller/mesh/DynamicTextureController.as
src/aerys/minko/scene/controller/mesh/DynamicTextureController.as
package aerys.minko.scene.controller.mesh { import aerys.minko.render.Viewport; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.scene.controller.EnterFrameController; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataProvider; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.geom.Matrix; import flash.geom.Rectangle; /** * The DynamicTextureController makes it possible to use Flash DisplayObjects * as dynamic textures. * * <p> * The DynamicTextureController listen for the Scene.enterFrame signal and * update the specified texture property of the targeted Meshes by rasterizing * the source Flash DisplayObject. * </p> * * @author Jean-Marc Le Roux * */ public final class DynamicTextureController extends EnterFrameController { private var _data : DataProvider; private var _source : DisplayObject; private var _framerate : Number; private var _mipMapping : Boolean; private var _propertyName : String; private var _matrix : Matrix; private var _forceBitmapDataClear : Boolean; private var _bitmapData : BitmapData; private var _texture : TextureResource; private var _lastDraw : Number; /** * Create a new DynamicTextureController. * * @param source The source DisplayObject to use as a dynamic texture. * @param width The width of the dynamic texture. * @param height The height of the dynamic texture. * @param mipMapping Whether mip-mapping should be enabled or not. Default value is 'true'. * @param framerate The frame rate of the dynamic texture. Default value is '30'. * @param propertyName The name of the bindings property that should be set with the * dynamic texture. Default value if 'diffuseMap'. * @param matrix The Matrix object that shall be used when rasterizing the DisplayObject * into the dynamic texture. Default value is 'null'. * */ public function DynamicTextureController(source : DisplayObject, width : Number, height : Number, mipMapping : Boolean = true, framerate : Number = 30., propertyName : String = 'diffuseMap', matrix : Matrix = null, forceBitmapDataClear : Boolean = false) { super(); _source = source; _texture = new TextureResource(width, height); _framerate = framerate; _mipMapping = mipMapping; _propertyName = propertyName; _matrix = matrix; _forceBitmapDataClear = forceBitmapDataClear; _data = new DataProvider(); _data.setProperty(propertyName, _texture); } public function get forceBitmapDataClear():Boolean { return _forceBitmapDataClear; } public function set forceBitmapDataClear(value:Boolean):void { _forceBitmapDataClear = value; } override protected function targetAddedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { super.targetAddedHandler(ctrl, target); // (target as Mesh).properties.setProperty(_propertyName, _texture); if (target is Scene) (target as Scene).bindings.addProvider(_data); else if (target is Mesh) (target as Mesh).bindings.addProvider(_data); else throw new Error(); } override protected function targetRemovedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { super.targetRemovedHandler(ctrl, target); // (target as Mesh).properties.removeProperty(_propertyName); if (target is Scene) (target as Scene).bindings.removeProvider(_data); else if (target is Mesh) (target as Mesh).bindings.removeProvider(_data); } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, target : BitmapData, time : Number) : void { if (time - _lastDraw > 1000. / _framerate) { _lastDraw = time; _bitmapData ||= new BitmapData(_source.width, _source.height); if (_forceBitmapDataClear) { _bitmapData.fillRect(new Rectangle(0, 0, _bitmapData.width, _bitmapData.height), 0); } _bitmapData.draw(_source, _matrix); _texture.setContentFromBitmapData(_bitmapData, _mipMapping); } } } }
package aerys.minko.scene.controller.mesh { import aerys.minko.render.Viewport; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.scene.controller.EnterFrameController; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.type.binding.DataProvider; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.geom.Matrix; import flash.geom.Rectangle; /** * The DynamicTextureController makes it possible to use Flash DisplayObjects * as dynamic textures. * * <p> * The DynamicTextureController listen for the Scene.enterFrame signal and * update the specified texture property of the targeted Meshes by rasterizing * the source Flash DisplayObject. * </p> * * @author Jean-Marc Le Roux * */ public final class DynamicTextureController extends EnterFrameController { private var _data : DataProvider; private var _source : DisplayObject; private var _framerate : Number; private var _mipMapping : Boolean; private var _propertyName : String; private var _matrix : Matrix; private var _forceBitmapDataClear : Boolean; private var _bitmapData : BitmapData; private var _texture : TextureResource; private var _lastDraw : Number; /** * Create a new DynamicTextureController. * * @param source The source DisplayObject to use as a dynamic texture. * @param width The width of the dynamic texture. * @param height The height of the dynamic texture. * @param mipMapping Whether mip-mapping should be enabled or not. Default value is 'true'. * @param framerate The frame rate of the dynamic texture. Default value is '30'. * @param propertyName The name of the bindings property that should be set with the * dynamic texture. Default value if 'diffuseMap'. * @param matrix The Matrix object that shall be used when rasterizing the DisplayObject * into the dynamic texture. Default value is 'null'. * */ public function DynamicTextureController(source : DisplayObject, width : Number, height : Number, mipMapping : Boolean = true, framerate : Number = 30., propertyName : String = 'diffuseMap', matrix : Matrix = null, forceBitmapDataClear : Boolean = false) { super(); _source = source; _texture = new TextureResource(width, height); _framerate = framerate; _mipMapping = mipMapping; _propertyName = propertyName; _matrix = matrix; _forceBitmapDataClear = forceBitmapDataClear; _data = new DataProvider(); _data.setProperty(propertyName, _texture); } public function get forceBitmapDataClear():Boolean { return _forceBitmapDataClear; } public function set forceBitmapDataClear(value:Boolean):void { _forceBitmapDataClear = value; } override protected function targetAddedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { super.targetAddedHandler(ctrl, target); if (target is Scene) (target as Scene).bindings.addProvider(_data); else if (target is Mesh) (target as Mesh).bindings.addProvider(_data); else throw new Error(); } override protected function targetRemovedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { super.targetRemovedHandler(ctrl, target); if (target is Scene) (target as Scene).bindings.removeProvider(_data); else if (target is Mesh) (target as Mesh).bindings.removeProvider(_data); } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, target : BitmapData, time : Number) : void { if (!_lastDraw || time - _lastDraw > 1000. / _framerate) { _lastDraw = time; _bitmapData ||= new BitmapData(_source.width, _source.height); if (_forceBitmapDataClear) _bitmapData.fillRect( new Rectangle(0, 0, _bitmapData.width, _bitmapData.height), 0 ); _bitmapData.draw(_source, _matrix); _texture.setContentFromBitmapData(_bitmapData, _mipMapping); } } } }
fix DynamicTextureController.sceneEnterFrameHandler() to make sure the source is rasterized/uploaded to init. the texture and avoid error 3700 at the first frame
fix DynamicTextureController.sceneEnterFrameHandler() to make sure the source is rasterized/uploaded to init. the texture and avoid error 3700 at the first frame
ActionScript
mit
aerys/minko-as3
84cfaec97fbdc245fa1533b252c2360a45a266f5
src/org/mangui/jwplayer/media/HLSProvider.as
src/org/mangui/jwplayer/media/HLSProvider.as
package org.mangui.jwplayer.media { import org.mangui.HLS.parsing.Level; import org.mangui.HLS.*; import org.mangui.HLS.utils.Log; import org.mangui.HLS.utils.ScaleVideo; import com.longtailvideo.jwplayer.events.MediaEvent; import com.longtailvideo.jwplayer.model.PlayerConfig; import com.longtailvideo.jwplayer.model.PlaylistItem; import com.longtailvideo.jwplayer.media.*; import com.longtailvideo.jwplayer.player.PlayerState; import com.longtailvideo.jwplayer.utils.RootReference; import flash.display.DisplayObject; import flash.geom.Rectangle; import flash.media.SoundTransform; import flash.media.Video; import flash.media.StageVideo; import flash.system.Capabilities; import flash.events.Event; /** JW Player provider for hls streaming. **/ public class HLSProvider extends MediaProvider { /** Reference to the framework. **/ protected var _hls : HLS; /** Current quality level. **/ protected var _level : Number; /** Reference to the quality levels. **/ protected var _levels : Vector.<Level>; /** Reference to the video object. **/ private var _video : Video; /** Reference to the stage video element. **/ private var _stageVideo : StageVideo; /** Whether or not StageVideo is enabled (not working with JW5) **/ protected var _stageEnabled : Boolean = false; /** current position **/ protected var _media_position : Number; /** Video Original size **/ private var _videoWidth : Number = 0; private var _videoHeight : Number = 0; private var _seekInLiveDurationThreshold : Number = 60; public function HLSProvider() { super('hls'); }; /** Forward completes from the framework. **/ private function _completeHandler(event : HLSEvent) : void { complete(); }; /** Forward playback errors from the framework. **/ private function _errorHandler(event : HLSEvent) : void { super.error(event.error.msg); }; /** Forward QOS metrics on fragment load. **/ protected function _fragmentHandler(event : HLSEvent) : void { _level = event.metrics.level; sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata:{bandwidth:Math.round(event.metrics.bandwidth / 1024), droppedFrames:_hls.stream.info.droppedFrames, currentLevel:(_level + 1) + ' of ' + _levels.length + ' (' + Math.round(_levels[_level].bitrate / 1024) + 'kbps, ' + _levels[_level].width + 'px)', width:_videoWidth}}); }; /** Update video A/R on manifest load. **/ private function _manifestHandler(event : HLSEvent) : void { _levels = event.levels; // only report position/duration/buffer for VOD playlist and live playlist with duration > _seekInLiveDurationThreshold if (_hls.type == HLSTypes.VOD || _levels[0].duration > _seekInLiveDurationThreshold) { item.duration = _levels[0].duration; } else { item.duration = -1; } sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_TIME, {position:0, duration:item.duration}); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); /* start playback on manifest load */ if (item.start != 0) { _hls.stream.seek(item.start); } else { _hls.stream.play(); } }; /** Update playback position. **/ private function _mediaTimeHandler(event : HLSEvent) : void { // only report position/duration/buffer for VOD playlist and live playlist with duration > _seekInLiveDurationThreshold if (_hls.type == HLSTypes.VOD || event.mediatime.duration > _seekInLiveDurationThreshold) { item.duration = event.mediatime.duration; _media_position = Math.max(0, event.mediatime.position); var _bufferPercent : Number = 100 * (_media_position + event.mediatime.buffer) / event.mediatime.duration; sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_TIME, {bufferPercent:_bufferPercent, offset:0, position:_media_position, duration:event.mediatime.duration}); } var videoWidth : Number; var videoHeight : Number; if (_stageVideo) { videoWidth = _stageVideo.videoWidth; videoHeight = _stageVideo.videoHeight; } else { videoWidth = _video.videoWidth; videoHeight = _video.videoHeight; } if (videoWidth && videoHeight) { if (_videoWidth != videoWidth || _videoHeight != videoHeight) { _videoHeight = videoHeight; _videoWidth = videoWidth; Log.info("video size changed to " + _videoWidth + "/" + _videoHeight); // force resize to adjust video A/R resize(videoWidth, _videoHeight); } } }; /** Forward state changes from the framework. **/ private function _stateHandler(event : HLSEvent) : void { switch(event.state) { case HLSPlayStates.IDLE: setState(PlayerState.IDLE); break; case HLSPlayStates.PLAYING_BUFFERING: case HLSPlayStates.PAUSED_BUFFERING: setState(PlayerState.BUFFERING); break; case HLSPlayStates.PLAYING: _video.visible = true; setState(PlayerState.PLAYING); break; case HLSPlayStates.PAUSED: setState(PlayerState.PAUSED); break; } }; private function _audioHandler(e : Event) : void { media = null; // sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_LOADED); // dispatchEvent(new MediaEvent(MediaEvent.JWPLAYER_MEDIA_LOADED)); } /** Set the volume on init. **/ override public function initializeMediaProvider(cfg : PlayerConfig) : void { super.initializeMediaProvider(cfg); _hls = new HLS(); _hls.stage = RootReference.stage; _hls.stream.soundTransform = new SoundTransform(cfg.volume / 100); _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.AUDIO_ONLY, _audioHandler); // Allow stagevideo to be disabled by user config if (cfg.hasOwnProperty('stagevideo') && cfg['stagevideo'].toString() == "false") { _stageEnabled = false; } _video = new Video(320, 240); _video.smoothing = true; // Use stageVideo when available if (_stageEnabled && RootReference.stage.stageVideos.length > 0) { _stageVideo = RootReference.stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, 320, 240); _stageVideo.attachNetStream(_hls.stream); Log.info("stage video enabled"); } else { _video.attachNetStream(_hls.stream); } _level = 0; var value : Object; // parse configuration parameters value = cfg.hls_debug; if (value != null) { Log.info("hls_debug:" + value); Log.LOG_DEBUG_ENABLED = value as Boolean; } value = cfg.hls_debug2; if (value != null) { Log.info("hls_debug2:" + value); Log.LOG_DEBUG2_ENABLED = value as Boolean; } value = cfg.hls_minbufferlength; if (value != null) { Log.info("hls_minbufferlength:" + value); _hls.minBufferLength = value as Number; } value = cfg.hls_maxbufferlength; if (value != null) { Log.info("hls_maxbufferlength:" + value); _hls.maxBufferLength = value as Number; } value = cfg.hls_lowbufferlength; if (value != null) { Log.info("hls_lowbufferlength:" + value); _hls.lowBufferLength = value as Number; } value = cfg.hls_startfromlowestlevel; if (value != null) { Log.info("hls_startfromlowestlevel:" + value); _hls.startFromLowestLevel = value as Boolean; } value = cfg.hls_seekfromlowestlevel; if (value != null) { Log.info("hls_seekfromlowestlevel:" + value); _hls.seekFromLowestLevel = value as Boolean; } value = cfg.hls_live_flushurlcache; if (value != null) { Log.info("hls_live_flushurlcache:" + value); _hls.flushLiveURLCache = value as Boolean; } value = cfg.hls_live_seekdurationthreshold; if (value != null) { Log.info("hls_live_seekdurationthreshold:" + value); _seekInLiveDurationThreshold = value as Number; } value = cfg.hls_seekmode; if (value != null) { Log.info("hls_seekmode:" + value); _hls.seekMode = value as String; } value = cfg.hls_fragmentloadmaxretry; if (value != null) { Log.info("hls_fragmentloadmaxretry:" + value); _hls.fragmentLoadMaxRetry = value as Number; } value = cfg.hls_manifestloadmaxretry; if (value != null) { Log.info("hls_manifestloadmaxretry:" + value); _hls.manifestLoadMaxRetry = value as Number; } value = cfg.hls_capleveltostage; if (value != null) { Log.info("hls_capleveltostage:" + value); if (value as Boolean == true) { _hls.capLeveltoStage = true; } } mute(cfg.mute); }; /** Check that Flash Player version is sufficient (10.1 or above) **/ private function _checkVersion() : Number { var versionStr : String = Capabilities.version; var verArray : Array = versionStr.split(/\s|,/); var versionNum : Number = Number(String(verArray[1] + "." + verArray[2])); return versionNum; } /** Load a new playlist item **/ override public function load(itm : PlaylistItem) : void { // Check flash player version var ver : Number = _checkVersion(); var minVersion : Number = 11.6; if ( ver < minVersion ) { sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_ERROR, {message:"This application requires Flash Player 11.6 at mimimum"}); } else { super.load(itm); play(); } }; /** Get the video object. **/ override public function get display() : DisplayObject { return _video; }; public override function getRawMedia():DisplayObject { return display; } /** Resume playback of a paused item. **/ override public function play() : void { if (state == PlayerState.PAUSED) { _hls.stream.resume(); } else { setState(PlayerState.BUFFERING); _hls.load(item.file); } }; /** Pause a playing item. **/ override public function pause() : void { _hls.stream.pause(); }; /** Do a resize on the video. **/ override public function resize(width : Number, height : Number) : void { Log.info("resize video from [" + _videoWidth + "," + _videoHeight + "]" + "to [" + width + "," + height + "]"); _width = width; _height = height; if (_videoWidth && _videoHeight) { var rect : Rectangle = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, width, height); if (_stageVideo) { _stageVideo.viewPort = rect; } else { _video.x = rect.x; _video.y = rect.y; _video.width = rect.width; _video.height = rect.height; } } }; /** Seek to a certain position in the item. **/ override public function seek(pos : Number) : void { _hls.stream.seek(pos); }; /** Change the playback volume of the item. **/ override public function setVolume(vol : Number) : void { _hls.stream.soundTransform = new SoundTransform(vol / 100); super.setVolume(vol); }; /** Stop playback. **/ override public function stop() : void { _hls.stream.close(); super.stop(); _hls.removeEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _level = 0; }; } }
package org.mangui.jwplayer.media { import org.mangui.HLS.parsing.Level; import org.mangui.HLS.*; import org.mangui.HLS.utils.Log; import org.mangui.HLS.utils.ScaleVideo; import com.longtailvideo.jwplayer.events.MediaEvent; import com.longtailvideo.jwplayer.model.PlayerConfig; import com.longtailvideo.jwplayer.model.PlaylistItem; import com.longtailvideo.jwplayer.media.*; import com.longtailvideo.jwplayer.player.PlayerState; import com.longtailvideo.jwplayer.utils.RootReference; import flash.display.DisplayObject; import flash.geom.Rectangle; import flash.media.SoundTransform; import flash.media.Video; import flash.media.StageVideo; import flash.system.Capabilities; import flash.events.Event; /** JW Player provider for hls streaming. **/ public class HLSProvider extends MediaProvider { /** Reference to the framework. **/ protected var _hls : HLS; /** Current quality level. **/ protected var _level : Number; /** Reference to the quality levels. **/ protected var _levels : Vector.<Level>; /** Reference to the video object. **/ private var _video : Video; /** Reference to the stage video element. **/ private var _stageVideo : StageVideo; /** Whether or not StageVideo is enabled (not working with JW5) **/ protected var _stageEnabled : Boolean = false; /** current position **/ protected var _media_position : Number; /** Video Original size **/ private var _videoWidth : Number = 0; private var _videoHeight : Number = 0; private var _seekInLiveDurationThreshold : Number = 60; public function HLSProvider() { super('hls'); }; /** Forward completes from the framework. **/ private function _completeHandler(event : HLSEvent) : void { complete(); }; /** Forward playback errors from the framework. **/ private function _errorHandler(event : HLSEvent) : void { super.error(event.error.msg); }; /** Forward QOS metrics on fragment load. **/ protected function _fragmentHandler(event : HLSEvent) : void { _level = event.metrics.level; sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata:{bandwidth:Math.round(event.metrics.bandwidth / 1024), droppedFrames:_hls.stream.info.droppedFrames, currentLevel:(_level + 1) + ' of ' + _levels.length + ' (' + Math.round(_levels[_level].bitrate / 1024) + 'kbps, ' + _levels[_level].width + 'px)', width:_videoWidth}}); }; /** Update video A/R on manifest load. **/ private function _manifestHandler(event : HLSEvent) : void { _levels = event.levels; // only report position/duration/buffer for VOD playlist and live playlist with duration > _seekInLiveDurationThreshold if (_hls.type == HLSTypes.VOD || _levels[0].duration > _seekInLiveDurationThreshold) { item.duration = _levels[0].duration; } else { item.duration = -1; } sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_TIME, {position:0, duration:item.duration}); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); /* start playback on manifest load */ if (item.start != 0) { _hls.stream.seek(item.start); } else { _hls.stream.play(); } }; /** Update playback position. **/ private function _mediaTimeHandler(event : HLSEvent) : void { // only report position/duration/buffer for VOD playlist and live playlist with duration > _seekInLiveDurationThreshold if (_hls.type == HLSTypes.VOD || event.mediatime.duration > _seekInLiveDurationThreshold) { item.duration = event.mediatime.duration; _media_position = Math.max(0, event.mediatime.position); var _bufferPercent : Number = 100 * (_media_position + event.mediatime.buffer) / event.mediatime.duration; sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_TIME, {bufferPercent:_bufferPercent, offset:0, position:_media_position, duration:event.mediatime.duration}); } var videoWidth : Number; var videoHeight : Number; if (_stageVideo) { videoWidth = _stageVideo.videoWidth; videoHeight = _stageVideo.videoHeight; } else { videoWidth = _video.videoWidth; videoHeight = _video.videoHeight; } if (videoWidth && videoHeight) { if (_videoWidth != videoWidth || _videoHeight != videoHeight) { _videoHeight = videoHeight; _videoWidth = videoWidth; Log.info("video size changed to " + _videoWidth + "/" + _videoHeight); // force resize to adjust video A/R resize(videoWidth, _videoHeight); } } }; /** Forward state changes from the framework. **/ private function _stateHandler(event : HLSEvent) : void { switch(event.state) { case HLSPlayStates.IDLE: setState(PlayerState.IDLE); break; case HLSPlayStates.PLAYING_BUFFERING: case HLSPlayStates.PAUSED_BUFFERING: setState(PlayerState.BUFFERING); break; case HLSPlayStates.PLAYING: _video.visible = true; setState(PlayerState.PLAYING); break; case HLSPlayStates.PAUSED: setState(PlayerState.PAUSED); break; } }; private function _audioHandler(e : Event) : void { media = null; // sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_LOADED); // dispatchEvent(new MediaEvent(MediaEvent.JWPLAYER_MEDIA_LOADED)); } /** Set the volume on init. **/ override public function initializeMediaProvider(cfg : PlayerConfig) : void { super.initializeMediaProvider(cfg); _hls = new HLS(); _hls.stage = RootReference.stage; _hls.stream.soundTransform = new SoundTransform(cfg.volume / 100); _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.AUDIO_ONLY, _audioHandler); // Allow stagevideo to be disabled by user config if (cfg.hasOwnProperty('stagevideo') && cfg['stagevideo'].toString() == "false") { _stageEnabled = false; } _video = new Video(1920, 960); _video.smoothing = true; // Use stageVideo when available if (_stageEnabled && RootReference.stage.stageVideos.length > 0) { _stageVideo = RootReference.stage.stageVideos[0]; _stageVideo.viewPort = new Rectangle(0, 0, 1920, 960); _stageVideo.attachNetStream(_hls.stream); Log.info("stage video enabled"); } else { _video.attachNetStream(_hls.stream); } _level = 0; var value : Object; // parse configuration parameters value = cfg.hls_debug; if (value != null) { Log.info("hls_debug:" + value); Log.LOG_DEBUG_ENABLED = value as Boolean; } value = cfg.hls_debug2; if (value != null) { Log.info("hls_debug2:" + value); Log.LOG_DEBUG2_ENABLED = value as Boolean; } value = cfg.hls_minbufferlength; if (value != null) { Log.info("hls_minbufferlength:" + value); _hls.minBufferLength = value as Number; } value = cfg.hls_maxbufferlength; if (value != null) { Log.info("hls_maxbufferlength:" + value); _hls.maxBufferLength = value as Number; } value = cfg.hls_lowbufferlength; if (value != null) { Log.info("hls_lowbufferlength:" + value); _hls.lowBufferLength = value as Number; } value = cfg.hls_startfromlowestlevel; if (value != null) { Log.info("hls_startfromlowestlevel:" + value); _hls.startFromLowestLevel = value as Boolean; } value = cfg.hls_seekfromlowestlevel; if (value != null) { Log.info("hls_seekfromlowestlevel:" + value); _hls.seekFromLowestLevel = value as Boolean; } value = cfg.hls_live_flushurlcache; if (value != null) { Log.info("hls_live_flushurlcache:" + value); _hls.flushLiveURLCache = value as Boolean; } value = cfg.hls_live_seekdurationthreshold; if (value != null) { Log.info("hls_live_seekdurationthreshold:" + value); _seekInLiveDurationThreshold = value as Number; } value = cfg.hls_seekmode; if (value != null) { Log.info("hls_seekmode:" + value); _hls.seekMode = value as String; } value = cfg.hls_fragmentloadmaxretry; if (value != null) { Log.info("hls_fragmentloadmaxretry:" + value); _hls.fragmentLoadMaxRetry = value as Number; } value = cfg.hls_manifestloadmaxretry; if (value != null) { Log.info("hls_manifestloadmaxretry:" + value); _hls.manifestLoadMaxRetry = value as Number; } value = cfg.hls_capleveltostage; if (value != null) { Log.info("hls_capleveltostage:" + value); if (value as Boolean == true) { _hls.capLeveltoStage = true; } } mute(cfg.mute); }; /** Check that Flash Player version is sufficient (10.1 or above) **/ private function _checkVersion() : Number { var versionStr : String = Capabilities.version; var verArray : Array = versionStr.split(/\s|,/); var versionNum : Number = Number(String(verArray[1] + "." + verArray[2])); return versionNum; } /** Load a new playlist item **/ override public function load(itm : PlaylistItem) : void { // Check flash player version var ver : Number = _checkVersion(); var minVersion : Number = 11.6; if ( ver < minVersion ) { sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_ERROR, {message:"This application requires Flash Player 11.6 at mimimum"}); } else { super.load(itm); play(); } }; /** Get the video object. **/ override public function get display() : DisplayObject { return _video; }; public override function getRawMedia():DisplayObject { return display; } /** Resume playback of a paused item. **/ override public function play() : void { if (state == PlayerState.PAUSED) { _hls.stream.resume(); } else { setState(PlayerState.BUFFERING); _hls.load(item.file); } }; /** Pause a playing item. **/ override public function pause() : void { _hls.stream.pause(); }; /** Do a resize on the video. **/ override public function resize(width : Number, height : Number) : void { Log.info("resize video from [" + _videoWidth + "," + _videoHeight + "]" + "to [" + width + "," + height + "]"); _width = width; _height = height; if (_videoWidth && _videoHeight) { var rect : Rectangle = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, width, height); if (_stageVideo) { _stageVideo.viewPort = rect; } else { _video.x = rect.x; _video.y = rect.y; _video.width = rect.width; _video.height = rect.height; } } }; /** Seek to a certain position in the item. **/ override public function seek(pos : Number) : void { _hls.stream.seek(pos); }; /** Change the playback volume of the item. **/ override public function setVolume(vol : Number) : void { _hls.stream.soundTransform = new SoundTransform(vol / 100); super.setVolume(vol); }; /** Stop playback. **/ override public function stop() : void { _hls.stream.close(); super.stop(); _hls.removeEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _level = 0; }; } }
Create Video element using 1920x960 resolution.
Create Video element using 1920x960 resolution.
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
329b9d7a6ab0de7c2483d9a53ca36027e463cf25
src/aerys/minko/scene/node/Scene.as
src/aerys/minko/scene/node/Scene.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.Effect; import aerys.minko.render.Viewport; import aerys.minko.scene.controller.scene.RenderingController; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.loader.AssetsLibrary; import flash.display.BitmapData; import flash.utils.Dictionary; import flash.utils.getTimer; /** * Scene objects are the root of any 3D scene. * * @author Jean-Marc Le Roux * */ public final class Scene extends Group { use namespace minko_scene; minko_scene var _camera : AbstractCamera; private var _renderingCtrl : RenderingController; private var _properties : DataProvider; private var _bindings : DataBindings; private var _numTriangles : uint; private var _enterFrame : Signal; private var _renderingBegin : Signal; private var _renderingEnd : Signal; private var _exitFrame : Signal; private var _assets : AssetsLibrary; public function get assets() : AssetsLibrary { return _assets; } public function get activeCamera() : AbstractCamera { return _camera; } public function get numPasses() : uint { return _renderingCtrl.numPasses; } public function get numEnabledPasses() : uint { return _renderingCtrl.numEnabledPasses; } public function get numDrawCalls() : uint { return _renderingCtrl.numDrawCalls; } public function get numEnabledDrawCalls() : uint { return _renderingCtrl.numEnabledDrawCalls; } public function get numTriangles() : uint { return _numTriangles; } public function get numDrawCalls() : uint { return _renderingCtrl.numDrawCalls; } public function get postProcessingEffect() : Effect { return _renderingCtrl.postProcessingEffect; } public function set postProcessingEffect(value : Effect) : void { _renderingCtrl.postProcessingEffect = value; } public function get postProcessingProperties() : DataProvider { return _renderingCtrl.postProcessingProperties; } public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get bindings() : DataBindings { return _bindings; } /** * The signal executed when the viewport is about to start rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who starts rendering the frame</li> * </ul> * @return * */ public function get enterFrame() : Signal { return _enterFrame; } /** * The signal executed when the viewport is done rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who just finished rendering the frame</li> * </ul> * @return * */ public function get exitFrame() : Signal { return _exitFrame; } public function get renderingBegin() : Signal { return _renderingBegin; } public function get renderingEnd() : Signal { return _renderingEnd; } public function Scene(...children) { super(children); } override protected function initialize() : void { _bindings = new DataBindings(this); _assets = new AssetsLibrary(); this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE); super.initialize(); } override protected function initializeSignals() : void { super.initializeSignals(); _enterFrame = new Signal('Scene.enterFrame'); _renderingBegin = new Signal('Scene.renderingBegin'); _renderingEnd = new Signal('Scene.renderingEnd'); _exitFrame = new Signal('Scene.exitFrame'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); added.add(addedHandler); } override protected function initializeContollers() : void { _renderingCtrl = new RenderingController(); addController(_renderingCtrl); super.initializeContollers(); } public function render(viewport : Viewport, destination : BitmapData = null) : void { _enterFrame.execute(this, viewport, destination, getTimer()); if (viewport.ready && viewport.visible) { _renderingBegin.execute(this, viewport, destination, getTimer()); _numTriangles = _renderingCtrl.render(viewport, destination); _renderingEnd.execute(this, viewport, destination, getTimer()); } _exitFrame.execute(this, viewport, destination, getTimer()); } private function addedHandler(child : ISceneNode, parent : Group) : void { throw new Error(); } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.Effect; import aerys.minko.render.Viewport; import aerys.minko.scene.controller.scene.RenderingController; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.loader.AssetsLibrary; import flash.display.BitmapData; import flash.utils.Dictionary; import flash.utils.getTimer; /** * Scene objects are the root of any 3D scene. * * @author Jean-Marc Le Roux * */ public final class Scene extends Group { use namespace minko_scene; minko_scene var _camera : AbstractCamera; private var _renderingCtrl : RenderingController; private var _properties : DataProvider; private var _bindings : DataBindings; private var _numTriangles : uint; private var _enterFrame : Signal; private var _renderingBegin : Signal; private var _renderingEnd : Signal; private var _exitFrame : Signal; private var _assets : AssetsLibrary; public function get assets() : AssetsLibrary { return _assets; } public function get activeCamera() : AbstractCamera { return _camera; } public function get numPasses() : uint { return _renderingCtrl.numPasses; } public function get numEnabledPasses() : uint { return _renderingCtrl.numEnabledPasses; } public function get numDrawCalls() : uint { return _renderingCtrl.numDrawCalls; } public function get numEnabledDrawCalls() : uint { return _renderingCtrl.numEnabledDrawCalls; } public function get numTriangles() : uint { return _numTriangles; } public function get postProcessingEffect() : Effect { return _renderingCtrl.postProcessingEffect; } public function set postProcessingEffect(value : Effect) : void { _renderingCtrl.postProcessingEffect = value; } public function get postProcessingProperties() : DataProvider { return _renderingCtrl.postProcessingProperties; } public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get bindings() : DataBindings { return _bindings; } /** * The signal executed when the viewport is about to start rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who starts rendering the frame</li> * </ul> * @return * */ public function get enterFrame() : Signal { return _enterFrame; } /** * The signal executed when the viewport is done rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who just finished rendering the frame</li> * </ul> * @return * */ public function get exitFrame() : Signal { return _exitFrame; } public function get renderingBegin() : Signal { return _renderingBegin; } public function get renderingEnd() : Signal { return _renderingEnd; } public function Scene(...children) { super(children); } override protected function initialize() : void { _bindings = new DataBindings(this); _assets = new AssetsLibrary(); this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE); super.initialize(); } override protected function initializeSignals() : void { super.initializeSignals(); _enterFrame = new Signal('Scene.enterFrame'); _renderingBegin = new Signal('Scene.renderingBegin'); _renderingEnd = new Signal('Scene.renderingEnd'); _exitFrame = new Signal('Scene.exitFrame'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); added.add(addedHandler); } override protected function initializeContollers() : void { _renderingCtrl = new RenderingController(); addController(_renderingCtrl); super.initializeContollers(); } public function render(viewport : Viewport, destination : BitmapData = null) : void { _enterFrame.execute(this, viewport, destination, getTimer()); if (viewport.ready && viewport.visible) { _renderingBegin.execute(this, viewport, destination, getTimer()); _numTriangles = _renderingCtrl.render(viewport, destination); _renderingEnd.execute(this, viewport, destination, getTimer()); } _exitFrame.execute(this, viewport, destination, getTimer()); } private function addedHandler(child : ISceneNode, parent : Group) : void { throw new Error(); } } }
fix duplicate function definition for Scene.numDrawCalls getter
fix duplicate function definition for Scene.numDrawCalls getter
ActionScript
mit
aerys/minko-as3
b5162c4fe663d2e69626d08e4e28a1582b1fff8d
src/com/google/analytics/core/DocumentInfo.as
src/com/google/analytics/core/DocumentInfo.as
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package com.google.analytics.core { import com.google.analytics.external.AdSenseGlobals; import com.google.analytics.utils.Environment; import com.google.analytics.utils.Variables; import com.google.analytics.v4.Configuration; /** * The DocumentInfo class. */ public class DocumentInfo { private var _config:Configuration; private var _info:Environment; private var _adSense:AdSenseGlobals; private var _pageURL:String; private var _utmr:String; /** * Creates a new DocumentInfo instance. */ public function DocumentInfo( config:Configuration, info:Environment, formatedReferrer:String, pageURL:String = null, adSense:AdSenseGlobals = null ) { _config = config; _info = info; _utmr = formatedReferrer; _pageURL = pageURL; _adSense = adSense; } /** * Generates hit id for revenue per page tracking for AdSense. * <p>This method first examines the DOM for existing hid.</p> * <p>If there is already a hid in DOM, then this method will return the existing hid.</p> * <p>If there isn't any hid in DOM, then this method will generate a new hid, and both stores it in DOM, and returns it to the caller.</p> * @return hid used by AdSense for revenue per page tracking */ private function _generateHitId():Number { var hid:Number; //have hid in DOM if( _adSense.hid && (_adSense.hid != "") ) { hid = Number( _adSense.hid ); } //doesn't have hid in DOM else { hid = Math.round( Math.random() * 0x7fffffff ); _adSense.hid = String( hid ); } return hid; } /** * This method will collect and return the page URL information based on * the page URL specified by the user if present. If there is no parameter, * the URL of the HTML page embedding the SWF will be sent. If * ExternalInterface.avaliable=false, a default of "/" will be used. * * @private * @param {String} opt_pageURL (Optional) User-specified Page URL to assign * metrics to at the back-end. * * @return {String} Final page URL to assign metrics to at the back-end. */ private function _renderPageURL( pageURL:String = "" ):String { var pathname:String = _info.locationPath; var search:String = _info.locationSearch; if( !pageURL || (pageURL == "") ) { pageURL = pathname + unescape( search ); if ( pageURL == "" ) { pageURL = "/"; } } return pageURL; } /** * Page title, which is a URL-encoded string. * <p><b>Example :</b></p> * <pre class="prettyprint">utmdt=analytics%20page%20test</pre> */ public function get utmdt():String { return _info.documentTitle; } /** * Hit id for revenue per page tracking for AdSense. * <p><b>Example :<b><code class="prettyprint">utmhid=2059107202</code></p> */ public function get utmhid():String { return String( _generateHitId() ); } /** * Referral, complete URL. * <p><b>Example :<b><code class="prettyprint">utmr=http://www.example.com/aboutUs/index.php?var=selected</code></p> */ public function get utmr():String { if( !_utmr ) { return "-"; } return _utmr; } /** * Page request of the current page. * <p><b>Example :<b><code class="prettyprint">utmp=/testDirectory/myPage.html</code></p> */ public function get utmp():String { return _renderPageURL( _pageURL ); } /** * Returns a Variables object representation. * @return a Variables object representation. */ public function toVariables():Variables { var variables:Variables = new Variables(); variables.URIencode = true; if( _config.detectTitle && ( utmdt != "") ) { variables.utmdt = utmdt; } variables.utmhid = utmhid; variables.utmr = utmr; variables.utmp = utmp; return variables; } /** * Returns the url String representation of the object. * @return the url String representation of the object. */ public function toURLString():String { var v:Variables = toVariables(); return v.toString(); } } }
/* * Copyright 2008 Adobe Systems Inc., 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributor(s): * Zwetan Kjukov <[email protected]>. */ package com.google.analytics.core { import com.google.analytics.external.AdSenseGlobals; import com.google.analytics.utils.Environment; import com.google.analytics.utils.Variables; import com.google.analytics.v4.Configuration; /** * The DocumentInfo class. */ public class DocumentInfo { private var _config:Configuration; private var _info:Environment; private var _adSense:AdSenseGlobals; private var _pageURL:String; private var _utmr:String; /** * Creates a new DocumentInfo instance. */ public function DocumentInfo( config:Configuration, info:Environment, formatedReferrer:String, pageURL:String = null, adSense:AdSenseGlobals = null ) { _config = config; _info = info; _utmr = formatedReferrer; _pageURL = pageURL; _adSense = adSense; } /** * Generates hit id for revenue per page tracking for AdSense. * <p>This method first examines the DOM for existing hid.</p> * <p>If there is already a hid in DOM, then this method will return the existing hid.</p> * <p>If there isn't any hid in DOM, then this method will generate a new hid, and both stores it in DOM, and returns it to the caller.</p> * @return hid used by AdSense for revenue per page tracking */ private function _generateHitId():Number { var hid:Number; //have hid in DOM if( _adSense.hid && (_adSense.hid != "") ) { hid = Number( _adSense.hid ); } //doesn't have hid in DOM else { hid = Math.round( Math.random() * 0x7fffffff ); _adSense.hid = String( hid ); } return hid; } /** * This method will collect and return the page URL information based on * the page URL specified by the user if present. If there is no parameter, * the URL of the HTML page embedding the SWF will be sent. If * ExternalInterface.avaliable=false, a default of "/" will be used. * * @private * @param {String} opt_pageURL (Optional) User-specified Page URL to assign * metrics to at the back-end. * * @return {String} Final page URL to assign metrics to at the back-end. */ private function _renderPageURL( pageURL:String = "" ):String { var pathname:String = _info.locationPath; var search:String = _info.locationSearch; if( !pageURL || (pageURL == "") ) { pageURL = pathname + unescape( search ); if ( pageURL == "" ) { pageURL = "/"; } } return pageURL; } /** * Page title, which is a URL-encoded string. * <p><b>Example :</b></p> * <pre class="prettyprint">utmdt=analytics%20page%20test</pre> */ public function get utmdt():String { return _info.documentTitle; } /** * Hit id for revenue per page tracking for AdSense. * <p><b>Example :</b><code class="prettyprint">utmhid=2059107202</code></p> */ public function get utmhid():String { return String( _generateHitId() ); } /** * Referral, complete URL. * <p><b>Example :</b><code class="prettyprint">utmr=http://www.example.com/aboutUs/index.php?var=selected</code></p> */ public function get utmr():String { if( !_utmr ) { return "-"; } return _utmr; } /** * Page request of the current page. * <p><b>Example :</b><code class="prettyprint">utmp=/testDirectory/myPage.html</code></p> */ public function get utmp():String { return _renderPageURL( _pageURL ); } /** * Returns a Variables object representation. * @return a Variables object representation. */ public function toVariables():Variables { var variables:Variables = new Variables(); variables.URIencode = true; if( _config.detectTitle && ( utmdt != "") ) { variables.utmdt = utmdt; } variables.utmhid = utmhid; variables.utmr = utmr; variables.utmp = utmp; return variables; } /** * Returns the url String representation of the object. * @return the url String representation of the object. */ public function toURLString():String { var v:Variables = toVariables(); return v.toString(); } } }
fix comment for asdoc
fix comment for asdoc
ActionScript
apache-2.0
jisobkim/gaforflash,mrthuanvn/gaforflash,jeremy-wischusen/gaforflash,drflash/gaforflash,DimaBaliakin/gaforflash,Vigmar/gaforflash,Vigmar/gaforflash,jisobkim/gaforflash,dli-iclinic/gaforflash,jeremy-wischusen/gaforflash,drflash/gaforflash,soumavachakraborty/gaforflash,DimaBaliakin/gaforflash,mrthuanvn/gaforflash,soumavachakraborty/gaforflash,dli-iclinic/gaforflash,Miyaru/gaforflash,Miyaru/gaforflash
e1ee831e0f68f3de6c7ca1b368a662bc94fdee5d
src/battlecode/client/viewer/render/ImageAssets.as
src/battlecode/client/viewer/render/ImageAssets.as
package battlecode.client.viewer.render { public class ImageAssets { // control bar background [Embed('/img/client/background.png')] public static const GRADIENT_BACKGROUND:Class; [Embed('/img/client/hud_unit_underlay.png')] public static const HUD_ARCHON_BACKGROUND:Class; // button icons [Embed('/img/client/icons/control_play.png')] public static const PLAY_ICON:Class; [Embed('/img/client/icons/control_pause.png')] public static const PAUSE_ICON:Class; [Embed('/img/client/icons/control_start.png')] public static const START_ICON:Class; [Embed('/img/client/icons/control_fastforward.png')] public static const FASTFORWARD_ICON:Class; [Embed('/img/client/icons/resultset_next.png')] public static const NEXT_ICON:Class; [Embed('/img/client/icons/resultset_previous.png')] public static const PREVIOUS_ICON:Class; [Embed('/img/client/icons/control_fastforward_blue.png')] public static const STEP_FORWARD_ICON:Class; [Embed('/img/client/icons/control_rewind_blue.png')] public static const STEP_BACKWARD_ICON:Class; [Embed('/img/client/icons/arrow_out.png')] public static const ENTER_FULLSCREEN_ICON:Class; [Embed('/img/client/icons/arrow_in.png')] public static const EXIT_FULLSCREEN_ICON:Class; [Embed('/img/client/icons/information.png')] public static const INFO_ICON:Class; // unit avatars [Embed('/img/units/archon0.png')] public static const ARCHON_A:Class; [Embed('/img/units/archon1.png')] public static const ARCHON_B:Class; [Embed('/img/units/archon2.png')] public static const ARCHON_NEUTRAL:Class; [Embed('/img/units/scout0.png')] public static const SCOUT_A:Class; [Embed('/img/units/scout1.png')] public static const SCOUT_B:Class; [Embed('/img/units/soldier0.png')] public static const SOLDIER_A:Class; [Embed('/img/units/soldier1.png')] public static const SOLDIER_B:Class; [Embed('/img/units/guard0.png')] public static const GUARD_A:Class; [Embed('/img/units/guard1.png')] public static const GUARD_B:Class; [Embed('/img/units/viper0.png')] public static const VIPER_A:Class; [Embed('/img/units/viper1.png')] public static const VIPER_B:Class; [Embed('/img/units/turret0.png')] public static const TURRET_A:Class; [Embed('/img/units/turret1.png')] public static const TURRET_B:Class; [Embed('/img/units/ttm0.png')] public static const TTM_A:Class; [Embed('/img/units/ttm1.png')] public static const TTM_B:Class; // zombie avatars [Embed('/img/units/zombieden3.png')] public static const ZOMBIEDEN_ZOMBIE:Class; [Embed('/img/units/standardzombie3.png')] public static const STANDARDZOMBIE_ZOMBIE:Class; [Embed('/img/units/rangedzombie3.png')] public static const RANGEDZOMBIE_ZOMBIE:Class; [Embed('/img/units/fastzombie3.png')] public static const FASTZOMBIE_ZOMBIE:Class; [Embed('/img/units/bigzombie3.png')] public static const BIGZOMBIE_ZOMBIE:Class; // explosions images [Embed('/img/explode/explode64_f01.png')] public static const EXPLODE_1:Class; [Embed('/img/explode/explode64_f02.png')] public static const EXPLODE_2:Class; [Embed('/img/explode/explode64_f03.png')] public static const EXPLODE_3:Class; [Embed('/img/explode/explode64_f04.png')] public static const EXPLODE_4:Class; [Embed('/img/explode/explode64_f05.png')] public static const EXPLODE_5:Class; [Embed('/img/explode/explode64_f06.png')] public static const EXPLODE_6:Class; [Embed('/img/explode/explode64_f07.png')] public static const EXPLODE_7:Class; [Embed('/img/explode/explode64_f08.png')] public static const EXPLODE_8:Class; [Embed('/img/hats/batman.png')] public static const HAT_BATMAN:Class; [Embed('/img/hats/bird.png')] public static const HAT_BIRD:Class; [Embed('/img/hats/bunny.png')] public static const HAT_BUNNY:Class; [Embed('/img/hats/christmas.png')] public static const HAT_CHRISTMAS:Class; [Embed('/img/hats/duck.png')] public static const HAT_DUCK:Class; [Embed('/img/hats/fedora.png')] public static const HAT_FEDORA:Class; [Embed('/img/hats/kipmud.png')] public static const HAT_KIPMUD:Class; [Embed('/img/hats/smiley.png')] public static const HAT_SMILEY:Class; public function ImageAssets() { } public static function getRobotAvatar(type:String, team:String):Class { return ImageAssets[type + "_" + team]; } private static const HATS:Array = [ HAT_BATMAN, HAT_BIRD, HAT_BUNNY, HAT_CHRISTMAS, HAT_DUCK, HAT_FEDORA, HAT_KIPMUD, HAT_SMILEY ]; public static function getHatAvatar(i:int):Class { return HATS[((i % HATS.length) + HATS.length) % HATS.length]; } } }
package battlecode.client.viewer.render { public class ImageAssets { // control bar background [Embed('/img/client/background.png')] public static const GRADIENT_BACKGROUND:Class; [Embed('/img/client/hud_unit_underlay.png')] public static const HUD_ARCHON_BACKGROUND:Class; // button icons [Embed('/img/client/icons/control_play.png')] public static const PLAY_ICON:Class; [Embed('/img/client/icons/control_pause.png')] public static const PAUSE_ICON:Class; [Embed('/img/client/icons/control_start.png')] public static const START_ICON:Class; [Embed('/img/client/icons/control_fastforward.png')] public static const FASTFORWARD_ICON:Class; [Embed('/img/client/icons/resultset_next.png')] public static const NEXT_ICON:Class; [Embed('/img/client/icons/resultset_previous.png')] public static const PREVIOUS_ICON:Class; [Embed('/img/client/icons/control_fastforward_blue.png')] public static const STEP_FORWARD_ICON:Class; [Embed('/img/client/icons/control_rewind_blue.png')] public static const STEP_BACKWARD_ICON:Class; [Embed('/img/client/icons/arrow_out.png')] public static const ENTER_FULLSCREEN_ICON:Class; [Embed('/img/client/icons/arrow_in.png')] public static const EXIT_FULLSCREEN_ICON:Class; [Embed('/img/client/icons/information.png')] public static const INFO_ICON:Class; // unit avatars [Embed('/img/units/archon0.png')] public static const ARCHON_A:Class; [Embed('/img/units/archon1.png')] public static const ARCHON_B:Class; [Embed('/img/units/archon2.png')] public static const ARCHON_NEUTRAL:Class; [Embed('/img/units/scout0.png')] public static const SCOUT_A:Class; [Embed('/img/units/scout1.png')] public static const SCOUT_B:Class; [Embed('/img/units/scout2.png')] public static const SCOUT_NEUTRAL:Class; [Embed('/img/units/soldier0.png')] public static const SOLDIER_A:Class; [Embed('/img/units/soldier1.png')] public static const SOLDIER_B:Class; [Embed('/img/units/soldier2.png')] public static const SOLDIER_NEUTRAL:Class; [Embed('/img/units/guard0.png')] public static const GUARD_A:Class; [Embed('/img/units/guard1.png')] public static const GUARD_B:Class; [Embed('/img/units/guard2.png')] public static const GUARD_NEUTRAL:Class; [Embed('/img/units/viper0.png')] public static const VIPER_A:Class; [Embed('/img/units/viper1.png')] public static const VIPER_B:Class; [Embed('/img/units/viper2.png')] public static const VIPER_NEUTRAL:Class; [Embed('/img/units/turret0.png')] public static const TURRET_A:Class; [Embed('/img/units/turret1.png')] public static const TURRET_B:Class; [Embed('/img/units/turret2.png')] public static const TURRET_NEUTRAL:Class; [Embed('/img/units/ttm0.png')] public static const TTM_A:Class; [Embed('/img/units/ttm1.png')] public static const TTM_B:Class; [Embed('/img/units/ttm2.png')] public static const TTM_NEUTRAL:Class; // zombie avatars [Embed('/img/units/zombieden3.png')] public static const ZOMBIEDEN_ZOMBIE:Class; [Embed('/img/units/standardzombie3.png')] public static const STANDARDZOMBIE_ZOMBIE:Class; [Embed('/img/units/rangedzombie3.png')] public static const RANGEDZOMBIE_ZOMBIE:Class; [Embed('/img/units/fastzombie3.png')] public static const FASTZOMBIE_ZOMBIE:Class; [Embed('/img/units/bigzombie3.png')] public static const BIGZOMBIE_ZOMBIE:Class; // explosions images [Embed('/img/explode/explode64_f01.png')] public static const EXPLODE_1:Class; [Embed('/img/explode/explode64_f02.png')] public static const EXPLODE_2:Class; [Embed('/img/explode/explode64_f03.png')] public static const EXPLODE_3:Class; [Embed('/img/explode/explode64_f04.png')] public static const EXPLODE_4:Class; [Embed('/img/explode/explode64_f05.png')] public static const EXPLODE_5:Class; [Embed('/img/explode/explode64_f06.png')] public static const EXPLODE_6:Class; [Embed('/img/explode/explode64_f07.png')] public static const EXPLODE_7:Class; [Embed('/img/explode/explode64_f08.png')] public static const EXPLODE_8:Class; [Embed('/img/hats/batman.png')] public static const HAT_BATMAN:Class; [Embed('/img/hats/bird.png')] public static const HAT_BIRD:Class; [Embed('/img/hats/bunny.png')] public static const HAT_BUNNY:Class; [Embed('/img/hats/christmas.png')] public static const HAT_CHRISTMAS:Class; [Embed('/img/hats/duck.png')] public static const HAT_DUCK:Class; [Embed('/img/hats/fedora.png')] public static const HAT_FEDORA:Class; [Embed('/img/hats/kipmud.png')] public static const HAT_KIPMUD:Class; [Embed('/img/hats/smiley.png')] public static const HAT_SMILEY:Class; public function ImageAssets() { } public static function getRobotAvatar(type:String, team:String):Class { return ImageAssets[type + "_" + team]; } private static const HATS:Array = [ HAT_BATMAN, HAT_BIRD, HAT_BUNNY, HAT_CHRISTMAS, HAT_DUCK, HAT_FEDORA, HAT_KIPMUD, HAT_SMILEY ]; public static function getHatAvatar(i:int):Class { return HATS[((i % HATS.length) + HATS.length) % HATS.length]; } } }
fix rendering of neutral units
fix rendering of neutral units
ActionScript
mit
trun/battlecode-webclient
c5d6d126a2f18a8db18bb59b4f56b44aa1664178
frameworks/as/projects/FlexJSJX/src/org/apache/flex/effects/Effect.as
frameworks/as/projects/FlexJSJX/src/org/apache/flex/effects/Effect.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.effects { import org.apache.flex.events.EventDispatcher; /** * Effect is the base class for effects in FlexJS. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Effect extends EventDispatcher implements IEffect { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * The <code>Effect.EFFECT_END</code> constant defines the value of the * event object's <code>type</code> property for a <code>effectEnd</code> event. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>cancelable</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>. </td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. * Use the <code>currentTarget</code> property to always access the * Object listening for the event.</td></tr> * </table> * * @eventType effectEnd * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const EFFECT_END:String = "effectEnd"; /** * The <code>Effect.EFFECT_START</code> constant defines the value of the * event object's <code>type</code> property for a <code>effectStart</code> event. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>cancelable</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>. </td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. * Use the <code>currentTarget</code> property to always access the * Object listening for the event.</td></tr> * </table> * * @eventType effectStart * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const EFFECT_START:String = "effectStart"; /** * The <code>Effect.EFFECT_STOP</code> constant defines the value of the * event object's <code>type</code> property for a <code>effectStop</code> event. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>cancelable</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>. </td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. * Use the <code>currentTarget</code> property to always access the * Object listening for the event.</td></tr> * </table> * * @eventType effectStop * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const EFFECT_STOP:String = "effectStop"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Effect() { } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // duration //---------------------------------- private var _duration:Number = 3000; /** * Duration of the animation, in milliseconds. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get duration():Number { return _duration; } public function set duration(value:Number):void { _duration = value; } /** * Plays the effect in reverse, * starting from the current position of the effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function reverse():void { } /** * Pauses the effect until you call the <code>resume()</code> method. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function pause():void { } /** * Stops the tween, ending it without dispatching an event or calling * the Tween's endFunction or <code>onTweenEnd()</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function play():void { } /** * Stops the tween, ending it without dispatching an event or calling * the Tween's endFunction or <code>onTweenEnd()</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function stop():void { } /** * Resumes the effect after it has been paused * by a call to the <code>pause()</code> method. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function resume():void { } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.effects { import org.apache.flex.events.EventDispatcher; /** * Effect is the base class for effects in FlexJS. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class Effect extends EventDispatcher implements IEffect { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * The <code>Effect.EFFECT_END</code> constant defines the value of the * event object's <code>type</code> property for a <code>effectEnd</code> event. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>cancelable</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>. </td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. * Use the <code>currentTarget</code> property to always access the * Object listening for the event.</td></tr> * </table> * * @eventType effectEnd * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const EFFECT_END:String = "effectEnd"; /** * The <code>Effect.EFFECT_START</code> constant defines the value of the * event object's <code>type</code> property for a <code>effectStart</code> event. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>cancelable</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>. </td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. * Use the <code>currentTarget</code> property to always access the * Object listening for the event.</td></tr> * </table> * * @eventType effectStart * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const EFFECT_START:String = "effectStart"; /** * The <code>Effect.EFFECT_STOP</code> constant defines the value of the * event object's <code>type</code> property for a <code>effectStop</code> event. * * <p>The properties of the event object have the following values:</p> * <table class="innertable"> * <tr><th>Property</th><th>Value</th></tr> * <tr><td><code>bubbles</code></td><td>false</td></tr> * <tr><td><code>cancelable</code></td><td>false</td></tr> * <tr><td><code>currentTarget</code></td><td>The Object that defines the * event listener that handles the event. For example, if you use * <code>myButton.addEventListener()</code> to register an event listener, * myButton is the value of the <code>currentTarget</code>. </td></tr> * <tr><td><code>target</code></td><td>The Object that dispatched the event; * it is not always the Object listening for the event. * Use the <code>currentTarget</code> property to always access the * Object listening for the event.</td></tr> * </table> * * @eventType effectStop * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const EFFECT_STOP:String = "effectStop"; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Effect() { } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // duration //---------------------------------- private var _duration:Number = 500; /** * Duration of the animation, in milliseconds. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get duration():Number { return _duration; } public function set duration(value:Number):void { _duration = value; } /** * Plays the effect in reverse, * starting from the current position of the effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function reverse():void { } /** * Pauses the effect until you call the <code>resume()</code> method. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function pause():void { } /** * Stops the tween, ending it without dispatching an event or calling * the Tween's endFunction or <code>onTweenEnd()</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function play():void { } /** * Stops the tween, ending it without dispatching an event or calling * the Tween's endFunction or <code>onTweenEnd()</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function stop():void { } /** * Resumes the effect after it has been paused * by a call to the <code>pause()</code> method. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function resume():void { } } }
change default duration
change default duration
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
bcb90305762c342449831926e244369c2216cdd4
flexEditor/src/org/arisgames/editor/view/CreateOrOpenGameSelectorView.as
flexEditor/src/org/arisgames/editor/view/CreateOrOpenGameSelectorView.as
package org.arisgames.editor.view { import flash.events.MouseEvent; import flash.utils.Dictionary; import mx.collections.ArrayCollection; import mx.containers.Panel; import mx.controls.Alert; import mx.controls.Button; import mx.controls.DataGrid; import mx.controls.TextArea; import mx.controls.TextInput; import mx.events.DynamicEvent; import mx.events.FlexEvent; import mx.rpc.Responder; import mx.rpc.events.ResultEvent; import org.arisgames.editor.data.Game; import org.arisgames.editor.data.PlaceMark; import org.arisgames.editor.data.arisserver.Item; import org.arisgames.editor.data.arisserver.Media; import org.arisgames.editor.data.arisserver.NPC; import org.arisgames.editor.data.arisserver.Node; import org.arisgames.editor.data.arisserver.WebPage; import org.arisgames.editor.data.businessobjects.ObjectPaletteItemBO; import org.arisgames.editor.models.GameModel; import org.arisgames.editor.models.SecurityModel; import org.arisgames.editor.models.StateModel; import org.arisgames.editor.services.AppServices; import org.arisgames.editor.util.AppConstants; import org.arisgames.editor.util.AppDynamicEventManager; import org.arisgames.editor.util.AppUtils; public class CreateOrOpenGameSelectorView extends Panel { [Bindable] public var nameOfGame:TextInput; [Bindable] public var gameDescription:TextArea; [Bindable] public var createGameButton:Button; [Bindable] public var gamesDataGrid:DataGrid; [Bindable] public var loadGameButton:Button; [Bindable] public var usersGames:ArrayCollection; /** * Constructor */ public function CreateOrOpenGameSelectorView() { super(); usersGames = new ArrayCollection(); this.addEventListener(FlexEvent.CREATION_COMPLETE, onComplete); } private function onComplete(event:FlexEvent): void { doubleClickEnabled = true; createGameButton.addEventListener(MouseEvent.CLICK, onCreateButtonClick); loadGameButton.addEventListener(MouseEvent.CLICK, onLoadButtonClick); gamesDataGrid.addEventListener(MouseEvent.DOUBLE_CLICK, onDoubleClick); AppServices.getInstance().loadGamesByUserId(SecurityModel.getInstance().getUserId(), new Responder(handleLoadUsersGames, handleFault)); AppDynamicEventManager.getInstance().addEventListener(AppConstants.APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED, handleCurrentStateChangedEvent); } private function handleCurrentStateChangedEvent(obj:Object):void { trace("CreateOrOpenGameSelectorView: handleCurrentStateChangedEvent"); if (StateModel.getInstance().currentState == StateModel.VIEWCREATEOROPENGAMEWINDOW){ trace("CreateOrOpenGameSelectorView: handleCurrentStateChangedEvent: Refreshing"); nameOfGame.text = ""; gameDescription.text = ""; usersGames.removeAll(); AppServices.getInstance().loadGamesByUserId(SecurityModel.getInstance().getUserId(), new Responder(handleLoadUsersGames, handleFault)); } } private function handleLoadUsersGames(obj:Object):void { trace("handleLoadUsersGames"); usersGames.removeAll(); if (obj.result.data == null) { trace("obj.result.data is NULL"); return; } for (var j:Number = 0; j < obj.result.data.list.length; j++) { var g:Game = new Game(); g.gameId = obj.result.data.list.getItemAt(j).game_id; g.name = obj.result.data.list.getItemAt(j).name; g.description = obj.result.data.list.getItemAt(j).description; g.iconMediaId = obj.result.data.list.getItemAt(j).icon_media_id; g.mediaId = obj.result.data.list.getItemAt(j).media_id; g.pcMediaId = obj.result.data.list.getItemAt(j).pc_media_id; g.introNodeId = obj.result.data.list.getItemAt(j).on_launch_node_id; g.completeNodeId = obj.result.data.list.getItemAt(j).game_complete_node_id; g.allowsPlayerCreatedLocations = obj.result.data.list.getItemAt(j).allow_player_created_locations; g.resetDeletesPlayerCreatedLocations = obj.result.data.list.getItemAt(j).delete_player_locations_on_reset; g.isLocational = obj.result.data.list.getItemAt(j).is_locational; g.readyForPublic = obj.result.data.list.getItemAt(j).ready_for_public; usersGames.addItem(g); } trace("done loading UsersGames."); } private function onCreateButtonClick(evt:MouseEvent):void { trace("create button clicked!"); var g:Game = new Game(); GameModel.getInstance().game = g; g.name = nameOfGame.text; g.description = gameDescription.text; AppServices.getInstance().saveGame(g, new Responder(handleCreateGame, handleFault)); } private function onLoadButtonClick(evt:MouseEvent):void { trace("load button clicked!"); //make sure something is happening if(gamesDataGrid.selectedItem != null){ var g:Game = gamesDataGrid.selectedItem as Game; trace("Selected game to load data for has Id = " + g.gameId); // Load the game into the app's models GameModel.getInstance().game = g; GameModel.getInstance().game.placeMarks.removeAll(); GameModel.getInstance().game.gameObjects.removeAll(); GameModel.getInstance().loadLocations(); StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR; } } private function onDoubleClick(evt:MouseEvent):void { trace("Double Click"); //make sure something is happening if(gamesDataGrid.selectedItem != null){ var g:Game = gamesDataGrid.selectedItem as Game; trace("Selected game to load data for has Id = " + g.gameId); // Load the game into the app's models GameModel.getInstance().game = g; GameModel.getInstance().game.placeMarks.removeAll(); GameModel.getInstance().game.gameObjects.removeAll(); GameModel.getInstance().loadLocations(); StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR; } } public function handleCreateGame(obj:Object):void { trace("Result called with obj = " + obj + "; Result = " + obj.result); if (obj.result.returnCode != 0) { trace("Bad create game attempt... let's see what happened."); var msg:String = obj.result.returnCodeDescription; Alert.show("Error Was: " + msg, "Error While Creating Game"); } else { trace("Game Creation was successfull"); GameModel.getInstance().game.gameId = obj.result.data; GameModel.getInstance().game.name = nameOfGame.text; GameModel.getInstance().game.description = gameDescription.text; Alert.show("Your game was succesfully created. Please use the editor to start building it.", "Successfully Created Game"); //Clear everything from previous loads of other games GameModel.getInstance().game.placeMarks.removeAll(); GameModel.getInstance().game.gameObjects.removeAll(); GameModel.getInstance().loadLocations(); StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR; } } public function handleFault(obj:Object):void { trace("Fault called. The error is: " + obj.fault.faultString); Alert.show("Error occurred: " + obj.fault.faultString, "More problems.."); } } }
package org.arisgames.editor.view { import flash.events.MouseEvent; import flash.utils.Dictionary; import mx.collections.ArrayCollection; import mx.containers.Panel; import mx.controls.Alert; import mx.controls.Button; import mx.controls.DataGrid; import mx.controls.TextArea; import mx.controls.TextInput; import mx.events.DynamicEvent; import mx.events.FlexEvent; import mx.rpc.Responder; import mx.rpc.events.ResultEvent; import org.arisgames.editor.data.Game; import org.arisgames.editor.data.PlaceMark; import org.arisgames.editor.data.arisserver.Item; import org.arisgames.editor.data.arisserver.Media; import org.arisgames.editor.data.arisserver.NPC; import org.arisgames.editor.data.arisserver.Node; import org.arisgames.editor.data.arisserver.WebPage; import org.arisgames.editor.data.businessobjects.ObjectPaletteItemBO; import org.arisgames.editor.models.GameModel; import org.arisgames.editor.models.SecurityModel; import org.arisgames.editor.models.StateModel; import org.arisgames.editor.services.AppServices; import org.arisgames.editor.util.AppConstants; import org.arisgames.editor.util.AppDynamicEventManager; import org.arisgames.editor.util.AppUtils; public class CreateOrOpenGameSelectorView extends Panel { [Bindable] public var nameOfGame:TextInput; [Bindable] public var gameDescription:TextArea; [Bindable] public var createGameButton:Button; [Bindable] public var gamesDataGrid:DataGrid; [Bindable] public var loadGameButton:Button; [Bindable] public var usersGames:ArrayCollection; /** * Constructor */ public function CreateOrOpenGameSelectorView() { super(); usersGames = new ArrayCollection(); this.addEventListener(FlexEvent.CREATION_COMPLETE, onComplete); } private function onComplete(event:FlexEvent): void { doubleClickEnabled = true; createGameButton.addEventListener(MouseEvent.CLICK, onCreateButtonClick); loadGameButton.addEventListener(MouseEvent.CLICK, onLoadButtonClick); gamesDataGrid.addEventListener(MouseEvent.DOUBLE_CLICK, onDoubleClick); AppServices.getInstance().loadGamesByUserId(SecurityModel.getInstance().getUserId(), new Responder(handleLoadUsersGames, handleFault)); AppDynamicEventManager.getInstance().addEventListener(AppConstants.APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED, handleCurrentStateChangedEvent); } private function handleCurrentStateChangedEvent(obj:Object):void { trace("CreateOrOpenGameSelectorView: handleCurrentStateChangedEvent"); if (StateModel.getInstance().currentState == StateModel.VIEWCREATEOROPENGAMEWINDOW){ trace("CreateOrOpenGameSelectorView: handleCurrentStateChangedEvent: Refreshing"); nameOfGame.text = ""; gameDescription.text = ""; usersGames.removeAll(); AppServices.getInstance().loadGamesByUserId(SecurityModel.getInstance().getUserId(), new Responder(handleLoadUsersGames, handleFault)); } } private function handleLoadUsersGames(obj:Object):void { trace("handleLoadUsersGames"); usersGames.removeAll(); if (obj.result.data == null) { trace("obj.result.data is NULL"); return; } for (var j:Number = 0; j < obj.result.data.list.length; j++) { var g:Game = new Game(); g.gameId = obj.result.data.list.getItemAt(j).game_id; g.name = obj.result.data.list.getItemAt(j).name; g.description = obj.result.data.list.getItemAt(j).description; g.iconMediaId = obj.result.data.list.getItemAt(j).icon_media_id; g.mediaId = obj.result.data.list.getItemAt(j).media_id; g.pcMediaId = obj.result.data.list.getItemAt(j).pc_media_id; g.introNodeId = obj.result.data.list.getItemAt(j).on_launch_node_id; g.completeNodeId = obj.result.data.list.getItemAt(j).game_complete_node_id; g.allowsPlayerCreatedLocations = obj.result.data.list.getItemAt(j).allow_player_created_locations; g.resetDeletesPlayerCreatedLocations = obj.result.data.list.getItemAt(j).delete_player_locations_on_reset; g.isLocational = obj.result.data.list.getItemAt(j).is_locational; g.readyForPublic = obj.result.data.list.getItemAt(j).ready_for_public; usersGames.addItem(g); } trace("done loading UsersGames."); } private function onCreateButtonClick(evt:MouseEvent):void { trace("create button clicked!"); var g:Game = new Game(); GameModel.getInstance().game = g; g.name = nameOfGame.text; g.description = gameDescription.text; AppServices.getInstance().saveGame(g, new Responder(handleCreateGame, handleFault)); } private function onLoadButtonClick(evt:MouseEvent):void { trace("load button clicked!"); //make sure something is happening if(gamesDataGrid.selectedItem != null){ var g:Game = gamesDataGrid.selectedItem as Game; trace("Selected game to load data for has Id = " + g.gameId); // Load the game into the app's models GameModel.getInstance().game = g; GameModel.getInstance().game.placeMarks.removeAll(); GameModel.getInstance().game.gameObjects.removeAll(); GameModel.getInstance().loadLocations(); StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR; var de:DynamicEvent = new DynamicEvent(AppConstants.DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR); AppDynamicEventManager.getInstance().dispatchEvent(de); } } private function onDoubleClick(evt:MouseEvent):void { trace("Double Click"); //make sure something is happening if(gamesDataGrid.selectedItem != null){ var g:Game = gamesDataGrid.selectedItem as Game; trace("Selected game to load data for has Id = " + g.gameId); // Load the game into the app's models GameModel.getInstance().game = g; GameModel.getInstance().game.placeMarks.removeAll(); GameModel.getInstance().game.gameObjects.removeAll(); GameModel.getInstance().loadLocations(); StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR; var de:DynamicEvent = new DynamicEvent(AppConstants.DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR); AppDynamicEventManager.getInstance().dispatchEvent(de); } } public function handleCreateGame(obj:Object):void { trace("Result called with obj = " + obj + "; Result = " + obj.result); if (obj.result.returnCode != 0) { trace("Bad create game attempt... let's see what happened."); var msg:String = obj.result.returnCodeDescription; Alert.show("Error Was: " + msg, "Error While Creating Game"); } else { trace("Game Creation was successfull"); GameModel.getInstance().game.gameId = obj.result.data; GameModel.getInstance().game.name = nameOfGame.text; GameModel.getInstance().game.description = gameDescription.text; Alert.show("Your game was succesfully created. Please use the editor to start building it.", "Successfully Created Game"); //Clear everything from previous loads of other games GameModel.getInstance().game.placeMarks.removeAll(); GameModel.getInstance().game.gameObjects.removeAll(); GameModel.getInstance().loadLocations(); StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR; } } public function handleFault(obj:Object):void { trace("Fault called. The error is: " + obj.fault.faultString); Alert.show("Error occurred: " + obj.fault.faultString, "More problems.."); } } }
Delete modals on game switch
Delete modals on game switch
ActionScript
mit
inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,augustozuniga/arisgames
744a1b0b67e721d95849ec093da7e924fab54322
src/main/actionscript/com/dotfold/dotvimstat/view/summary/UserSummary.as
src/main/actionscript/com/dotfold/dotvimstat/view/summary/UserSummary.as
package com.dotfold.dotvimstat.view.summary { import com.dotfold.dotvimstat.model.image.EntityImage; import com.dotfold.dotvimstat.view.IView; import com.dotfold.dotvimstat.view.animation.ElementAnimationSequencer; import com.dotfold.dotvimstat.view.event.UserSummaryEvent; import flash.display.Graphics; import flash.display.Loader; import flash.display.Shape; import flash.events.Event; import flash.events.MouseEvent; import flash.net.URLRequest; import modena.core.ElementContent; import modena.ui.Label; import modena.ui.Stack; /** * Displays the User name and profile picture. * * @author jamesmcnamee * */ public class UserSummary extends Stack implements IView { public static const ELEMENT_NAME:String = "userSummary"; [Inject] public var animationQueue:ElementAnimationSequencer; private var _userNameLabel:Label; private var _loader:Loader; /** * Constructor. */ public function UserSummary() { super(); } /** * @inheritDocs */ override protected function createElementContent():ElementContent { var content:ElementContent = super.createElementContent(); _loader = new Loader(); _loader.alpha = 0; _userNameLabel = new Label("titleLabel"); _userNameLabel.alpha = 0; setupClickHandler(); mouseEnabled = true; buttonMode = true; useHandCursor = true; content.addChild(_loader); content.addChild(_userNameLabel); return content; } /** * Update the username label text. */ public function set displayName(value:String):void { _userNameLabel.text = value; invalidateRender(); } /** * Sets the image URL and triggers the load operation for the image. */ public function set image(value:EntityImage):void { loadUserImage(value.url); } /** * Set up the <code>MouseEvent</code> handler on the click element. */ private function setupClickHandler():void { addEventListener(MouseEvent.CLICK, elementClickHandler); } /** * Dispatches <code>UserSummaryEvent.VISIT_PROFILE</code> to Mediator. */ private function elementClickHandler(event:MouseEvent):void { dispatchEvent(new UserSummaryEvent(UserSummaryEvent.VISIT_PROFILE)); } /** * Loads the user image. */ private function loadUserImage(url:String):void { _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete); _loader.load(new URLRequest(url)); } /** * Add elements to the sequencer and start animation. */ private function animateElements():void { animationQueue .addElement(_loader) .addElement(_userNameLabel) .play(); } /** * Image load completed successfully. Sets up mask and * adds to the display list. */ private function loadComplete(event:Event):void { validationManager.validateNow(); var imageIndex:int = getChildIndex(_loader); var mask:Shape = new Shape(); paintShape(mask); content.addChildAt(mask, imageIndex); _loader.mask = mask; _loader.x = 0; _loader.y = 0; var overlay:Shape = new Shape(); paintShape(overlay, 0x000000, 0.5); content.addChildAt(overlay, getChildIndex(_userNameLabel)); animateElements(); } /** * Paints a <code>Shape</code> Graphics with fill. */ private function paintShape(element:Shape, color:uint = 0x000000, alpha:Number = 0.0):void { var g:Graphics = element.graphics; g.clear(); g.beginFill(color, alpha); g.drawRect(0, 0, width, height); g.endFill(); } } }
package com.dotfold.dotvimstat.view.summary { import com.dotfold.dotvimstat.model.image.EntityImage; import com.dotfold.dotvimstat.view.IView; import com.dotfold.dotvimstat.view.animation.ElementAnimationSequencer; import com.dotfold.dotvimstat.view.event.UserSummaryEvent; import flash.display.Graphics; import flash.display.Loader; import flash.display.Shape; import flash.events.Event; import flash.events.MouseEvent; import flash.net.URLRequest; import modena.core.ElementContent; import modena.ui.Label; import modena.ui.Stack; /** * Displays the User name and profile picture. * * @author jamesmcnamee * */ public class UserSummary extends Stack implements IView { public static const ELEMENT_NAME:String = "userSummary"; [Inject] public var animationQueue:ElementAnimationSequencer; private var _userNameLabel:Label; private var _loader:Loader; /** * Constructor. */ public function UserSummary() { super(); } /** * @inheritDocs */ override protected function createElementContent():ElementContent { var content:ElementContent = super.createElementContent(); _loader = new Loader(); _loader.alpha = 0; _userNameLabel = new Label("titleLabel"); _userNameLabel.alpha = 0; setupClickHandler(); mouseEnabled = true; buttonMode = true; useHandCursor = true; content.addChild(_loader); content.addChild(_userNameLabel); return content; } /** * Update the username label text. */ public function set displayName(value:String):void { _userNameLabel.text = value; invalidateRender(); } /** * Sets the image URL and triggers the load operation for the image. */ public function set image(value:EntityImage):void { loadUserImage(value.url); } /** * Set up the <code>MouseEvent</code> handler on the click element. */ private function setupClickHandler():void { addEventListener(MouseEvent.CLICK, elementClickHandler); } /** * Dispatches <code>UserSummaryEvent.VISIT_PROFILE</code> to Mediator. */ private function elementClickHandler(event:MouseEvent):void { dispatchEvent(new UserSummaryEvent(UserSummaryEvent.VISIT_PROFILE)); } /** * Loads the user image. */ private function loadUserImage(url:String):void { _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete); _loader.load(new URLRequest(url)); } /** * Add elements to the sequencer and start animation. */ private function animateElements():void { animationQueue .addElement(_loader) .addElement(_userNameLabel) .play(); } /** * Image load completed successfully. Sets up mask and * adds to the display list. */ private function loadComplete(event:Event):void { validationManager.validateNow(); var imageIndex:int = getChildIndex(_loader); var mask:Shape = new Shape(); paintShape(mask); content.addChildAt(mask, imageIndex); _loader.mask = mask; _loader.x = 0; _loader.y = 0; var overlay:Shape = new Shape(); paintShape(overlay, 0x000000, 0.65); content.addChildAt(overlay, getChildIndex(_userNameLabel)); animateElements(); } /** * Paints a <code>Shape</code> Graphics with fill. */ private function paintShape(element:Shape, color:uint = 0x000000, alpha:Number = 0.0):void { var g:Graphics = element.graphics; g.clear(); g.beginFill(color, alpha); g.drawRect(0, 0, width, height); g.endFill(); } } }
increase alpha on user image overlay
[feat] increase alpha on user image overlay
ActionScript
mit
dotfold/dotvimstat
058ee738a208e32d39cb5931102c97f829f67b84
source/fairygui/GLoader.as
source/fairygui/GLoader.as
package fairygui { import fairygui.display.Image; import fairygui.display.MovieClip; import fairygui.utils.ToolSet; import laya.display.Node; import laya.display.Sprite; import laya.maths.Rectangle; import laya.resource.Texture; import laya.utils.Handler; public class GLoader extends GObject implements IAnimationGear,IColorGear { private var _url: String; private var _align: String; private var _valign: String; private var _autoSize: Boolean; private var _fill: int; private var _showErrorSign: Boolean; private var _playing: Boolean; private var _frame: Number = 0; private var _color: String; private var _contentItem: PackageItem; private var _contentSourceWidth: Number = 0; private var _contentSourceHeight: Number = 0; private var _contentWidth: Number = 0; private var _contentHeight: Number = 0; private var _content:Sprite; private var _errorSign: GObject; private var _updatingLayout: Boolean; private static var _errorSignPool: GObjectPool = new GObjectPool(); public function GLoader () { super(); this._playing = true; this._url = ""; this._fill = LoaderFillType.None; this._align = "left"; this._valign = "top"; this._showErrorSign = true; this._color = "#FFFFFF"; } override protected function createDisplayObject(): void { super.createDisplayObject(); this._displayObject.mouseEnabled = true; } override public function dispose(): void { if(this._contentItem == null && (this._content is Image)) { var texture: Texture = Image(this._content).tex; if(texture != null) this.freeExternal(texture); } super.dispose(); } public function get url(): String { return this._url; } public function set url(value: String):void { if (this._url == value) return; this._url = value; this.loadContent(); updateGear(7); } override public function get icon():String { return _url; } override public function set icon(value:String):void { this.url = value; } public function get align(): String { return this._align; } public function set align(value: String):void { if (this._align != value) { this._align = value; this.updateLayout(); } } public function get verticalAlign(): String { return this._valign; } public function set verticalAlign(value: String):void { if (this._valign != value) { this._valign = value; this.updateLayout(); } } public function get fill(): int { return this._fill; } public function set fill(value: int):void { if (this._fill != value) { this._fill = value; this.updateLayout(); } } public function get autoSize(): Boolean { return this._autoSize; } public function set autoSize(value: Boolean):void { if (this._autoSize != value) { this._autoSize = value; this.updateLayout(); } } public function get playing(): Boolean { return this._playing; } public function set playing(value: Boolean):void { if (this._playing != value) { this._playing = value; if (this._content is MovieClip) MovieClip(this._content).playing = value; this.updateGear(5); } } public function get frame(): Number { return this._frame; } public function set frame(value: Number):void { if (this._frame != value) { this._frame = value; if (this._content is MovieClip) MovieClip(this._content).currentFrame = value; this.updateGear(5); } } public function get color(): String { return this._color; } public function set color(value: String):void { if(this._color != value) { this._color = value; this.updateGear(4); this.applyColor(); } } private function applyColor(): void { //todo: } public function get showErrorSign(): Boolean { return this._showErrorSign; } public function set showErrorSign(value: Boolean):void { this._showErrorSign = value; } public function get content(): Node { return this._content; } protected function loadContent(): void { this.clearContent(); if (!this._url) return; if(ToolSet.startsWith(this._url,"ui://")) this.loadFromPackage(this._url); else this.loadExternal(); } protected function loadFromPackage(itemURL: String):void { this._contentItem = UIPackage.getItemByURL(itemURL); if(this._contentItem != null) { this._contentItem.load(); if(_autoSize) this.setSize(_contentItem.width, _contentItem.height); if(this._contentItem.type == PackageItemType.Image) { if(this._contentItem.texture == null) { this.setErrorState(); } else { if(!(this._content is Image)) { this._content = new Image(); this._displayObject.addChild(this._content); } else this._displayObject.addChild(this._content); Image(this._content).tex = this._contentItem.texture; Image(this._content).scale9Grid = this._contentItem.scale9Grid; Image(this._content).scaleByTile = this._contentItem.scaleByTile; Image(this._content).tileGridIndice = this._contentItem.tileGridIndice; this._contentSourceWidth = this._contentItem.width; this._contentSourceHeight = this._contentItem.height; this.updateLayout(); } } else if(this._contentItem.type == PackageItemType.MovieClip) { if(!(this._content is MovieClip)) { this._content = new MovieClip(); this._displayObject.addChild(this._content); } else this._displayObject.addChild(this._content); this._contentSourceWidth = this._contentItem.width; this._contentSourceHeight = this._contentItem.height; MovieClip(this._content).interval = this._contentItem.interval; MovieClip(this._content).swing = this._contentItem.swing; MovieClip(this._content).repeatDelay = this._contentItem.repeatDelay; MovieClip(this._content).frames = this._contentItem.frames; MovieClip(this._content).boundsRect = new Rectangle(0,0,this._contentSourceWidth,this._contentSourceHeight); this.updateLayout(); } else this.setErrorState(); } else this.setErrorState(); } protected function loadExternal(): void { AssetProxy.inst.load(this._url, Handler.create(this, this.__getResCompleted)); } protected function freeExternal(texture: Texture): void { } protected function onExternalLoadSuccess(texture: Texture): void { if(!(this._content is Image)) { this._content = new Image(); this._displayObject.addChild(this._content); } else this._displayObject.addChild(this._content); Image(this._content).tex = texture; Image(this._content).scale9Grid = null; Image(this._content).scaleByTile = false; this._contentSourceWidth = texture.width; this._contentSourceHeight = texture.height; this.updateLayout(); } protected function onExternalLoadFailed(): void { this.setErrorState(); } private function __getResCompleted(tex:Texture): void { if(tex!=null) this.onExternalLoadSuccess(tex); else this.onExternalLoadFailed(); } private function setErrorState(): void { if (!this._showErrorSign) return; if (this._errorSign == null) { if (fairygui.UIConfig.loaderErrorSign != null) { this._errorSign = GLoader._errorSignPool.getObject(fairygui.UIConfig.loaderErrorSign); } } if (this._errorSign != null) { this._errorSign.setSize(this.width, this.height); this._displayObject.addChild(this._errorSign.displayObject); } } private function clearErrorState(): void { if (this._errorSign != null) { this._displayObject.removeChild(this._errorSign.displayObject); GLoader._errorSignPool.returnObject(this._errorSign); this._errorSign = null; } } private function updateLayout(): void { if (this._content == null) { if (this._autoSize) { this._updatingLayout = true; this.setSize(50, 30); this._updatingLayout = false; } return; } this._content.x = 0; this._content.y = 0; this._content.scaleX = 1; this._content.scaleY = 1; this._contentWidth = this._contentSourceWidth; this._contentHeight = this._contentSourceHeight; if (this._autoSize) { this._updatingLayout = true; if (this._contentWidth == 0) this._contentWidth = 50; if (this._contentHeight == 0) this._contentHeight = 30; this.setSize(this._contentWidth, this._contentHeight); this._updatingLayout = false; if(_contentWidth==_width && _contentHeight==_height) return; } var sx: Number = 1, sy: Number = 1; if(_fill!=LoaderFillType.None) { sx = this.width/_contentSourceWidth; sy = this.height/_contentSourceHeight; if(sx!=1 || sy!=1) { if (_fill == LoaderFillType.ScaleMatchHeight) sx = sy; else if (_fill == LoaderFillType.ScaleMatchWidth) sy = sx; else if (_fill == LoaderFillType.Scale) { if (sx > sy) sx = sy; else sy = sx; } else if (_fill == LoaderFillType.ScaleNoBorder) { if (sx > sy) sy = sx; else sx = sy; } _contentWidth = _contentSourceWidth * sx; _contentHeight = _contentSourceHeight * sy; } } if (this._content is Image) Image(this._content).scaleTexture(sx, sy); else this._content.scale(sx, sy); if (this._align == "center") this._content.x = Math.floor((this.width - this._contentWidth) / 2); else if (this._align == "right") this._content.x = this.width - this._contentWidth; if (this._valign == "middle") this._content.y = Math.floor((this.height - this._contentHeight) / 2); else if (this._valign == "bottom") this._content.y = this.height - this._contentHeight; } private function clearContent(): void { this.clearErrorState(); if (this._content != null && this._content.parent != null) this._displayObject.removeChild(this._content); if(this._contentItem == null && (this._content is Image)) { var texture: Texture = Image(this._content).tex; if(texture != null) this.freeExternal(texture); } this._contentItem = null; } override protected function handleSizeChanged(): void { super.handleSizeChanged(); if(!this._updatingLayout) this.updateLayout(); } override public function setup_beforeAdd(xml: Object): void { super.setup_beforeAdd(xml); var str: String; str = xml.getAttribute("url"); if (str) this._url = str; str = xml.getAttribute("align"); if (str) this._align = str; str = xml.getAttribute("vAlign"); if (str) this._valign = str; str = xml.getAttribute("fill"); if (str) this._fill = LoaderFillType.parse(str); this._autoSize = xml.getAttribute("autoSize") == "true"; str = xml.getAttribute("errorSign"); if (str) this._showErrorSign = str == "true"; this._playing = xml.getAttribute("playing") != "false"; str = xml.getAttribute("color"); if(str) this.color = str; if (this._url) this.loadContent(); } } }
package fairygui { import fairygui.display.Image; import fairygui.display.MovieClip; import fairygui.utils.ToolSet; import laya.display.Node; import laya.display.Sprite; import laya.maths.Rectangle; import laya.resource.Texture; import laya.utils.Handler; public class GLoader extends GObject implements IAnimationGear,IColorGear { private var _url: String; private var _align: String; private var _valign: String; private var _autoSize: Boolean; private var _fill: int; private var _shrinkOnly:Boolean; private var _showErrorSign: Boolean; private var _playing: Boolean; private var _frame: Number = 0; private var _color: String; private var _contentItem: PackageItem; private var _contentSourceWidth: Number = 0; private var _contentSourceHeight: Number = 0; private var _contentWidth: Number = 0; private var _contentHeight: Number = 0; private var _content:Sprite; private var _errorSign: GObject; private var _content2:GComponent; private var _updatingLayout: Boolean; private static var _errorSignPool: GObjectPool = new GObjectPool(); public function GLoader () { super(); this._playing = true; this._url = ""; this._fill = LoaderFillType.None; this._align = "left"; this._valign = "top"; this._showErrorSign = true; this._color = "#FFFFFF"; } override protected function createDisplayObject(): void { super.createDisplayObject(); this._displayObject.mouseEnabled = true; } override public function dispose(): void { if(this._contentItem == null && (this._content is Image)) { var texture: Texture = Image(this._content).tex; if(texture != null) this.freeExternal(texture); } if(_content2!=null) _content2.dispose(); super.dispose(); } public function get url(): String { return this._url; } public function set url(value: String):void { if (this._url == value) return; this._url = value; this.loadContent(); updateGear(7); } override public function get icon():String { return _url; } override public function set icon(value:String):void { this.url = value; } public function get align(): String { return this._align; } public function set align(value: String):void { if (this._align != value) { this._align = value; this.updateLayout(); } } public function get verticalAlign(): String { return this._valign; } public function set verticalAlign(value: String):void { if (this._valign != value) { this._valign = value; this.updateLayout(); } } public function get fill(): int { return this._fill; } public function set fill(value: int):void { if (this._fill != value) { this._fill = value; this.updateLayout(); } } public function get shrinkOnly():Boolean { return _shrinkOnly; } public function set shrinkOnly(value:Boolean):void { if(_shrinkOnly!=value) { _shrinkOnly = value; updateLayout(); } } public function get autoSize(): Boolean { return this._autoSize; } public function set autoSize(value: Boolean):void { if (this._autoSize != value) { this._autoSize = value; this.updateLayout(); } } public function get playing(): Boolean { return this._playing; } public function set playing(value: Boolean):void { if (this._playing != value) { this._playing = value; if (this._content is MovieClip) MovieClip(this._content).playing = value; this.updateGear(5); } } public function get frame(): Number { return this._frame; } public function set frame(value: Number):void { if (this._frame != value) { this._frame = value; if (this._content is MovieClip) MovieClip(this._content).currentFrame = value; this.updateGear(5); } } public function get color(): String { return this._color; } public function set color(value: String):void { if(this._color != value) { this._color = value; this.updateGear(4); this.applyColor(); } } private function applyColor(): void { //todo: } public function get showErrorSign(): Boolean { return this._showErrorSign; } public function set showErrorSign(value: Boolean):void { this._showErrorSign = value; } public function get content(): Node { return this._content; } public function get component():GComponent { return _content2; } protected function loadContent(): void { this.clearContent(); if (!this._url) return; if(ToolSet.startsWith(this._url,"ui://")) this.loadFromPackage(this._url); else this.loadExternal(); } protected function loadFromPackage(itemURL: String):void { this._contentItem = UIPackage.getItemByURL(itemURL); if(this._contentItem != null) { this._contentItem.load(); if(_autoSize) this.setSize(_contentItem.width, _contentItem.height); if(this._contentItem.type == PackageItemType.Image) { if(this._contentItem.texture == null) { this.setErrorState(); } else { if(!(this._content is Image)) { this._content = new Image(); this._displayObject.addChild(this._content); } else this._displayObject.addChild(this._content); Image(this._content).tex = this._contentItem.texture; Image(this._content).scale9Grid = this._contentItem.scale9Grid; Image(this._content).scaleByTile = this._contentItem.scaleByTile; Image(this._content).tileGridIndice = this._contentItem.tileGridIndice; this._contentSourceWidth = this._contentItem.width; this._contentSourceHeight = this._contentItem.height; this.updateLayout(); } } else if(this._contentItem.type == PackageItemType.MovieClip) { if(!(this._content is MovieClip)) { this._content = new MovieClip(); this._displayObject.addChild(this._content); } else this._displayObject.addChild(this._content); this._contentSourceWidth = this._contentItem.width; this._contentSourceHeight = this._contentItem.height; MovieClip(this._content).interval = this._contentItem.interval; MovieClip(this._content).swing = this._contentItem.swing; MovieClip(this._content).repeatDelay = this._contentItem.repeatDelay; MovieClip(this._content).frames = this._contentItem.frames; MovieClip(this._content).boundsRect = new Rectangle(0,0,this._contentSourceWidth,this._contentSourceHeight); this.updateLayout(); } else if(_contentItem.type==PackageItemType.Component) { var obj:GObject = UIPackage.createObjectFromURL(itemURL); if(!obj) setErrorState(); else if(!(obj is GComponent)) { obj.dispose(); setErrorState(); } else { _content2 = obj.asCom; this._displayObject.addChild(_content2.displayObject); _contentSourceWidth = _contentItem.width; _contentSourceHeight = _contentItem.height; updateLayout(); } } else this.setErrorState(); } else this.setErrorState(); } protected function loadExternal(): void { AssetProxy.inst.load(this._url, Handler.create(this, this.__getResCompleted)); } protected function freeExternal(texture: Texture): void { } protected function onExternalLoadSuccess(texture: Texture): void { if(!(this._content is Image)) { this._content = new Image(); this._displayObject.addChild(this._content); } else this._displayObject.addChild(this._content); Image(this._content).tex = texture; Image(this._content).scale9Grid = null; Image(this._content).scaleByTile = false; this._contentSourceWidth = texture.width; this._contentSourceHeight = texture.height; this.updateLayout(); } protected function onExternalLoadFailed(): void { this.setErrorState(); } private function __getResCompleted(tex:Texture): void { if(tex!=null) this.onExternalLoadSuccess(tex); else this.onExternalLoadFailed(); } private function setErrorState(): void { if (!this._showErrorSign) return; if (this._errorSign == null) { if (fairygui.UIConfig.loaderErrorSign != null) { this._errorSign = GLoader._errorSignPool.getObject(fairygui.UIConfig.loaderErrorSign); } } if (this._errorSign != null) { this._errorSign.setSize(this.width, this.height); this._displayObject.addChild(this._errorSign.displayObject); } } private function clearErrorState(): void { if (this._errorSign != null) { this._displayObject.removeChild(this._errorSign.displayObject); GLoader._errorSignPool.returnObject(this._errorSign); this._errorSign = null; } } private function updateLayout(): void { if (_content2==null && this._content == null) { if (this._autoSize) { this._updatingLayout = true; this.setSize(50, 30); this._updatingLayout = false; } return; } this._contentWidth = this._contentSourceWidth; this._contentHeight = this._contentSourceHeight; if (this._autoSize) { this._updatingLayout = true; if (this._contentWidth == 0) this._contentWidth = 50; if (this._contentHeight == 0) this._contentHeight = 30; this.setSize(this._contentWidth, this._contentHeight); this._updatingLayout = false; if(_contentWidth==_width && _contentHeight==_height) { if(_content2!=null) { _content2.setXY(0, 0); _content2.setScale(1, 1); } else { _content.x = 0; _content.y = 0; _content.scaleX = 1; _content.scaleY = 1; } return; } } var sx: Number = 1, sy: Number = 1; if(_fill!=LoaderFillType.None) { sx = this.width/_contentSourceWidth; sy = this.height/_contentSourceHeight; if(sx!=1 || sy!=1) { if (_fill == LoaderFillType.ScaleMatchHeight) sx = sy; else if (_fill == LoaderFillType.ScaleMatchWidth) sy = sx; else if (_fill == LoaderFillType.Scale) { if (sx > sy) sx = sy; else sy = sx; } else if (_fill == LoaderFillType.ScaleNoBorder) { if (sx > sy) sy = sx; else sx = sy; } if (_shrinkOnly && sx >= 1 && sy >= 1) sx = sy = 1; _contentWidth = _contentSourceWidth * sx; _contentHeight = _contentSourceHeight * sy; } } if(_content2!=null) _content2.setScale(sx, sy); else if (this._content is Image) Image(this._content).scaleTexture(sx, sy); else this._content.scale(sx, sy); var nx:Number, ny:Number; if (this._align == "center") nx = Math.floor((this.width - this._contentWidth) / 2); else if (this._align == "right") nx = this.width - this._contentWidth; else nx = 0; if (this._valign == "middle") ny = Math.floor((this.height - this._contentHeight) / 2); else if (this._valign == "bottom") ny = this.height - this._contentHeight; else ny = 0; if(_content2!=null) _content2.setXY(nx, ny); else { _content.x = nx; _content.y = ny; } } private function clearContent(): void { this.clearErrorState(); if (this._content != null && this._content.parent != null) this._displayObject.removeChild(this._content); if(this._contentItem == null && (this._content is Image)) { var texture: Texture = Image(this._content).tex; if(texture != null) this.freeExternal(texture); } if(_content2!=null) { _content2.dispose(); _content2 = null; } this._contentItem = null; } override protected function handleSizeChanged(): void { super.handleSizeChanged(); if(!this._updatingLayout) this.updateLayout(); } override public function setup_beforeAdd(xml: Object): void { super.setup_beforeAdd(xml); var str: String; str = xml.getAttribute("url"); if (str) this._url = str; str = xml.getAttribute("align"); if (str) this._align = str; str = xml.getAttribute("vAlign"); if (str) this._valign = str; str = xml.getAttribute("fill"); if (str) this._fill = LoaderFillType.parse(str); _shrinkOnly = xml.getAttribute("shrinkOnly") == "true"; this._autoSize = xml.getAttribute("autoSize") == "true"; str = xml.getAttribute("errorSign"); if (str) this._showErrorSign = str == "true"; this._playing = xml.getAttribute("playing") != "false"; str = xml.getAttribute("color"); if(str) this.color = str; if (this._url) this.loadContent(); } } }
Allow GLoader to load component.
Allow GLoader to load component.
ActionScript
mit
fairygui/FairyGUI-layabox,fairygui/FairyGUI-layabox
a0d479fbc4a5ab5fccc98ce9edc1b33e7456a184
src/Modi/ManagedContext.as
src/Modi/ManagedContext.as
/* * This is free software; you can redistribute it and/or modify it under the * terms of MIT free software license as published by the Massachusetts * Institute of Technology. * * Copyright 2012. Vjekoslav Krajacic, Tomislav Podhraski */ package Modi { import Core.Assert; import flash.utils.Dictionary; public class ManagedContext { private var _managedObjects:Dictionary; private var _idCounter:uint; public function ManagedContext() { _managedObjects = new Dictionary(); _idCounter = 0; } public function addToContext(managedObject:ManagedObject):void { var id:ManagedObjectId = new ManagedObjectId("id_" + _idCounter); _managedObjects[id.objectId] = managedObject; managedObject.contextId = new ManagedObjectId(id); _idCounter++; } public function removeFromContext(id:ManagedObjectId):void { Assert(_managedObjects[id.objectId], "ManagedObject with " + id.objectId + " does not exist!"); _managedObjects[id.objectId] = null; } public function getManagedObjectById(id:ManagedObjectId):ManagedObject { var managedObject:ManagedObject = _managedObjects[id.objectId]; return managedObject; } public function createManagedObject(ObjectClass:Class):* { var object:* = new ObjectClass(); this.addToContext(object); return object; } } }
/* * This is free software; you can redistribute it and/or modify it under the * terms of MIT free software license as published by the Massachusetts * Institute of Technology. * * Copyright 2012. Vjekoslav Krajacic, Tomislav Podhraski */ package Modi { import Core.Assert; import flash.utils.Dictionary; public class ManagedContext { private var _managedObjects:Dictionary; private var _idCounter:uint; public function ManagedContext() { _managedObjects = new Dictionary(); _idCounter = 0; } public function addToContext(managedObject:ManagedObject):void { var id:ManagedObjectId = new ManagedObjectId("id_" + _idCounter); _managedObjects[id.objectId] = managedObject; managedObject.contextId = new ManagedObjectId(id.objectId); _idCounter++; } public function removeFromContext(id:ManagedObjectId):void { Assert(_managedObjects[id.objectId], "ManagedObject with " + id.objectId + " does not exist!"); _managedObjects[id.objectId] = null; } public function getManagedObjectById(id:ManagedObjectId):ManagedObject { var managedObject:ManagedObject = _managedObjects[id.objectId]; return managedObject; } public function createManagedObject(ObjectClass:Class):* { var object:* = new ObjectClass(); this.addToContext(object); return object; } } }
Fix in managed context
Fix in managed context
ActionScript
mit
justpinegames/Modi
90ff08f21b0c8fe337ce6706009b2741c1b5b451
collect-client/src/main/flex/org/openforis/collect/presenter/JobMonitor.as
collect-client/src/main/flex/org/openforis/collect/presenter/JobMonitor.as
package org.openforis.collect.presenter { import flash.events.EventDispatcher; import flash.events.TimerEvent; import flash.utils.Timer; import mx.rpc.AsyncResponder; import mx.rpc.events.ResultEvent; import org.openforis.collect.Application; import org.openforis.collect.client.ClientFactory; import org.openforis.collect.concurrency.CollectJobStatusPopUp; import org.openforis.collect.event.CollectJobEvent; import org.openforis.collect.i18n.Message; import org.openforis.collect.remoting.service.concurrency.proxy.ApplicationLockingJobProxy; import org.openforis.concurrency.proxy.JobProxy; import org.openforis.concurrency.proxy.JobProxy$Status; /** * @author S. Ricci */ public class JobMonitor extends AbstractPresenter { private static const STATUS_UPDATE_DELAY:int = 2000; private var _progressTimer:Timer; private var jobId:String; private var _job:JobProxy; public function JobMonitor(jobId:String) { super(null); this.jobId = jobId; } public function start():void { if ( _progressTimer == null ) { _progressTimer = new Timer(STATUS_UPDATE_DELAY); _progressTimer.addEventListener(TimerEvent.TIMER, progressTimerHandler); } _progressTimer.start(); } public function get currentJob():JobProxy { return _job; } protected function stop():void { if ( _progressTimer != null ) { _progressTimer.stop(); _progressTimer = null; } } protected function progressTimerHandler(event:TimerEvent):void { loadCurrentJobAndUpdateState(); } private function loadCurrentJobAndUpdateState():void { function onComplete():void { if (_job == null || ! _job.running) { stop(); } if (CollectJobStatusPopUp.popUpOpen) { CollectJobStatusPopUp.setActiveJob(_job); } else { CollectJobStatusPopUp.openPopUp(_job); } dispatchJobUpdateEvent(); } loadJob(function():void { onComplete(); }); } private function loadJob(complete:Function):void { ClientFactory.collectJobClient.getJob(new AsyncResponder( function(event:ResultEvent, token:Object = null):void { _job = event.result as JobProxy; complete(); }, faultHandler), jobId); } private function dispatchJobUpdateEvent():void { if (_job != null) { eventDispatcher.dispatchEvent(new CollectJobEvent(CollectJobEvent.COLLECT_JOB_STATUS_UPDATE, _job)); if (_job.completed || _job.aborted || _job.failed) { eventDispatcher.dispatchEvent(new CollectJobEvent(CollectJobEvent.COLLECT_JOB_END, _job)); } } } } }
package org.openforis.collect.presenter { import flash.events.EventDispatcher; import flash.events.TimerEvent; import flash.utils.Timer; import mx.rpc.AsyncResponder; import mx.rpc.events.ResultEvent; import org.openforis.collect.Application; import org.openforis.collect.client.ClientFactory; import org.openforis.collect.concurrency.CollectJobStatusPopUp; import org.openforis.collect.event.CollectJobEvent; import org.openforis.collect.i18n.Message; import org.openforis.collect.remoting.service.concurrency.proxy.ApplicationLockingJobProxy; import org.openforis.concurrency.proxy.JobProxy; import org.openforis.concurrency.proxy.JobProxy$Status; /** * @author S. Ricci */ public class JobMonitor extends AbstractPresenter { private static const STATUS_UPDATE_DELAY:int = 2000; private var _progressTimer:Timer; private var jobId:String; private var _job:JobProxy; public function JobMonitor(jobId:String) { super(null); this.jobId = jobId; } public function start():void { if ( _progressTimer == null ) { _progressTimer = new Timer(STATUS_UPDATE_DELAY); _progressTimer.addEventListener(TimerEvent.TIMER, progressTimerHandler); } _progressTimer.start(); } public function get currentJob():JobProxy { return _job; } protected function stop():void { if ( _progressTimer != null ) { _progressTimer.stop(); _progressTimer = null; } } protected function progressTimerHandler(event:TimerEvent):void { loadCurrentJobAndUpdateState(); } private function loadCurrentJobAndUpdateState():void { function onComplete():void { if (_job == null || ! _job.running) { stop(); } if (CollectJobStatusPopUp.popUpOpen) { CollectJobStatusPopUp.setActiveJob(_job); } else { CollectJobStatusPopUp.openPopUp(_job); } dispatchJobUpdateEvent(); } loadJob(function():void { onComplete(); }); } private function loadJob(complete:Function):void { ClientFactory.collectJobClient.getJob(new AsyncResponder( function(event:ResultEvent, token:Object = null):void { _job = event.result as JobProxy; complete(); }, faultHandler), jobId); } private function dispatchJobUpdateEvent():void { if (_job != null) { eventDispatcher.dispatchEvent(new CollectJobEvent(CollectJobEvent.COLLECT_JOB_STATUS_UPDATE, _job)); if (_job.completed || _job.aborted || _job.failed) { eventDispatcher.dispatchEvent(new CollectJobEvent(CollectJobEvent.COLLECT_JOB_END, _job)); stop(); } } } } }
Stop job monitoring timer when job is complete
Stop job monitoring timer when job is complete
ActionScript
mit
openforis/collect,openforis/collect,openforis/collect,openforis/collect
9102a931962cccb6dc801158ace29331d65145a7
actionscript/src/com/chartboost/plugin/air/CBLocation.as
actionscript/src/com/chartboost/plugin/air/CBLocation.as
package com.chartboost.plugin.air { public final class CBLocation { public static const DEFAULT:String = "Default"; public static const STARTUP:String = "Startup"; public static const HOME_SCREEN:String = "Home Screen"; public static const MAIN_MENU:String = "Main Menu"; public static const GAME_SCREEN:String = "Game Screen"; public static const ACHIEVEMENTS:String = "Achievements"; public static const QUESTS:String = "Quests"; public static const PAUSE:String = "Pause"; public static const LEVEL_START:String = "Level Start"; public static const LEVEL_COMPLETE:String = "Pause"; public static const IAP_STORE:String = "IAP Store"; public static const ITEM_STORE:String = "Item Store"; public static const GAME_OVER:String = "Game Over"; public static const LEADERBOARD:String = "Leaderboard"; public static const SETTINGS:String = "Settings"; public static const QUIT:String = "Quit"; } }
package com.chartboost.plugin.air { public final class CBLocation { public static const DEFAULT:String = "Default"; public static const STARTUP:String = "Startup"; public static const HOME_SCREEN:String = "Home Screen"; public static const MAIN_MENU:String = "Main Menu"; public static const GAME_SCREEN:String = "Game Screen"; public static const ACHIEVEMENTS:String = "Achievements"; public static const QUESTS:String = "Quests"; public static const PAUSE:String = "Pause"; public static const LEVEL_START:String = "Level Start"; public static const LEVEL_COMPLETE:String = "Level Complete"; public static const IAP_STORE:String = "IAP Store"; public static const ITEM_STORE:String = "Item Store"; public static const GAME_OVER:String = "Game Over"; public static const LEADERBOARD:String = "Leaderboard"; public static const SETTINGS:String = "Settings"; public static const QUIT:String = "Quit"; } }
Update CBLocation.as
Update CBLocation.as Fixed wrong string for LEVEL_COMPLETE constant.
ActionScript
mit
thenitro/air,thenitro/air,thenitro/air,ChartBoost/air,ChartBoost/air,ChartBoost/air
807165e6fcc8fff83c0ebe4dcc5896bae860ca67
src/as/com/threerings/flash/path/Path.as
src/as/com/threerings/flash/path/Path.as
// // $Id$ package com.threerings.flash.path { import flash.display.DisplayObject; import flash.events.Event; import flash.utils.getTimer; /** * Moves a display object along a particular path in a specified amount of time. */ public /*abstract*/ class Path { /** * Moves the specified display object from the specified starting coordinates to the specified * ending coordinates in the specified number of milliseconds. */ public static function move (target :DisplayObject, startx :int, starty :int, destx :int, desty :int, duration :int) :Path { return new LinePath(target, new LinearFunc(startx, destx), new LinearFunc(starty, desty), duration); } /** * Moves the specified display object from its current location to the specified ending * coordinates in the specified number of milliseconds. <em>NOTE:</em> beware the fact that * Flash does not immediately apply a display object's location update, so setting x and y and * then calling moveTo() will not work. Use {@link #move} instead. */ public static function moveTo (target :DisplayObject, destx :int, desty :int, duration :int) :Path { return move(target, target.x, target.y, destx, desty, duration); } /** * Creates a delay path of the desired duration. For use with CompositePath. */ public static function delay (delay :int) :Path { return new DelayPath(delay); } /** * Creates a path that executes the supplied sequence of paths one after the other. */ public static function connect (... paths) :Path { return new CompositePath(paths); } /** * Starts this path. The path will be ticked once immediately and subsequently ticked every * frame. * * @param onComplete an optional function to be called when it completes (or is aborted). * @param startOffset an optional number of milliseconds by which to adjust the time at which * the path believes that it was started. */ public function start () :void { _target.addEventListener(Event.ENTER_FRAME, onEnterFrame); willStart(getTimer(), 0); } /** * Configures this path's onStart function. The function should have the following signature: * <code>function (path :Path) :void</code>. This should only be called before the path is * started. * * @return a reference to this path, for easy chaining. */ public function setOnStart (onStart :Function) :Path { _onStart = onStart; return this; } /** * Configures this path's onComplete function. The function should have the following * signature: <code>function (path :Path) :void</code>. This should generally only be called * shortly after construction as the function will not be called if the path is already * completed or aborted. * * @return a reference to this path, for easy chaining. */ public function setOnComplete (onComplete :Function) :Path { _onComplete = onComplete; return this; } /** * Aborts this path. Any onComplete() function will be called as if the path terminated * normally. The callback can call {@link #wasAborted} to discover whether the path was aborted * or terminated normally. */ public function abort () :void { pathCompleted(true); } /** * Returns the target of this path. */ public function get target () :DisplayObject { return _target; } /** * Returns true if this path was aborted, false if it completed normally. This return value is * only valid during a call to onComplete(). */ public function wasAborted () :Boolean { return _wasAborted; } /** * Derived classes must call this method to wire this path up to its target. */ protected function init (target :DisplayObject) :void { _target = target; } /** * Called when this path is about to start, either due to a call to {@link #start} or to the * path being started by a {@link CompositePath}. */ protected function willStart (now :int, startOffset :int = 0) :int { _startStamp = now + startOffset; if (_onStart != null) { _onStart(this); } return tick(now); } /** * Derived classes should override this method and update their target based on the current * timestamp. They should return a positive number, indicating the number of milliseconds they * have remaining before they are complete, or zero if they completed perfectly on time, or a * negative number if they completed with milliseconds to spare since their last tick. */ protected function tick (curStamp :int) :int { return 0; } /** * Called when this path is has completed or was aborted. */ protected function didComplete (aborted :Boolean) :void { _wasAborted = aborted; if (_onComplete != null) { _onComplete(this); } } protected function onEnterFrame (event :Event) :void { if (tick(getTimer()) <= 0) { pathCompleted(false); } } protected function pathCompleted (aborted :Boolean) :void { _target.removeEventListener(Event.ENTER_FRAME, onEnterFrame); didComplete(aborted); } // needed by CompositePath protected static function tickPath (path :Path, curStamp :int) :int { return path.tick(curStamp); } // needed by CompositePath protected static function startPath (path :Path, curStamp :int, startOffset :int) :int { return path.willStart(curStamp, startOffset); } protected var _target :DisplayObject; protected var _onStart :Function; protected var _onComplete :Function; protected var _startStamp :int = -1; protected var _wasAborted :Boolean; } }
// // $Id$ package com.threerings.flash.path { import flash.display.DisplayObject; import flash.events.Event; import flash.utils.getTimer; /** * Moves a display object along a particular path in a specified amount of time. */ public /*abstract*/ class Path { /** * Moves the specified display object from the specified starting coordinates to the specified * ending coordinates in the specified number of milliseconds. */ public static function move (target :DisplayObject, startx :int, starty :int, destx :int, desty :int, duration :int) :Path { return new LinePath(target, new LinearFunc(startx, destx), new LinearFunc(starty, desty), duration); } /** * Moves the specified display object from its current location to the specified ending * coordinates in the specified number of milliseconds. <em>NOTE:</em> beware the fact that * Flash does not immediately apply a display object's location update, so setting x and y and * then calling moveTo() will not work. Use {@link #move} instead. */ public static function moveTo (target :DisplayObject, destx :int, desty :int, duration :int) :Path { return move(target, target.x, target.y, destx, desty, duration); } /** * Creates a delay path of the desired duration. For use with CompositePath. */ public static function delay (delay :int) :Path { return new DelayPath(delay); } /** * Creates a path that executes the supplied sequence of paths one after the other. */ public static function connect (... paths) :Path { return new CompositePath(paths); } /** * Starts this path. The path will be ticked once immediately and subsequently ticked every * frame. * * @param onComplete an optional function to be called when it completes (or is aborted). * @param startOffset an optional number of milliseconds by which to adjust the time at which * the path believes that it was started. */ public function start () :void { _target.addEventListener(Event.ENTER_FRAME, onEnterFrame); willStart(getTimer(), 0); } /** * Configures this path's onStart function. The function should have the following signature: * <code>function (path :Path) :void</code>. This should only be called before the path is * started. * * @return a reference to this path, for easy chaining. */ public function setOnStart (onStart :Function) :Path { _onStart = onStart; return this; } /** * Configures this path's onComplete function. The function should have the following * signature: <code>function (path :Path) :void</code>. This should generally only be called * shortly after construction as the function will not be called if the path is already * completed or aborted. * * @return a reference to this path, for easy chaining. */ public function setOnComplete (onComplete :Function) :Path { _onComplete = onComplete; return this; } /** * Aborts this path. Any onComplete() function will be called as if the path terminated * normally. The callback can call {@link #wasAborted} to discover whether the path was aborted * or terminated normally. */ public function abort () :void { pathCompleted(true); } /** * Returns the target of this path. */ public function get target () :DisplayObject { return _target; } /** * Returns true if this path was aborted, false if it completed normally. This return value is * only valid during a call to onComplete(). */ public function wasAborted () :Boolean { return _wasAborted; } /** * Derived classes must call this method to wire this path up to its target. */ protected function init (target :DisplayObject) :void { _target = target; } /** * Called when this path is about to start, either due to a call to {@link #start} or to the * path being started by a {@link CompositePath}. */ protected function willStart (now :int, startOffset :int = 0) :int { _startStamp = now + startOffset; if (_onStart != null) { _onStart(this); } var remain :int = tick(now); if (remain <= 0) { pathCompleted(false); } return remain; } /** * Derived classes should override this method and update their target based on the current * timestamp. They should return a positive number, indicating the number of milliseconds they * have remaining before they are complete, or zero if they completed perfectly on time, or a * negative number if they completed with milliseconds to spare since their last tick. */ protected function tick (curStamp :int) :int { return 0; } /** * Called when this path is has completed or was aborted. */ protected function didComplete (aborted :Boolean) :void { _wasAborted = aborted; if (_onComplete != null) { _onComplete(this); } } protected function onEnterFrame (event :Event) :void { if (tick(getTimer()) <= 0) { pathCompleted(false); } } protected function pathCompleted (aborted :Boolean) :void { _target.removeEventListener(Event.ENTER_FRAME, onEnterFrame); didComplete(aborted); } // needed by CompositePath protected static function tickPath (path :Path, curStamp :int) :int { return path.tick(curStamp); } // needed by CompositePath protected static function startPath (path :Path, curStamp :int, startOffset :int) :int { return path.willStart(curStamp, startOffset); } protected var _target :DisplayObject; protected var _onStart :Function; protected var _onComplete :Function; protected var _startStamp :int = -1; protected var _wasAborted :Boolean; } }
Make sure to perform the path completion steps if starting the path causes it to complete.
Make sure to perform the path completion steps if starting the path causes it to complete. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@375 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
6dee96bb156e0f0e4f5219cd6d8ca664e0047567
src/as/com/threerings/util/RingBuffer.as
src/as/com/threerings/util/RingBuffer.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { public class RingBuffer { /** Creates a new RingBuffer with the specified capacity. */ public function RingBuffer (capacity :uint = 1) { _capacity = capacity; _array.length = _capacity; } /** Returns the capacity of the RingBuffer. */ public function get capacity () :uint { return _capacity; } /** * Sets the capacity of the RingBuffer. * If the new capacity is less than the RingBuffer's length, * elements will be removed from the end of the RingBuffer * to accommodate the smaller capacity. */ public function set capacity (newCapacity :uint) :void { // Copy all the elements to a new array. var newArray :Array = new Array(); var newLength :uint = Math.min(_length, newCapacity); newArray.length = newCapacity; for (var i :uint = 0; i < newLength; ++i) { newArray[i] = this.at(i); } _capacity = newCapacity; _length = newLength; _array = newArray; _firstIndex = 0; } /** Returns the number of elements currently stored in the RingBuffer. */ public function get length () :uint { return _length; } /** Returns true if the RingBuffer contains 0 elements. */ public function get empty () :Boolean { return (0 == _length); } /** * Adds the specified elements to the front of the RingBuffer. * If the RingBuffer's length is equal to its capacity, this * will cause elements to be removed from the back of * the RingBuffer. * Returns the new length of the RingBuffer. */ public function unshift (...args) :uint { for (var i :int = args.length - 1; i >= 0; --i) { var index :uint = (_firstIndex > 0 ? _firstIndex - 1 : _capacity - 1); _array[index] = args[i]; _length = Math.min(_length + 1, _capacity); _firstIndex = index; } return _length; } /** * Adds the specified elements to the back of the RingBuffer. * If the RingBuffer's length is equal to its capacity, this * will cause a elements to be removed from the front of * the RingBuffer. * Returns the new length of the RingBuffer. */ public function push (...args) :uint { for (var i :uint = 0; i < args.length; ++i) { var index :uint = ((_firstIndex + _length) % _capacity); _array[index] = args[i]; _length = Math.min(_length + 1, _capacity); // did we overwrite the first index? if (index == _firstIndex && _length == _capacity) { _firstIndex = (_firstIndex < _capacity - 1 ? _firstIndex + 1 : 0); } } return _length; } /** * Removes the first element from the RingBuffer and returns it. * If the RingBuffer is empty, shift() will return undefined. */ public function shift () :* { if (this.empty) { return undefined; } var obj :* = _array[_firstIndex]; _array[_firstIndex] = undefined; _firstIndex = (_firstIndex < _capacity - 1 ? _firstIndex + 1 : 0); --_length; return obj; } /** * Removes the last element from the RingBuffer and returns it. * If the RingBuffer is empty, pop() will return undefined. */ public function pop () :* { if (this.empty) { return undefined; } var lastIndex :uint = ((_firstIndex + _length - 1) % _capacity); var obj :* = _array[lastIndex]; _array[lastIndex] = undefined; --_length; return obj; } /** Removes all elements from the RingBuffer. */ public function clear () :void { _array = new Array(); _array.length = _capacity; _length = 0; _firstIndex = 0; } /** * Returns the element at the specified index. * If index >= length, at() will return undefined. */ public function at (index :uint) :* { if (index >= _length) { return undefined; } else { var index :uint = ((_firstIndex + index) % _capacity); return _array[index]; } } /** * Executes a test function on each item in the ring buffer * until an item is reached that returns false for the specified * function. * * Returns a Boolean value of true if all items in the buffer return * true for the specified function; otherwise, false. */ public function every (callback :Function, thisObject :* = null) :Boolean { for (var i :int = 0; i < _length; ++i) { if (!callback.apply(thisObject, this.at(i))) { return false; } } return true; } /** * Executes a function on each item in the ring buffer. */ public function forEach (callback :Function, thisObject :* = null) :void { for (var i :int = 0; i < _length; ++i) { callback.apply(thisObject, this.at(i)); } } /** * Searches for an item in the ring buffer by using strict equality * (===) and returns the index position of the item, or -1 * if the item is not found. */ public function indexOf (searchElement :*, fromIndex :int = 0) :int { for (var i :int = 0; i < _length; ++i) { if (this.at(i) === searchElement) { return i; } } return -1; } protected var _array :Array = new Array(); protected var _capacity :uint; protected var _length :uint; protected var _firstIndex :uint; } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { public class RingBuffer { /** Creates a new RingBuffer with the specified capacity. */ public function RingBuffer (capacity :uint = 1) { _capacity = capacity; _array.length = _capacity; } /** Returns the capacity of the RingBuffer. */ public function get capacity () :uint { return _capacity; } /** * Sets the capacity of the RingBuffer. * If the new capacity is less than the RingBuffer's length, * elements will be removed from the end of the RingBuffer * to accommodate the smaller capacity. */ public function set capacity (newCapacity :uint) :void { // Copy all the elements to a new array. var newArray :Array = new Array(); var newLength :uint = Math.min(_length, newCapacity); newArray.length = newCapacity; for (var i :uint = 0; i < newLength; ++i) { newArray[i] = this.at(i); } _capacity = newCapacity; _length = newLength; _array = newArray; _firstIndex = 0; } /** Returns the number of elements currently stored in the RingBuffer. */ public function get length () :uint { return _length; } /** Returns true if the RingBuffer contains 0 elements. */ public function get empty () :Boolean { return (0 == _length); } /** * Adds the specified elements to the front of the RingBuffer. * If the RingBuffer's length is equal to its capacity, this * will cause elements to be removed from the back of * the RingBuffer. * Returns the new length of the RingBuffer. */ public function unshift (...args) :uint { for (var i :int = args.length - 1; i >= 0; --i) { var index :uint = (_firstIndex > 0 ? _firstIndex - 1 : _capacity - 1); _array[index] = args[i]; _length = Math.min(_length + 1, _capacity); _firstIndex = index; } return _length; } /** * Adds the specified elements to the back of the RingBuffer. * If the RingBuffer's length is equal to its capacity, this * will cause a elements to be removed from the front of * the RingBuffer. * Returns the new length of the RingBuffer. */ public function push (...args) :uint { for (var i :uint = 0; i < args.length; ++i) { var index :uint = ((_firstIndex + _length) % _capacity); _array[index] = args[i]; _length = Math.min(_length + 1, _capacity); // did we overwrite the first index? if (index == _firstIndex && _length == _capacity) { _firstIndex = (_firstIndex < _capacity - 1 ? _firstIndex + 1 : 0); } } return _length; } /** * Removes the first element from the RingBuffer and returns it. * If the RingBuffer is empty, shift() will return undefined. */ public function shift () :* { if (this.empty) { return undefined; } var obj :* = _array[_firstIndex]; _array[_firstIndex] = undefined; _firstIndex = (_firstIndex < _capacity - 1 ? _firstIndex + 1 : 0); --_length; return obj; } /** * Removes the last element from the RingBuffer and returns it. * If the RingBuffer is empty, pop() will return undefined. */ public function pop () :* { if (this.empty) { return undefined; } var lastIndex :uint = ((_firstIndex + _length - 1) % _capacity); var obj :* = _array[lastIndex]; _array[lastIndex] = undefined; --_length; return obj; } /** Removes all elements from the RingBuffer. */ public function clear () :void { _array = new Array(); _array.length = _capacity; _length = 0; _firstIndex = 0; } /** * Returns the element at the specified index. * If index >= length, at() will return undefined. */ public function at (index :uint) :* { if (index >= _length) { return undefined; } else { var index :uint = ((_firstIndex + index) % _capacity); return _array[index]; } } /** * Executes a test function on each item in the ring buffer * until an item is reached that returns false for the specified * function. * * Returns a Boolean value of true if all items in the buffer return * true for the specified function; otherwise, false. */ public function every (callback :Function, thisObject :* = null) :Boolean { for (var i :int = 0; i < _length; ++i) { if (!callback.call(thisObject, this.at(i))) { return false; } } return true; } /** * Executes a function on each item in the ring buffer. */ public function forEach (callback :Function, thisObject :* = null) :void { for (var i :int = 0; i < _length; ++i) { callback.call(thisObject, this.at(i)); } } /** * Searches for an item in the ring buffer by using strict equality * (===) and returns the index position of the item, or -1 * if the item is not found. */ public function indexOf (searchElement :*, fromIndex :int = 0) :int { for (var i :int = 0; i < _length; ++i) { if (this.at(i) === searchElement) { return i; } } return -1; } protected var _array :Array = new Array(); protected var _capacity :uint; protected var _length :uint; protected var _firstIndex :uint; } }
use Function.call(), not Function.apply()
use Function.call(), not Function.apply() git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4941 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
5d52f5f3fd0cf360a328ebc26aebf529355ac6a9
src/aerys/minko/type/Signal.as
src/aerys/minko/type/Signal.as
package aerys.minko.type { public final class Signal { private var _name : String = null; private var _callbacks : Array = []; private var _numCallbacks : uint = 0; private var _executed : Boolean = false; private var _numAdded : uint = 0; private var _toAdd : Array = null; private var _numRemoved : uint = 0; private var _toRemove : Array = null; public function get numCallbacks() : uint { return _numCallbacks; } public function Signal(name : String) { _name = name; } public function add(callback : Function) : void { if (_executed) { if (_toAdd) _toAdd.push(callback); else _toAdd = [callback]; ++_numAdded; return ; } _callbacks[_numCallbacks] = callback; ++_numCallbacks; } public function remove(callback : Function) : void { if (_executed) { if (_toRemove) _toRemove.push(callback); else _toRemove = [callback]; ++_numRemoved; return ; } var index : int = _callbacks.indexOf(callback); if (index < 0) throw new Error("This callback does not exist."); --_numCallbacks; _callbacks[index] = _callbacks[_numCallbacks]; _callbacks.length = _numCallbacks; } public function hasCallback(callback : Function) : Boolean { return _callbacks.indexOf(callback) >= 0; } public function execute(...params) : void { _executed = true; for (var i : uint = 0; i < _numCallbacks; ++i) (_callbacks[i] as Function).apply(null, params); _executed = false; for (i = 0; i < _numAdded; ++i) add(_toAdd[i]); _numAdded = 0; _toAdd = null; for (i = 0; i < _numRemoved; ++i) remove(_toRemove[i]); _numRemoved = 0; _toRemove = null; } } }
package aerys.minko.type { public final class Signal { private var _name : String = null; private var _callbacks : Array = []; private var _numCallbacks : uint = 0; private var _executed : Boolean = false; private var _numAdded : uint = 0; private var _toAdd : Array = null; private var _numRemoved : uint = 0; private var _toRemove : Array = null; public function get numCallbacks() : uint { return _numCallbacks; } public function Signal(name : String) { _name = name; } public function removeAllCallback() : void { for (var callbackIndex : int = _numCallbacks - 1; callbackIndex >= 0; --callbackIndex) remove(_callbacks[callbackIndex]); } public function add(callback : Function) : void { if (_executed) { if (_toAdd) _toAdd.push(callback); else _toAdd = [callback]; ++_numAdded; return ; } _callbacks[_numCallbacks] = callback; ++_numCallbacks; } public function remove(callback : Function) : void { if (_executed) { if (_toRemove) _toRemove.push(callback); else _toRemove = [callback]; ++_numRemoved; return ; } var index : int = _callbacks.indexOf(callback); if (index < 0) throw new Error("This callback does not exist."); --_numCallbacks; _callbacks[index] = _callbacks[_numCallbacks]; _callbacks.length = _numCallbacks; } public function hasCallback(callback : Function) : Boolean { return _callbacks.indexOf(callback) >= 0; } public function execute(...params) : void { _executed = true; for (var i : uint = 0; i < _numCallbacks; ++i) (_callbacks[i] as Function).apply(null, params); _executed = false; for (i = 0; i < _numAdded; ++i) add(_toAdd[i]); _numAdded = 0; _toAdd = null; for (i = 0; i < _numRemoved; ++i) remove(_toRemove[i]); _numRemoved = 0; _toRemove = null; } } }
Add removeAllCallback method for Signal
Add removeAllCallback method for Signal
ActionScript
mit
aerys/minko-as3
5aeb5ab0f07d57fc58e2239af16025763bdd80ab
src/as/com/threerings/flash/LoaderUtil.as
src/as/com/threerings/flash/LoaderUtil.as
// // $Id$ package com.threerings.flash { import flash.display.Loader; /** * Contains a utility method for safely unloading a Loader. */ public class LoaderUtil { /** * Safely unload the specified loader. */ public static function unload (loader :Loader) :void { try { loader.close(); } catch (e1 :Error) { // ignore } // try { // loader.unloadAndStop(); // } catch (e2 :Error) { // hmm, maybe they are using FP9 still try { loader.unload(); } catch (e3 :Error) { // ignore } // } } } }
// // $Id$ package com.threerings.flash { import flash.display.Loader; /** * Contains a utility method for safely unloading a Loader. */ public class LoaderUtil { /** * Safely unload the specified loader. */ public static function unload (loader :Loader) :void { try { loader.close(); } catch (e1 :Error) { // ignore } try { loader.unloadAndStop(); } catch (e2 :Error) { // hmm, maybe they are using FP9 still try { loader.unload(); } catch (e3 :Error) { // ignore } } } } }
Enable glorious unloadAndStop(). I did some tests with it, and it sure does put the kibosh on things.
Enable glorious unloadAndStop(). I did some tests with it, and it sure does put the kibosh on things. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@769 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
534f0d4b149d3b861ee17ff140a435b3436edb41
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2TSFileHandler.as
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2TSFileHandler.as
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the at.matthew.httpstreaming package. * * The Initial Developer of the Original Code is * Matthew Kaufman. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ package org.denivip.osmf.net.httpstreaming.hls { import flash.utils.ByteArray; import flash.utils.IDataInput; import com.hurlant.util.Hex; import org.denivip.osmf.utility.decrypt.AES; import org.osmf.logging.Log; import org.osmf.logging.Logger; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; [Event(name="notifySegmentDuration", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] [Event(name="notifyTimeBias", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] public class HTTPStreamingMP2TSFileHandler extends HTTPStreamingFileHandlerBase { private var _syncFound:Boolean; private var _pmtPID:uint; private var _audioPID:uint; private var _videoPID:uint; private var _mp3AudioPID:uint; private var _audioPES:HTTPStreamingMP2PESAudio; private var _videoPES:HTTPStreamingMP2PESVideo; private var _mp3audioPES:HTTPStreamingMp3Audio2ToPESAudio; private var _cachedOutputBytes:ByteArray; private var alternatingYieldCounter:int = 0; private var _key:HTTPStreamingM3U8IndexKey = null; private var _iv:ByteArray = null; private var _decryptBuffer:ByteArray = new ByteArray; // AES-128 specific variables private var _decryptAES:AES = null; public function HTTPStreamingMP2TSFileHandler() { _audioPES = new HTTPStreamingMP2PESAudio; _videoPES = new HTTPStreamingMP2PESVideo; _mp3audioPES = new HTTPStreamingMp3Audio2ToPESAudio; } override public function beginProcessFile(seek:Boolean, seekTime:Number):void { _syncFound = false; } override public function get inputBytesNeeded():Number { return _syncFound ? 187 : 1; } override public function processFileSegment(input:IDataInput):ByteArray { var bytesAvailableStart:uint = input.bytesAvailable; var output:ByteArray; if (_cachedOutputBytes !== null) { output = _cachedOutputBytes; _cachedOutputBytes = null; } else { output = new ByteArray(); } while (true) { if(!_syncFound) { if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 16) { if (_decryptBuffer.bytesAvailable < 1) { break; } } else { if (!decryptToBuffer(input, 16)) { break; } } if (_decryptBuffer.readByte() == 0x47) { _syncFound = true; } } } else { if(input.bytesAvailable < 1) break; if(input.readByte() == 0x47) _syncFound = true; } } else { _syncFound = false; var packet:ByteArray = new ByteArray(); if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 176) { if (_decryptBuffer.bytesAvailable < 187) { break; } } else { var bytesLeft:uint = input.bytesAvailable - 176; if (bytesLeft > 0 && bytesLeft < 15) { if (!decryptToBuffer(input, input.bytesAvailable)) { break; } } else { if (!decryptToBuffer(input, 176)) { break; } } } _decryptBuffer.readBytes(packet, 0, 187); } } else { if(input.bytesAvailable < 187) break; input.readBytes(packet, 0, 187); } var result:ByteArray = processPacket(packet); if (result !== null) { output.writeBytes(result); } if (bytesAvailableStart - input.bytesAvailable > 10000) { alternatingYieldCounter = (alternatingYieldCounter + 1) & 0x03; if (alternatingYieldCounter /*& 0x01 === 1*/) { _cachedOutputBytes = output; return null; } break; } } } output.position = 0; return output.length === 0 ? null : output; } private function decryptToBuffer(input:IDataInput, blockSize:int):Boolean{ if (_key) { // Clear buffer if (_decryptBuffer.bytesAvailable == 0) { _decryptBuffer.clear(); } if (_key.type == "AES-128" && blockSize % 16 == 0 && _key.key) { if (!_decryptAES) { _decryptAES = new AES(_key.key); _decryptAES.pad = "none"; _decryptAES.iv = _iv; } // Save buffer position var currentPosition:uint = _decryptBuffer.position; _decryptBuffer.position += _decryptBuffer.bytesAvailable; // Save block to decrypt var decrypt:ByteArray = new ByteArray; input.readBytes(decrypt, 0, blockSize); // Save new IV from ciphertext var newIv:ByteArray = new ByteArray; decrypt.position += (decrypt.bytesAvailable-16); decrypt.readBytes(newIv, 0, 16); decrypt.position = 0; // Decrypt if (input.bytesAvailable == 0) { _decryptAES.pad = "pkcs7"; } _decryptAES.decrypt(decrypt); decrypt.position = 0; // Write into buffer _decryptBuffer.writeBytes(decrypt); _decryptBuffer.position = currentPosition; // Update AES IV _decryptAES.iv = newIv; return true; } } return false; } override public function endProcessFile(input:IDataInput):ByteArray { _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; return null; } public function resetCache():void{ _cachedOutputBytes = null; alternatingYieldCounter = 0; _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set initialOffset(offset:Number):void{ offset *= 1000; // convert to ms _videoPES.initialTimestamp = offset; _audioPES.initialTimestamp = offset; _mp3audioPES.initialTimestamp = offset; } public function set key(key:HTTPStreamingM3U8IndexKey):void { _key = key; if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set iv(iv:String):void { if (iv) { _iv = Hex.toArray(iv); } } private function processPacket(packet:ByteArray):ByteArray { // decode rest of transport stream prefix (after the 0x47 flag byte) // top of second byte var value:uint = packet.readUnsignedByte(); //var tei:Boolean = Boolean(value & 0x80); // error indicator var pusi:Boolean = Boolean(value & 0x40); // payload unit start indication //var tpri:Boolean = Boolean(value & 0x20); // transport priority indication // bottom of second byte and all of third value <<= 8; value += packet.readUnsignedByte(); var pid:uint = value & 0x1fff; // packet ID // fourth byte value = packet.readUnsignedByte(); //var scramblingControl:uint = (value >> 6) & 0x03; // scrambling control bits var hasAF:Boolean = Boolean(value & 0x20); // has adaptation field var hasPD:Boolean = Boolean(value & 0x10); // has payload data //var ccount:uint = value & 0x0f; // continuty count // technically hasPD without hasAF is an error, see spec if(hasAF) { // process adaptation field // don't care about flags // don't care about clocks here var af:uint = packet.readUnsignedByte(); packet.position += af; // skip to end } return hasPD ? processES(pid, pusi, packet) : null; } private function processES(pid:uint, pusi:Boolean, packet:ByteArray):ByteArray { var output:ByteArray = null; if(pid == 0) // PAT { if(pusi) processPAT(packet); } else if(pid == _pmtPID) { if(pusi) processPMT(packet); } else if(pid == _audioPID) { output = _audioPES.processES(pusi, packet); } else if(pid == _videoPID) { output = _videoPES.processES(pusi, packet); } else if(pid == _mp3AudioPID) { output = _mp3audioPES.processES(pusi, packet); } return output; } private function processPAT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint packet.readUnsignedByte(); // tableID:uint var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring misc and reserved bits packet.position += 5; // skip tsid + version/cni + sec# + last sec# remaining -= 5; while(remaining > 4) { packet.readUnsignedShort(); // program number _pmtPID = packet.readUnsignedShort() & 0x1fff; // 13 bits remaining -= 4; //return; // immediately after reading the first pmt ID, if we don't we get the LAST one } // and ignore the CRC (4 bytes) } private function processPMT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint var tableID:uint = packet.readUnsignedByte(); if (tableID != 0x02) { CONFIG::LOGGING { logger.warn("PAT pointed to PMT that isn't PMT"); } return; // don't try to parse it } var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring section syntax and reserved packet.position += 7; // skip program num, rserved, version, cni, section num, last section num, reserved, PCR PID remaining -= 7; var piLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 2; packet.position += piLen; // skip program info remaining -= piLen; while(remaining > 4) { var type:uint = packet.readUnsignedByte(); var pid:uint = packet.readUnsignedShort() & 0x1fff; var esiLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 5; packet.position += esiLen; remaining -= esiLen; switch(type) { case 0x1b: // H.264 video _videoPID = pid; break; case 0x0f: // AAC Audio / ADTS _audioPID = pid; break; case 0x03: // MP3 Audio (3 & 4) case 0x04: _mp3AudioPID = pid; break; default: CONFIG::LOGGING { logger.error("unsupported type "+type.toString(16)+" in PMT"); } break; } } // and ignore CRC } override public function flushFileSegment(input:IDataInput):ByteArray { var flvBytes:ByteArray = new ByteArray(); var flvBytesVideo:ByteArray = _videoPES.processES(false, null, true); var flvBytesAudio:ByteArray = _audioPES.processES(false, null, true); if(flvBytesVideo) flvBytes.readBytes(flvBytesVideo); if(flvBytesAudio) flvBytes.readBytes(flvBytesAudio); return flvBytes; } CONFIG::LOGGING { private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2TSFileHandler') as Logger; } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the at.matthew.httpstreaming package. * * The Initial Developer of the Original Code is * Matthew Kaufman. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ package org.denivip.osmf.net.httpstreaming.hls { import flash.utils.ByteArray; import flash.utils.IDataInput; import com.hurlant.util.Hex; import org.denivip.osmf.utility.decrypt.AES; import org.osmf.logging.Log; import org.osmf.logging.Logger; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; [Event(name="notifySegmentDuration", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] [Event(name="notifyTimeBias", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] public class HTTPStreamingMP2TSFileHandler extends HTTPStreamingFileHandlerBase { private var _syncFound:Boolean; private var _pmtPID:uint; private var _audioPID:uint; private var _videoPID:uint; private var _mp3AudioPID:uint; private var _audioPES:HTTPStreamingMP2PESAudio; private var _videoPES:HTTPStreamingMP2PESVideo; private var _mp3audioPES:HTTPStreamingMp3Audio2ToPESAudio; private var _cachedOutputBytes:ByteArray; private var alternatingYieldCounter:int = 0; private var _key:HTTPStreamingM3U8IndexKey = null; private var _iv:ByteArray = null; private var _decryptBuffer:ByteArray = new ByteArray; // AES-128 specific variables private var _decryptAES:AES = null; public function HTTPStreamingMP2TSFileHandler() { _audioPES = new HTTPStreamingMP2PESAudio; _videoPES = new HTTPStreamingMP2PESVideo; _mp3audioPES = new HTTPStreamingMp3Audio2ToPESAudio; } override public function beginProcessFile(seek:Boolean, seekTime:Number):void { _syncFound = false; } override public function get inputBytesNeeded():Number { return _syncFound ? 187 : 1; } override public function processFileSegment(input:IDataInput):ByteArray { var bytesAvailableStart:uint = input.bytesAvailable; var output:ByteArray; if (_cachedOutputBytes !== null) { output = _cachedOutputBytes; _cachedOutputBytes = null; } else { output = new ByteArray(); } while (true) { if(!_syncFound) { if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 16) { if (_decryptBuffer.bytesAvailable < 1) { break; } } else { if (!decryptToBuffer(input, 16)) { break; } } if (_decryptBuffer.readByte() == 0x47) { _syncFound = true; } } } else { if(input.bytesAvailable < 1) break; if(input.readByte() == 0x47) _syncFound = true; } } else { var packet:ByteArray = new ByteArray(); if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 176) { if (_decryptBuffer.bytesAvailable < 187) { break; } } else { var bytesLeft:uint = input.bytesAvailable - 176; if (bytesLeft > 0 && bytesLeft < 15) { if (!decryptToBuffer(input, input.bytesAvailable)) { break; } } else { if (!decryptToBuffer(input, 176)) { break; } } } _decryptBuffer.readBytes(packet, 0, 187); } } else { if(input.bytesAvailable < 187) break; input.readBytes(packet, 0, 187); } _syncFound = false; var result:ByteArray = processPacket(packet); if (result !== null) { output.writeBytes(result); } if (bytesAvailableStart - input.bytesAvailable > 10000) { alternatingYieldCounter = (alternatingYieldCounter + 1) & 0x03; if (alternatingYieldCounter /*& 0x01 === 1*/) { _cachedOutputBytes = output; return null; } break; } } } output.position = 0; return output.length === 0 ? null : output; } private function decryptToBuffer(input:IDataInput, blockSize:int):Boolean{ if (_key) { // Clear buffer if (_decryptBuffer.bytesAvailable == 0) { _decryptBuffer.clear(); } if (_key.type == "AES-128" && blockSize % 16 == 0 && _key.key) { if (!_decryptAES) { _decryptAES = new AES(_key.key); _decryptAES.pad = "none"; _decryptAES.iv = _iv; } // Save buffer position var currentPosition:uint = _decryptBuffer.position; _decryptBuffer.position += _decryptBuffer.bytesAvailable; // Save block to decrypt var decrypt:ByteArray = new ByteArray; input.readBytes(decrypt, 0, blockSize); // Save new IV from ciphertext var newIv:ByteArray = new ByteArray; decrypt.position += (decrypt.bytesAvailable-16); decrypt.readBytes(newIv, 0, 16); decrypt.position = 0; // Decrypt if (input.bytesAvailable == 0) { _decryptAES.pad = "pkcs7"; } _decryptAES.decrypt(decrypt); decrypt.position = 0; // Write into buffer _decryptBuffer.writeBytes(decrypt); _decryptBuffer.position = currentPosition; // Update AES IV _decryptAES.iv = newIv; return true; } } return false; } override public function endProcessFile(input:IDataInput):ByteArray { _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; return null; } public function resetCache():void{ _cachedOutputBytes = null; alternatingYieldCounter = 0; _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set initialOffset(offset:Number):void{ offset *= 1000; // convert to ms _videoPES.initialTimestamp = offset; _audioPES.initialTimestamp = offset; _mp3audioPES.initialTimestamp = offset; } public function set key(key:HTTPStreamingM3U8IndexKey):void { _key = key; if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set iv(iv:String):void { if (iv) { _iv = Hex.toArray(iv); } } private function processPacket(packet:ByteArray):ByteArray { // decode rest of transport stream prefix (after the 0x47 flag byte) // top of second byte var value:uint = packet.readUnsignedByte(); //var tei:Boolean = Boolean(value & 0x80); // error indicator var pusi:Boolean = Boolean(value & 0x40); // payload unit start indication //var tpri:Boolean = Boolean(value & 0x20); // transport priority indication // bottom of second byte and all of third value <<= 8; value += packet.readUnsignedByte(); var pid:uint = value & 0x1fff; // packet ID // fourth byte value = packet.readUnsignedByte(); //var scramblingControl:uint = (value >> 6) & 0x03; // scrambling control bits var hasAF:Boolean = Boolean(value & 0x20); // has adaptation field var hasPD:Boolean = Boolean(value & 0x10); // has payload data //var ccount:uint = value & 0x0f; // continuty count // technically hasPD without hasAF is an error, see spec if(hasAF) { // process adaptation field // don't care about flags // don't care about clocks here var af:uint = packet.readUnsignedByte(); packet.position += af; // skip to end } return hasPD ? processES(pid, pusi, packet) : null; } private function processES(pid:uint, pusi:Boolean, packet:ByteArray):ByteArray { var output:ByteArray = null; if(pid == 0) // PAT { if(pusi) processPAT(packet); } else if(pid == _pmtPID) { if(pusi) processPMT(packet); } else if(pid == _audioPID) { output = _audioPES.processES(pusi, packet); } else if(pid == _videoPID) { output = _videoPES.processES(pusi, packet); } else if(pid == _mp3AudioPID) { output = _mp3audioPES.processES(pusi, packet); } return output; } private function processPAT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint packet.readUnsignedByte(); // tableID:uint var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring misc and reserved bits packet.position += 5; // skip tsid + version/cni + sec# + last sec# remaining -= 5; while(remaining > 4) { packet.readUnsignedShort(); // program number _pmtPID = packet.readUnsignedShort() & 0x1fff; // 13 bits remaining -= 4; //return; // immediately after reading the first pmt ID, if we don't we get the LAST one } // and ignore the CRC (4 bytes) } private function processPMT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint var tableID:uint = packet.readUnsignedByte(); if (tableID != 0x02) { CONFIG::LOGGING { logger.warn("PAT pointed to PMT that isn't PMT"); } return; // don't try to parse it } var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring section syntax and reserved packet.position += 7; // skip program num, rserved, version, cni, section num, last section num, reserved, PCR PID remaining -= 7; var piLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 2; packet.position += piLen; // skip program info remaining -= piLen; while(remaining > 4) { var type:uint = packet.readUnsignedByte(); var pid:uint = packet.readUnsignedShort() & 0x1fff; var esiLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 5; packet.position += esiLen; remaining -= esiLen; switch(type) { case 0x1b: // H.264 video _videoPID = pid; break; case 0x0f: // AAC Audio / ADTS _audioPID = pid; break; case 0x03: // MP3 Audio (3 & 4) case 0x04: _mp3AudioPID = pid; break; default: CONFIG::LOGGING { logger.error("unsupported type "+type.toString(16)+" in PMT"); } break; } } // and ignore CRC } override public function flushFileSegment(input:IDataInput):ByteArray { var flvBytes:ByteArray = new ByteArray(); var flvBytesVideo:ByteArray = _videoPES.processES(false, null, true); var flvBytesAudio:ByteArray = _audioPES.processES(false, null, true); if(flvBytesVideo) flvBytes.readBytes(flvBytesVideo); if(flvBytesAudio) flvBytes.readBytes(flvBytesAudio); return flvBytes; } CONFIG::LOGGING { private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2TSFileHandler') as Logger; } } }
Fix bug where syncFound was flagged as false incorrectly
Fix bug where syncFound was flagged as false incorrectly This was causing byte-level sync issues with throttled (and potentially other) streams
ActionScript
isc
denivip/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,mruse/osmf-hls-plugin
ce3ba0ffd86b8bb1569fd24f1cb2b5a6272cc3aa
src/aerys/minko/render/material/basic/BasicMaterial.as
src/aerys/minko/render/material/basic/BasicMaterial.as
package aerys.minko.render.material.basic { import aerys.minko.render.Effect; import aerys.minko.render.material.Material; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.type.binding.IDataProvider; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; public class BasicMaterial extends Material { public static const DEFAULT_NAME : String = 'BasicMaterial'; public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader(); public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER); public function get blending() : uint { return getProperty(BasicProperties.BLENDING); } public function set blending(value : uint) : void { setProperty(BasicProperties.BLENDING, value); } public function get triangleCulling() : uint { return getProperty(BasicProperties.TRIANGLE_CULLING); } public function set triangleCulling(value : uint) : void { setProperty(BasicProperties.TRIANGLE_CULLING, value); } public function get diffuseColor() : Object { return getProperty(BasicProperties.DIFFUSE_COLOR); } public function set diffuseColor(value : Object) : void { setProperty(BasicProperties.DIFFUSE_COLOR, value); } public function get diffuseMap() : TextureResource { return getProperty(BasicProperties.DIFFUSE_MAP); } public function set diffuseMap(value : TextureResource) : void { setProperty(BasicProperties.DIFFUSE_MAP, value); } public function get diffuseMapFiltering() : uint { return getProperty(BasicProperties.DIFFUSE_MAP_FILTERING); } public function set diffuseMapFiltering(value : uint) : void { setProperty(BasicProperties.DIFFUSE_MAP_FILTERING, value); } public function get diffuseMapMipMapping() : uint { return getProperty(BasicProperties.DIFFUSE_MAP_MIPMAPPING); } public function set diffuseMapMipMapping(value : uint) : void { setProperty(BasicProperties.DIFFUSE_MAP_MIPMAPPING, value); } public function get diffuseMapFormat() : uint { return getProperty(BasicProperties.DIFFUSE_MAP_FORMAT); } public function set diffuseMapFormat(value : uint) : void { setProperty(BasicProperties.DIFFUSE_MAP_FORMAT, value); } public function get alphaMap() : TextureResource { return getProperty(BasicProperties.ALPHA_MAP) as TextureResource; } public function set alphaMap(value : TextureResource) : void { setProperty(BasicProperties.ALPHA_MAP, value); } public function get alphaThreshold() : Number { return getProperty(BasicProperties.ALPHA_THRESHOLD); } public function set alphaThreshold(value : Number) : void { setProperty(BasicProperties.ALPHA_THRESHOLD, value); } public function get depthTest() : uint { return getProperty(BasicProperties.DEPTH_TEST); } public function set depthTest(value : uint) : void { setProperty(BasicProperties.DEPTH_TEST, value); } public function get depthWriteEnabled() : Boolean { return getProperty(BasicProperties.DEPTH_WRITE_ENABLED); } public function set depthWriteEnabled(value : Boolean) : void { setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value); } public function get stencilTriangleFace() : uint { return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE); } public function set stencilTriangleFace(value : uint) : void { setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value); } public function get stencilCompareMode() : uint { return getProperty(BasicProperties.STENCIL_COMPARE_MODE); } public function set stencilCompareMode(value : uint) : void { setProperty(BasicProperties.STENCIL_COMPARE_MODE, value); } public function get stencilActionBothPass() : uint { return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS); } public function set stencilActionBothPass(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value); } public function get stencilActionDepthFail() : uint { return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL); } public function set stencilActionDepthFail(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value); } public function get stencilActionDepthPassStencilFail() : uint { return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL); } public function set stencilActionDepthPassStencilFail(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value); } public function get stencilReferenceValue() : Number { return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE); } public function set stencilReferenceValue(value : Number) : void { setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value); } public function get stencilReadMask() : uint { return getProperty(BasicProperties.STENCIL_READ_MASK); } public function set stencilReadMask(value : uint) : void { setProperty(BasicProperties.STENCIL_READ_MASK, value); } public function get stencilWriteMask() : uint { return getProperty(BasicProperties.STENCIL_WRITE_MASK); } public function set stencilWriteMask(value : uint) : void { setProperty(BasicProperties.STENCIL_WRITE_MASK, value); } public function get diffuseTransform() : Matrix4x4 { return getProperty(BasicProperties.DIFFUSE_TRANSFORM); } public function set diffuseTransform(value : Matrix4x4) : void { setProperty(BasicProperties.DIFFUSE_TRANSFORM, value); } public function get uvOffset() : Vector4 { return getProperty(BasicProperties.UV_OFFSET); } public function set uvOffset(value : Vector4) : void { setProperty(BasicProperties.UV_OFFSET, value); } public function get uvScale() : Vector4 { return getProperty(BasicProperties.UV_SCALE); } public function set uvScale(value : Vector4) : void { setProperty(BasicProperties.UV_SCALE, value); } public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME) { super(effect || DEFAULT_EFFECT, properties, name); } override public function clone() : IDataProvider { var mat : BasicMaterial = new BasicMaterial(this, effect, name); return mat; } } }
package aerys.minko.render.material.basic { import aerys.minko.render.Effect; import aerys.minko.render.material.Material; import aerys.minko.render.resource.texture.TextureResource; import aerys.minko.type.binding.IDataProvider; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; public class BasicMaterial extends Material { public static const DEFAULT_NAME : String = 'BasicMaterial'; public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader(); public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER); public function get blending() : uint { return getProperty(BasicProperties.BLENDING); } public function set blending(value : uint) : void { setProperty(BasicProperties.BLENDING, value); } public function get triangleCulling() : uint { return getProperty(BasicProperties.TRIANGLE_CULLING); } public function set triangleCulling(value : uint) : void { setProperty(BasicProperties.TRIANGLE_CULLING, value); } public function get diffuseColor() : Object { return getProperty(BasicProperties.DIFFUSE_COLOR); } public function set diffuseColor(value : Object) : void { setProperty(BasicProperties.DIFFUSE_COLOR, value); } public function get diffuseMap() : TextureResource { return getProperty(BasicProperties.DIFFUSE_MAP); } public function set diffuseMap(value : TextureResource) : void { setProperty(BasicProperties.DIFFUSE_MAP, value); } public function get diffuseMapFiltering() : uint { return getProperty(BasicProperties.DIFFUSE_MAP_FILTERING); } public function set diffuseMapFiltering(value : uint) : void { setProperty(BasicProperties.DIFFUSE_MAP_FILTERING, value); } public function get diffuseMapMipMapping() : uint { return getProperty(BasicProperties.DIFFUSE_MAP_MIPMAPPING); } public function set diffuseMapMipMapping(value : uint) : void { setProperty(BasicProperties.DIFFUSE_MAP_MIPMAPPING, value); } public function get diffuseMapWrapping() : uint { return getProperty(BasicProperties.DIFFUSE_MAP_WRAPPING); } public function set diffuseMapWrapping(value : uint) : void { setProperty(BasicProperties.DIFFUSE_MAP_WRAPPING, value); } public function get diffuseMapFormat() : uint { return getProperty(BasicProperties.DIFFUSE_MAP_FORMAT); } public function set diffuseMapFormat(value : uint) : void { setProperty(BasicProperties.DIFFUSE_MAP_FORMAT, value); } public function get alphaMap() : TextureResource { return getProperty(BasicProperties.ALPHA_MAP) as TextureResource; } public function set alphaMap(value : TextureResource) : void { setProperty(BasicProperties.ALPHA_MAP, value); } public function get alphaThreshold() : Number { return getProperty(BasicProperties.ALPHA_THRESHOLD); } public function set alphaThreshold(value : Number) : void { setProperty(BasicProperties.ALPHA_THRESHOLD, value); } public function get depthTest() : uint { return getProperty(BasicProperties.DEPTH_TEST); } public function set depthTest(value : uint) : void { setProperty(BasicProperties.DEPTH_TEST, value); } public function get depthWriteEnabled() : Boolean { return getProperty(BasicProperties.DEPTH_WRITE_ENABLED); } public function set depthWriteEnabled(value : Boolean) : void { setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value); } public function get stencilTriangleFace() : uint { return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE); } public function set stencilTriangleFace(value : uint) : void { setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value); } public function get stencilCompareMode() : uint { return getProperty(BasicProperties.STENCIL_COMPARE_MODE); } public function set stencilCompareMode(value : uint) : void { setProperty(BasicProperties.STENCIL_COMPARE_MODE, value); } public function get stencilActionBothPass() : uint { return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS); } public function set stencilActionBothPass(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value); } public function get stencilActionDepthFail() : uint { return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL); } public function set stencilActionDepthFail(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value); } public function get stencilActionDepthPassStencilFail() : uint { return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL); } public function set stencilActionDepthPassStencilFail(value : uint) : void { setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value); } public function get stencilReferenceValue() : Number { return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE); } public function set stencilReferenceValue(value : Number) : void { setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value); } public function get stencilReadMask() : uint { return getProperty(BasicProperties.STENCIL_READ_MASK); } public function set stencilReadMask(value : uint) : void { setProperty(BasicProperties.STENCIL_READ_MASK, value); } public function get stencilWriteMask() : uint { return getProperty(BasicProperties.STENCIL_WRITE_MASK); } public function set stencilWriteMask(value : uint) : void { setProperty(BasicProperties.STENCIL_WRITE_MASK, value); } public function get diffuseTransform() : Matrix4x4 { return getProperty(BasicProperties.DIFFUSE_TRANSFORM); } public function set diffuseTransform(value : Matrix4x4) : void { setProperty(BasicProperties.DIFFUSE_TRANSFORM, value); } public function get uvOffset() : Vector4 { return getProperty(BasicProperties.UV_OFFSET); } public function set uvOffset(value : Vector4) : void { setProperty(BasicProperties.UV_OFFSET, value); } public function get uvScale() : Vector4 { return getProperty(BasicProperties.UV_SCALE); } public function set uvScale(value : Vector4) : void { setProperty(BasicProperties.UV_SCALE, value); } public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME) { super(effect || DEFAULT_EFFECT, properties, name); } override public function clone() : IDataProvider { var mat : BasicMaterial = new BasicMaterial(this, effect, name); return mat; } } }
add property BasicMaterial.diffuseMapWrapping
add property BasicMaterial.diffuseMapWrapping
ActionScript
mit
aerys/minko-as3