code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package org.flixel.plugin { import org.flixel.*; /** * A simple manager for tracking and updating game timer objects. * * @author Adam Atomic */ public class TimerManager extends FlxBasic { protected var _timers:Array; /** * Instantiates a new timer manager. */ public function TimerManager() { _timers = new Array(); visible = false; //don't call draw on this plugin } /** * Clean up memory. */ override public function destroy():void { clear(); _timers = null; } /** * Called by <code>FlxG.updatePlugins()</code> before the game state has been updated. * Cycles through timers and calls <code>update()</code> on each one. */ override public function update():void { var i:int = _timers.length-1; var timer:FlxTimer; while(i >= 0) { timer = _timers[i--] as FlxTimer; if((timer != null) && !timer.paused && !timer.finished && (timer.time > 0)) timer.update(); } } /** * Add a new timer to the timer manager. * Usually called automatically by <code>FlxTimer</code>'s constructor. * * @param Timer The <code>FlxTimer</code> you want to add to the manager. */ public function add(Timer:FlxTimer):void { _timers.push(Timer); } /** * Remove a timer from the timer manager. * Usually called automatically by <code>FlxTimer</code>'s <code>stop()</code> function. * * @param Timer The <code>FlxTimer</code> you want to remove from the manager. */ public function remove(Timer:FlxTimer):void { var index:int = _timers.indexOf(Timer); if(index >= 0) _timers.splice(index,1); } /** * Removes all the timers from the timer manager. */ public function clear():void { var i:int = _timers.length-1; var timer:FlxTimer; while(i >= 0) { timer = _timers[i--] as FlxTimer; if(timer != null) timer.destroy(); } _timers.length = 0; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/plugin/TimerManager.as
ActionScript
gpl3
1,943
package org.flixel.plugin { import org.flixel.*; /** * A simple manager for tracking and drawing FlxPath debug data to the screen. * * @author Adam Atomic */ public class DebugPathDisplay extends FlxBasic { protected var _paths:Array; /** * Instantiates a new debug path display manager. */ public function DebugPathDisplay() { _paths = new Array(); active = false; //don't call update on this plugin } /** * Clean up memory. */ override public function destroy():void { super.destroy(); clear(); _paths = null; } /** * Called by <code>FlxG.drawPlugins()</code> after the game state has been drawn. * Cycles through cameras and calls <code>drawDebug()</code> on each one. */ override public function draw():void { if(!FlxG.visualDebug || ignoreDrawDebug) return; if(cameras == null) cameras = FlxG.cameras; var i:uint = 0; var l:uint = cameras.length; while(i < l) drawDebug(cameras[i++]); } /** * Similar to <code>FlxObject</code>'s <code>drawDebug()</code> functionality, * this function calls <code>drawDebug()</code> on each <code>FlxPath</code> for the specified camera. * Very helpful for debugging! * * @param Camera Which <code>FlxCamera</code> object to draw the debug data to. */ override public function drawDebug(Camera:FlxCamera=null):void { if(Camera == null) Camera = FlxG.camera; var i:int = _paths.length-1; var path:FlxPath; while(i >= 0) { path = _paths[i--] as FlxPath; if((path != null) && !path.ignoreDrawDebug) path.drawDebug(Camera); } } /** * Add a path to the path debug display manager. * Usually called automatically by <code>FlxPath</code>'s constructor. * * @param Path The <code>FlxPath</code> you want to add to the manager. */ public function add(Path:FlxPath):void { _paths.push(Path); } /** * Remove a path from the path debug display manager. * Usually called automatically by <code>FlxPath</code>'s <code>destroy()</code> function. * * @param Path The <code>FlxPath</code> you want to remove from the manager. */ public function remove(Path:FlxPath):void { var index:int = _paths.indexOf(Path); if(index >= 0) _paths.splice(index,1); } /** * Removes all the paths from the path debug display manager. */ public function clear():void { var i:int = _paths.length-1; var path:FlxPath; while(i >= 0) { path = _paths[i--] as FlxPath; if(path != null) path.destroy(); } _paths.length = 0; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/plugin/DebugPathDisplay.as
ActionScript
gpl3
2,628
package org.flixel { import flash.net.URLRequest; import flash.net.navigateToURL; import flash.utils.getDefinitionByName; import flash.utils.getQualifiedClassName; import flash.utils.getTimer; public class FlxU { /** * Opens a web page in a new tab or window. * MUST be called from the UI thread or else badness. * * @param URL The address of the web page. */ static public function openURL(URL:String):void { navigateToURL(new URLRequest(URL), "_blank"); } /** * Calculate the absolute value of a number. * * @param Value Any number. * * @return The absolute value of that number. */ static public function abs(Value:Number):Number { return (Value>0)?Value:-Value; } /** * Round down to the next whole number. E.g. floor(1.7) == 1, and floor(-2.7) == -2. * * @param Value Any number. * * @return The rounded value of that number. */ static public function floor(Value:Number):Number { var number:Number = int(Value); return (Value>0)?(number):((number!=Value)?(number-1):(number)); } /** * Round up to the next whole number. E.g. ceil(1.3) == 2, and ceil(-2.3) == -3. * * @param Value Any number. * * @return The rounded value of that number. */ static public function ceil(Value:Number):Number { var number:Number = int(Value); return (Value>0)?((number!=Value)?(number+1):(number)):(number); } /** * Round to the closest whole number. E.g. round(1.7) == 2, and round(-2.3) == -2. * * @param Value Any number. * * @return The rounded value of that number. */ static public function round(Value:Number):Number { var number:Number = int(Value+((Value>0)?0.5:-0.5)); return (Value>0)?(number):((number!=Value)?(number-1):(number)); } /** * Figure out which number is smaller. * * @param Number1 Any number. * @param Number2 Any number. * * @return The smaller of the two numbers. */ static public function min(Number1:Number,Number2:Number):Number { return (Number1 <= Number2)?Number1:Number2; } /** * Figure out which number is larger. * * @param Number1 Any number. * @param Number2 Any number. * * @return The larger of the two numbers. */ static public function max(Number1:Number,Number2:Number):Number { return (Number1 >= Number2)?Number1:Number2; } /** * Bound a number by a minimum and maximum. * Ensures that this number is no smaller than the minimum, * and no larger than the maximum. * * @param Value Any number. * @param Min Any number. * @param Max Any number. * * @return The bounded value of the number. */ static public function bound(Value:Number,Min:Number,Max:Number):Number { var lowerBound:Number = (Value<Min)?Min:Value; return (lowerBound>Max)?Max:lowerBound; } /** * Generates a random number based on the seed provided. * * @param Seed A number between 0 and 1, used to generate a predictable random number (very optional). * * @return A <code>Number</code> between 0 and 1. */ static public function srand(Seed:Number):Number { return ((69621 * int(Seed * 0x7FFFFFFF)) % 0x7FFFFFFF) / 0x7FFFFFFF; } /** * Shuffles the entries in an array into a new random order. * <code>FlxG.shuffle()</code> is deterministic and safe for use with replays/recordings. * HOWEVER, <code>FlxU.shuffle()</code> is NOT deterministic and unsafe for use with replays/recordings. * * @param A A Flash <code>Array</code> object containing...stuff. * @param HowManyTimes How many swaps to perform during the shuffle operation. Good rule of thumb is 2-4 times as many objects are in the list. * * @return The same Flash <code>Array</code> object that you passed in in the first place. */ static public function shuffle(Objects:Array,HowManyTimes:uint):Array { var i:uint = 0; var index1:uint; var index2:uint; var object:Object; while(i < HowManyTimes) { index1 = Math.random()*Objects.length; index2 = Math.random()*Objects.length; object = Objects[index2]; Objects[index2] = Objects[index1]; Objects[index1] = object; i++; } return Objects; } /** * Fetch a random entry from the given array. * Will return null if random selection is missing, or array has no entries. * <code>FlxG.getRandom()</code> is deterministic and safe for use with replays/recordings. * HOWEVER, <code>FlxU.getRandom()</code> is NOT deterministic and unsafe for use with replays/recordings. * * @param Objects A Flash array of objects. * @param StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. * @param Length Optional restriction on the number of values you want to randomly select from. * * @return The random object that was selected. */ static public function getRandom(Objects:Array,StartIndex:uint=0,Length:uint=0):Object { if(Objects != null) { var l:uint = Length; if((l == 0) || (l > Objects.length - StartIndex)) l = Objects.length - StartIndex; if(l > 0) return Objects[StartIndex + uint(Math.random()*l)]; } return null; } /** * Just grabs the current "ticks" or time in milliseconds that has passed since Flash Player started up. * Useful for finding out how long it takes to execute specific blocks of code. * * @return A <code>uint</code> to be passed to <code>FlxU.endProfile()</code>. */ static public function getTicks():uint { return getTimer(); } /** * Takes two "ticks" timestamps and formats them into the number of seconds that passed as a String. * Useful for logging, debugging, the watch window, or whatever else. * * @param StartTicks The first timestamp from the system. * @param EndTicks The second timestamp from the system. * * @return A <code>String</code> containing the formatted time elapsed information. */ static public function formatTicks(StartTicks:uint,EndTicks:uint):String { return ((EndTicks-StartTicks)/1000)+"s" } /** * Generate a Flash <code>uint</code> color from RGBA components. * * @param Red The red component, between 0 and 255. * @param Green The green component, between 0 and 255. * @param Blue The blue component, between 0 and 255. * @param Alpha How opaque the color should be, either between 0 and 1 or 0 and 255. * * @return The color as a <code>uint</code>. */ static public function makeColor(Red:uint, Green:uint, Blue:uint, Alpha:Number=1.0):uint { return (((Alpha>1)?Alpha:(Alpha * 255)) & 0xFF) << 24 | (Red & 0xFF) << 16 | (Green & 0xFF) << 8 | (Blue & 0xFF); } /** * Generate a Flash <code>uint</code> color from HSB components. * * @param Hue A number between 0 and 360, indicating position on a color strip or wheel. * @param Saturation A number between 0 and 1, indicating how colorful or gray the color should be. 0 is gray, 1 is vibrant. * @param Brightness A number between 0 and 1, indicating how bright the color should be. 0 is black, 1 is full bright. * @param Alpha How opaque the color should be, either between 0 and 1 or 0 and 255. * * @return The color as a <code>uint</code>. */ static public function makeColorFromHSB(Hue:Number,Saturation:Number,Brightness:Number,Alpha:Number=1.0):uint { var red:Number; var green:Number; var blue:Number; if(Saturation == 0.0) { red = Brightness; green = Brightness; blue = Brightness; } else { if(Hue == 360) Hue = 0; var slice:int = Hue/60; var hf:Number = Hue/60 - slice; var aa:Number = Brightness*(1 - Saturation); var bb:Number = Brightness*(1 - Saturation*hf); var cc:Number = Brightness*(1 - Saturation*(1.0 - hf)); switch (slice) { case 0: red = Brightness; green = cc; blue = aa; break; case 1: red = bb; green = Brightness; blue = aa; break; case 2: red = aa; green = Brightness; blue = cc; break; case 3: red = aa; green = bb; blue = Brightness; break; case 4: red = cc; green = aa; blue = Brightness; break; case 5: red = Brightness; green = aa; blue = bb; break; default: red = 0; green = 0; blue = 0; break; } } return (((Alpha>1)?Alpha:(Alpha * 255)) & 0xFF) << 24 | uint(red*255) << 16 | uint(green*255) << 8 | uint(blue*255); } /** * Loads an array with the RGBA values of a Flash <code>uint</code> color. * RGB values are stored 0-255. Alpha is stored as a floating point number between 0 and 1. * * @param Color The color you want to break into components. * @param Results An optional parameter, allows you to use an array that already exists in memory to store the result. * * @return An <code>Array</code> object containing the Red, Green, Blue and Alpha values of the given color. */ static public function getRGBA(Color:uint,Results:Array=null):Array { if(Results == null) Results = new Array(); Results[0] = (Color >> 16) & 0xFF; Results[1] = (Color >> 8) & 0xFF; Results[2] = Color & 0xFF; Results[3] = Number((Color >> 24) & 0xFF) / 255; return Results; } /** * Loads an array with the HSB values of a Flash <code>uint</code> color. * Hue is a value between 0 and 360. Saturation, Brightness and Alpha * are as floating point numbers between 0 and 1. * * @param Color The color you want to break into components. * @param Results An optional parameter, allows you to use an array that already exists in memory to store the result. * * @return An <code>Array</code> object containing the Red, Green, Blue and Alpha values of the given color. */ static public function getHSB(Color:uint,Results:Array=null):Array { if(Results == null) Results = new Array(); var red:Number = Number((Color >> 16) & 0xFF) / 255; var green:Number = Number((Color >> 8) & 0xFF) / 255; var blue:Number = Number((Color) & 0xFF) / 255; var m:Number = (red>green)?red:green; var dmax:Number = (m>blue)?m:blue; m = (red>green)?green:red; var dmin:Number = (m>blue)?blue:m; var range:Number = dmax - dmin; Results[2] = dmax; Results[1] = 0; Results[0] = 0; if(dmax != 0) Results[1] = range / dmax; if(Results[1] != 0) { if (red == dmax) Results[0] = (green - blue) / range; else if (green == dmax) Results[0] = 2 + (blue - red) / range; else if (blue == dmax) Results[0] = 4 + (red - green) / range; Results[0] *= 60; if(Results[0] < 0) Results[0] += 360; } Results[3] = Number((Color >> 24) & 0xFF) / 255; return Results; } /** * Format seconds as minutes with a colon, an optionally with milliseconds too. * * @param Seconds The number of seconds (for example, time remaining, time spent, etc). * @param ShowMS Whether to show milliseconds after a "." as well. Default value is false. * * @return A nicely formatted <code>String</code>, like "1:03". */ static public function formatTime(Seconds:Number,ShowMS:Boolean=false):String { var timeString:String = int(Seconds/60) + ":"; var timeStringHelper:int = int(Seconds)%60; if(timeStringHelper < 10) timeString += "0"; timeString += timeStringHelper; if(ShowMS) { timeString += "."; timeStringHelper = (Seconds-int(Seconds))*100; if(timeStringHelper < 10) timeString += "0"; timeString += timeStringHelper; } return timeString; } /** * Generate a comma-separated string from an array. * Especially useful for tracing or other debug output. * * @param AnyArray Any <code>Array</code> object. * * @return A comma-separated <code>String</code> containing the <code>.toString()</code> output of each element in the array. */ static public function formatArray(AnyArray:Array):String { if((AnyArray == null) || (AnyArray.length <= 0)) return ""; var string:String = AnyArray[0].toString(); var i:uint = 0; var l:uint = AnyArray.length; while(i < l) string += ", " + AnyArray[i++].toString(); return string; } /** * Automatically commas and decimals in the right places for displaying money amounts. * Does not include a dollar sign or anything, so doesn't really do much * if you call say <code>var results:String = FlxU.formatMoney(10,false);</code> * However, very handy for displaying large sums or decimal money values. * * @param Amount How much moneys (in dollars, or the equivalent "main" currency - i.e. not cents). * @param ShowDecimal Whether to show the decimals/cents component. Default value is true. * @param EnglishStyle Major quantities (thousands, millions, etc) separated by commas, and decimal by a period. Default value is true. * * @return A nicely formatted <code>String</code>. Does not include a dollar sign or anything! */ static public function formatMoney(Amount:Number,ShowDecimal:Boolean=true,EnglishStyle:Boolean=true):String { var helper:int; var amount:int = Amount; var string:String = ""; var comma:String = ""; var zeroes:String = ""; while(amount > 0) { if((string.length > 0) && comma.length <= 0) { if(EnglishStyle) comma = ","; else comma = "."; } zeroes = ""; helper = amount - int(amount/1000)*1000; amount /= 1000; if(amount > 0) { if(helper < 100) zeroes += "0"; if(helper < 10) zeroes += "0"; } string = zeroes + helper + comma + string; } if(ShowDecimal) { amount = int(Amount*100)-(int(Amount)*100); string += (EnglishStyle?".":",") + amount; if(amount < 10) string += "0"; } return string; } /** * Get the <code>String</code> name of any <code>Object</code>. * * @param Obj The <code>Object</code> object in question. * @param Simple Returns only the class name, not the package or packages. * * @return The name of the <code>Class</code> as a <code>String</code> object. */ static public function getClassName(Obj:Object,Simple:Boolean=false):String { var string:String = getQualifiedClassName(Obj); string = string.replace("::","."); if(Simple) string = string.substr(string.lastIndexOf(".")+1); return string; } /** * Check to see if two objects have the same class name. * * @param Object1 The first object you want to check. * @param Object2 The second object you want to check. * * @return Whether they have the same class name or not. */ static public function compareClassNames(Object1:Object,Object2:Object):Boolean { return getQualifiedClassName(Object1) == getQualifiedClassName(Object2); } /** * Look up a <code>Class</code> object by its string name. * * @param Name The <code>String</code> name of the <code>Class</code> you are interested in. * * @return A <code>Class</code> object. */ static public function getClass(Name:String):Class { return getDefinitionByName(Name) as Class; } /** * A tween-like function that takes a starting velocity * and some other factors and returns an altered velocity. * * @param Velocity Any component of velocity (e.g. 20). * @param Acceleration Rate at which the velocity is changing. * @param Drag Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. * @param Max An absolute value cap for the velocity. * * @return The altered Velocity value. */ static public function computeVelocity(Velocity:Number, Acceleration:Number=0, Drag:Number=0, Max:Number=10000):Number { if(Acceleration != 0) Velocity += Acceleration*FlxG.elapsed; else if(Drag != 0) { var drag:Number = Drag*FlxG.elapsed; if(Velocity - drag > 0) Velocity = Velocity - drag; else if(Velocity + drag < 0) Velocity += drag; else Velocity = 0; } if((Velocity != 0) && (Max != 10000)) { if(Velocity > Max) Velocity = Max; else if(Velocity < -Max) Velocity = -Max; } return Velocity; } //*** NOTE: THESE LAST THREE FUNCTIONS REQUIRE FLXPOINT ***// /** * Rotates a point in 2D space around another point by the given angle. * * @param X The X coordinate of the point you want to rotate. * @param Y The Y coordinate of the point you want to rotate. * @param PivotX The X coordinate of the point you want to rotate around. * @param PivotY The Y coordinate of the point you want to rotate around. * @param Angle Rotate the point by this many degrees. * @param Point Optional <code>FlxPoint</code> to store the results in. * * @return A <code>FlxPoint</code> containing the coordinates of the rotated point. */ static public function rotatePoint(X:Number, Y:Number, PivotX:Number, PivotY:Number, Angle:Number,Point:FlxPoint=null):FlxPoint { var sin:Number = 0; var cos:Number = 0; var radians:Number = Angle * -0.017453293; while (radians < -3.14159265) radians += 6.28318531; while (radians > 3.14159265) radians = radians - 6.28318531; if (radians < 0) { sin = 1.27323954 * radians + .405284735 * radians * radians; if (sin < 0) sin = .225 * (sin *-sin - sin) + sin; else sin = .225 * (sin * sin - sin) + sin; } else { sin = 1.27323954 * radians - 0.405284735 * radians * radians; if (sin < 0) sin = .225 * (sin *-sin - sin) + sin; else sin = .225 * (sin * sin - sin) + sin; } radians += 1.57079632; if (radians > 3.14159265) radians = radians - 6.28318531; if (radians < 0) { cos = 1.27323954 * radians + 0.405284735 * radians * radians; if (cos < 0) cos = .225 * (cos *-cos - cos) + cos; else cos = .225 * (cos * cos - cos) + cos; } else { cos = 1.27323954 * radians - 0.405284735 * radians * radians; if (cos < 0) cos = .225 * (cos *-cos - cos) + cos; else cos = .225 * (cos * cos - cos) + cos; } var dx:Number = X-PivotX; var dy:Number = PivotY+Y; //Y axis is inverted in flash, normally this would be a subtract operation if(Point == null) Point = new FlxPoint(); Point.x = PivotX + cos*dx - sin*dy; Point.y = PivotY - sin*dx - cos*dy; return Point; }; /** * Calculates the angle between two points. 0 degrees points straight up. * * @param Point1 The X coordinate of the point. * @param Point2 The Y coordinate of the point. * * @return The angle in degrees, between -180 and 180. */ static public function getAngle(Point1:FlxPoint, Point2:FlxPoint):Number { var x:Number = Point2.x - Point1.x; var y:Number = Point2.y - Point1.y; if((x == 0) && (y == 0)) return 0; var c1:Number = 3.14159265 * 0.25; var c2:Number = 3 * c1; var ay:Number = (y < 0)?-y:y; var angle:Number = 0; if (x >= 0) angle = c1 - c1 * ((x - ay) / (x + ay)); else angle = c2 - c1 * ((x + ay) / (ay - x)); angle = ((y < 0)?-angle:angle)*57.2957796; if(angle > 90) angle = angle - 270; else angle += 90; return angle; }; /** * Calculate the distance between two points. * * @param Point1 A <code>FlxPoint</code> object referring to the first location. * @param Point2 A <code>FlxPoint</code> object referring to the second location. * * @return The distance between the two points as a floating point <code>Number</code> object. */ static public function getDistance(Point1:FlxPoint,Point2:FlxPoint):Number { var dx:Number = Point1.x - Point2.x; var dy:Number = Point1.y - Point2.y; return Math.sqrt(dx * dx + dy * dy); } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxU.as
ActionScript
gpl3
19,961
package org.flixel.system { import org.flixel.FlxObject; /** * A miniature linked list class. * Useful for optimizing time-critical or highly repetitive tasks! * See <code>FlxQuadTree</code> for how to use it, IF YOU DARE. */ public class FlxList { /** * Stores a reference to a <code>FlxObject</code>. */ public var object:FlxObject; /** * Stores a reference to the next link in the list. */ public var next:FlxList; /** * Creates a new link, and sets <code>object</code> and <code>next</code> to <code>null</code>. */ public function FlxList() { object = null; next = null; } /** * Clean up memory. */ public function destroy():void { object = null; if(next != null) next.destroy(); next = null; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/FlxList.as
ActionScript
gpl3
791
package org.flixel.system { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; import flash.events.MouseEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.TextField; import flash.text.TextFormat; import org.flixel.FlxG; import org.flixel.system.debug.Log; import org.flixel.system.debug.Perf; import org.flixel.system.debug.VCR; import org.flixel.system.debug.Vis; import org.flixel.system.debug.Watch; /** * Container for the new debugger overlay. * Most of the functionality is in the debug folder widgets, * but this class instantiates the widgets and handles their basic formatting and arrangement. */ public class FlxDebugger extends Sprite { /** * Container for the performance monitor widget. */ public var perf:Perf; /** * Container for the trace output widget. */ public var log:Log; /** * Container for the watch window widget. */ public var watch:Watch; /** * Container for the record, stop and play buttons. */ public var vcr:VCR; /** * Container for the visual debug mode toggle. */ public var vis:Vis; /** * Whether the mouse is currently over one of the debugger windows or not. */ public var hasMouse:Boolean; /** * Internal, tracks what debugger window layout user has currently selected. */ protected var _layout:uint; /** * Internal, stores width and height of the Flash Player window. */ protected var _screen:Point; /** * Internal, used to space out windows from the edges. */ protected var _gutter:uint; /** * Instantiates the debugger overlay. * * @param Width The width of the screen. * @param Height The height of the screen. */ public function FlxDebugger(Width:Number,Height:Number) { super(); visible = false; hasMouse = false; _screen = new Point(Width,Height); addChild(new Bitmap(new BitmapData(Width,15,true,0x7f000000))); var txt:TextField = new TextField(); txt.x = 2; txt.width = 160; txt.height = 16; txt.selectable = false; txt.multiline = false; txt.defaultTextFormat = new TextFormat("Courier",12,0xffffff); var str:String = FlxG.getLibraryName(); if(FlxG.debug) str += " [debug]"; else str += " [release]"; txt.text = str; addChild(txt); _gutter = 8; var screenBounds:Rectangle = new Rectangle(_gutter,15+_gutter/2,_screen.x-_gutter*2,_screen.y-_gutter*1.5-15); log = new Log("log",0,0,true,screenBounds); addChild(log); watch = new Watch("watch",0,0,true,screenBounds); addChild(watch); perf = new Perf("stats",0,0,false,screenBounds); addChild(perf); vcr = new VCR(); vcr.x = (Width - vcr.width/2)/2; vcr.y = 2; addChild(vcr); vis = new Vis(); vis.x = Width-vis.width - 4; vis.y = 2; addChild(vis); setLayout(FlxG.DEBUGGER_STANDARD); //Should help with fake mouse focus type behavior addEventListener(MouseEvent.MOUSE_OVER,onMouseOver); addEventListener(MouseEvent.MOUSE_OUT,onMouseOut); } /** * Clean up memory. */ public function destroy():void { _screen = null; removeChild(log); log.destroy(); log = null; removeChild(watch); watch.destroy(); watch = null; removeChild(perf); perf.destroy(); perf = null; removeChild(vcr); vcr.destroy(); vcr = null; removeChild(vis); vis.destroy(); vis = null; removeEventListener(MouseEvent.MOUSE_OVER,onMouseOver); removeEventListener(MouseEvent.MOUSE_OUT,onMouseOut); } /** * Mouse handler that helps with fake "mouse focus" type behavior. * * @param E Flash mouse event. */ protected function onMouseOver(E:MouseEvent=null):void { hasMouse = true; } /** * Mouse handler that helps with fake "mouse focus" type behavior. * * @param E Flash mouse event. */ protected function onMouseOut(E:MouseEvent=null):void { hasMouse = false; } /** * Rearrange the debugger windows using one of the constants specified in FlxG. * * @param Layout The layout style for the debugger windows, e.g. <code>FlxG.DEBUGGER_MICRO</code>. */ public function setLayout(Layout:uint):void { _layout = Layout; resetLayout(); } /** * Forces the debugger windows to reset to the last specified layout. * The default layout is <code>FlxG.DEBUGGER_STANDARD</code>. */ public function resetLayout():void { switch(_layout) { case FlxG.DEBUGGER_MICRO: log.resize(_screen.x/4,68); log.reposition(0,_screen.y); watch.resize(_screen.x/4,68); watch.reposition(_screen.x,_screen.y); perf.reposition(_screen.x,0); break; case FlxG.DEBUGGER_BIG: log.resize((_screen.x-_gutter*3)/2,_screen.y/2); log.reposition(0,_screen.y); watch.resize((_screen.x-_gutter*3)/2,_screen.y/2); watch.reposition(_screen.x,_screen.y); perf.reposition(_screen.x,0); break; case FlxG.DEBUGGER_TOP: log.resize((_screen.x-_gutter*3)/2,_screen.y/4); log.reposition(0,0); watch.resize((_screen.x-_gutter*3)/2,_screen.y/4); watch.reposition(_screen.x,0); perf.reposition(_screen.x,_screen.y); break; case FlxG.DEBUGGER_LEFT: log.resize(_screen.x/3,(_screen.y-15-_gutter*2.5)/2); log.reposition(0,0); watch.resize(_screen.x/3,(_screen.y-15-_gutter*2.5)/2); watch.reposition(0,_screen.y); perf.reposition(_screen.x,0); break; case FlxG.DEBUGGER_RIGHT: log.resize(_screen.x/3,(_screen.y-15-_gutter*2.5)/2); log.reposition(_screen.x,0); watch.resize(_screen.x/3,(_screen.y-15-_gutter*2.5)/2); watch.reposition(_screen.x,_screen.y); perf.reposition(0,0); break; case FlxG.DEBUGGER_STANDARD: default: log.resize((_screen.x-_gutter*3)/2,_screen.y/4); log.reposition(0,_screen.y); watch.resize((_screen.x-_gutter*3)/2,_screen.y/4); watch.reposition(_screen.x,_screen.y); perf.reposition(_screen.x,0); break; } } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/FlxDebugger.as
ActionScript
gpl3
6,092
package org.flixel.system.input { import flash.events.KeyboardEvent; /** * Keeps track of what keys are pressed and how with handy booleans or strings. * * @author Adam Atomic */ public class Keyboard extends Input { public var ESCAPE:Boolean; public var F1:Boolean; public var F2:Boolean; public var F3:Boolean; public var F4:Boolean; public var F5:Boolean; public var F6:Boolean; public var F7:Boolean; public var F8:Boolean; public var F9:Boolean; public var F10:Boolean; public var F11:Boolean; public var F12:Boolean; public var ONE:Boolean; public var TWO:Boolean; public var THREE:Boolean; public var FOUR:Boolean; public var FIVE:Boolean; public var SIX:Boolean; public var SEVEN:Boolean; public var EIGHT:Boolean; public var NINE:Boolean; public var ZERO:Boolean; public var NUMPADONE:Boolean; public var NUMPADTWO:Boolean; public var NUMPADTHREE:Boolean; public var NUMPADFOUR:Boolean; public var NUMPADFIVE:Boolean; public var NUMPADSIX:Boolean; public var NUMPADSEVEN:Boolean; public var NUMPADEIGHT:Boolean; public var NUMPADNINE:Boolean; public var NUMPADZERO:Boolean; public var PAGEUP:Boolean; public var PAGEDOWN:Boolean; public var HOME:Boolean; public var END:Boolean; public var INSERT:Boolean; public var MINUS:Boolean; public var NUMPADMINUS:Boolean; public var PLUS:Boolean; public var NUMPADPLUS:Boolean; public var DELETE:Boolean; public var BACKSPACE:Boolean; public var TAB:Boolean; public var Q:Boolean; public var W:Boolean; public var E:Boolean; public var R:Boolean; public var T:Boolean; public var Y:Boolean; public var U:Boolean; public var I:Boolean; public var O:Boolean; public var P:Boolean; public var LBRACKET:Boolean; public var RBRACKET:Boolean; public var BACKSLASH:Boolean; public var CAPSLOCK:Boolean; public var A:Boolean; public var S:Boolean; public var D:Boolean; public var F:Boolean; public var G:Boolean; public var H:Boolean; public var J:Boolean; public var K:Boolean; public var L:Boolean; public var SEMICOLON:Boolean; public var QUOTE:Boolean; public var ENTER:Boolean; public var SHIFT:Boolean; public var Z:Boolean; public var X:Boolean; public var C:Boolean; public var V:Boolean; public var B:Boolean; public var N:Boolean; public var M:Boolean; public var COMMA:Boolean; public var PERIOD:Boolean; public var NUMPADPERIOD:Boolean; public var SLASH:Boolean; public var NUMPADSLASH:Boolean; public var CONTROL:Boolean; public var ALT:Boolean; public var SPACE:Boolean; public var UP:Boolean; public var DOWN:Boolean; public var LEFT:Boolean; public var RIGHT:Boolean; public function Keyboard() { var i:uint; //LETTERS i = 65; while(i <= 90) addKey(String.fromCharCode(i),i++); //NUMBERS i = 48; addKey("ZERO",i++); addKey("ONE",i++); addKey("TWO",i++); addKey("THREE",i++); addKey("FOUR",i++); addKey("FIVE",i++); addKey("SIX",i++); addKey("SEVEN",i++); addKey("EIGHT",i++); addKey("NINE",i++); i = 96; addKey("NUMPADZERO",i++); addKey("NUMPADONE",i++); addKey("NUMPADTWO",i++); addKey("NUMPADTHREE",i++); addKey("NUMPADFOUR",i++); addKey("NUMPADFIVE",i++); addKey("NUMPADSIX",i++); addKey("NUMPADSEVEN",i++); addKey("NUMPADEIGHT",i++); addKey("NUMPADNINE",i++); addKey("PAGEUP", 33); addKey("PAGEDOWN", 34); addKey("HOME", 36); addKey("END", 35); addKey("INSERT", 45); //FUNCTION KEYS i = 1; while(i <= 12) addKey("F"+i,111+(i++)); //SPECIAL KEYS + PUNCTUATION addKey("ESCAPE",27); addKey("MINUS",189); addKey("NUMPADMINUS",109); addKey("PLUS",187); addKey("NUMPADPLUS",107); addKey("DELETE",46); addKey("BACKSPACE",8); addKey("LBRACKET",219); addKey("RBRACKET",221); addKey("BACKSLASH",220); addKey("CAPSLOCK",20); addKey("SEMICOLON",186); addKey("QUOTE",222); addKey("ENTER",13); addKey("SHIFT",16); addKey("COMMA",188); addKey("PERIOD",190); addKey("NUMPADPERIOD",110); addKey("SLASH",191); addKey("NUMPADSLASH",191); addKey("CONTROL",17); addKey("ALT",18); addKey("SPACE",32); addKey("UP",38); addKey("DOWN",40); addKey("LEFT",37); addKey("RIGHT",39); addKey("TAB",9); } /** * Event handler so FlxGame can toggle keys. * * @param FlashEvent A <code>KeyboardEvent</code> object. */ public function handleKeyDown(FlashEvent:KeyboardEvent):void { var object:Object = _map[FlashEvent.keyCode]; if(object == null) return; if(object.current > 0) object.current = 1; else object.current = 2; this[object.name] = true; } /** * Event handler so FlxGame can toggle keys. * * @param FlashEvent A <code>KeyboardEvent</code> object. */ public function handleKeyUp(FlashEvent:KeyboardEvent):void { var object:Object = _map[FlashEvent.keyCode]; if(object == null) return; if(object.current > 0) object.current = -1; else object.current = 0; this[object.name] = false; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/input/Keyboard.as
ActionScript
gpl3
5,124
package org.flixel.system.input { /** * Basic input class that manages the fast-access Booleans and detailed key-state tracking. * Keyboard extends this with actual specific key data. * * @author Adam Atomic */ public class Input { /** * @private */ internal var _lookup:Object; /** * @private */ internal var _map:Array; /** * @private */ internal const _total:uint = 256; /** * Constructor */ public function Input() { _lookup = new Object(); _map = new Array(_total); } /** * Updates the key states (for tracking just pressed, just released, etc). */ public function update():void { var i:uint = 0; while(i < _total) { var o:Object = _map[i++]; if(o == null) continue; if((o.last == -1) && (o.current == -1)) o.current = 0; else if((o.last == 2) && (o.current == 2)) o.current = 1; o.last = o.current; } } /** * Resets all the keys. */ public function reset():void { var i:uint = 0; while(i < _total) { var o:Object = _map[i++]; if(o == null) continue; this[o.name] = false; o.current = 0; o.last = 0; } } /** * Check to see if this key is pressed. * * @param Key One of the key constants listed above (e.g. "LEFT" or "A"). * * @return Whether the key is pressed */ public function pressed(Key:String):Boolean { return this[Key]; } /** * Check to see if this key was just pressed. * * @param Key One of the key constants listed above (e.g. "LEFT" or "A"). * * @return Whether the key was just pressed */ public function justPressed(Key:String):Boolean { return _map[_lookup[Key]].current == 2; } /** * Check to see if this key is just released. * * @param Key One of the key constants listed above (e.g. "LEFT" or "A"). * * @return Whether the key is just released. */ public function justReleased(Key:String):Boolean { return _map[_lookup[Key]].current == -1; } /** * If any keys are not "released" (0), * this function will return an array indicating * which keys are pressed and what state they are in. * * @return An array of key state data. Null if there is no data. */ public function record():Array { var data:Array = null; var i:uint = 0; while(i < _total) { var o:Object = _map[i++]; if((o == null) || (o.current == 0)) continue; if(data == null) data = new Array(); data.push({code:i-1,value:o.current}); } return data; } /** * Part of the keystroke recording system. * Takes data about key presses and sets it into array. * * @param Record Array of data about key states. */ public function playback(Record:Array):void { var i:uint = 0; var l:uint = Record.length; var o:Object; var o2:Object; while(i < l) { o = Record[i++]; o2 = _map[o.code]; o2.current = o.value; if(o.value > 0) this[o2.name] = true; } } /** * Look up the key code for any given string name of the key or button. * * @param KeyName The <code>String</code> name of the key. * * @return The key code for that key. */ public function getKeyCode(KeyName:String):int { return _lookup[KeyName]; } /** * Check to see if any keys are pressed right now. * * @return Whether any keys are currently pressed. */ public function any():Boolean { var i:uint = 0; while(i < _total) { var o:Object = _map[i++]; if((o != null) && (o.current > 0)) return true; } return false; } /** * An internal helper function used to build the key array. * * @param KeyName String name of the key (e.g. "LEFT" or "A") * @param KeyCode The numeric Flash code for this key. */ protected function addKey(KeyName:String,KeyCode:uint):void { _lookup[KeyName] = KeyCode; _map[KeyCode] = { name: KeyName, current: 0, last: 0 }; } /** * Clean up memory. */ public function destroy():void { _lookup = null; _map = null; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/input/Input.as
ActionScript
gpl3
4,109
package org.flixel.system.input { import flash.display.Bitmap; import flash.display.Sprite; import flash.events.MouseEvent; import org.flixel.FlxCamera; import org.flixel.FlxG; import org.flixel.FlxPoint; import org.flixel.FlxSprite; import org.flixel.FlxU; import org.flixel.system.replay.MouseRecord; /** * This class helps contain and track the mouse pointer in your game. * Automatically accounts for parallax scrolling, etc. * * @author Adam Atomic */ public class Mouse extends FlxPoint { [Embed(source="../../data/cursor.png")] protected var ImgDefaultCursor:Class; /** * Current "delta" value of mouse wheel. If the wheel was just scrolled up, it will have a positive value. If it was just scrolled down, it will have a negative value. If it wasn't just scroll this frame, it will be 0. */ public var wheel:int; /** * Current X position of the mouse pointer on the screen. */ public var screenX:int; /** * Current Y position of the mouse pointer on the screen. */ public var screenY:int; /** * Helper variable for tracking whether the mouse was just pressed or just released. */ protected var _current:int; /** * Helper variable for tracking whether the mouse was just pressed or just released. */ protected var _last:int; /** * A display container for the mouse cursor. * This container is a child of FlxGame and sits at the right "height". */ protected var _cursorContainer:Sprite; /** * This is just a reference to the current cursor image, if there is one. */ protected var _cursor:Bitmap; /** * Helper variables for recording purposes. */ protected var _lastX:int; protected var _lastY:int; protected var _lastWheel:int; protected var _point:FlxPoint; protected var _globalScreenPosition:FlxPoint; /** * Constructor. */ public function Mouse(CursorContainer:Sprite) { super(); _cursorContainer = CursorContainer; _lastX = screenX = 0; _lastY = screenY = 0; _lastWheel = wheel = 0; _current = 0; _last = 0; _cursor = null; _point = new FlxPoint(); _globalScreenPosition = new FlxPoint(); } /** * Clean up memory. */ public function destroy():void { _cursorContainer = null; _cursor = null; _point = null; _globalScreenPosition = null; } /** * Either show an existing cursor or load a new one. * * @param Graphic The image you want to use for the cursor. * @param Scale Change the size of the cursor. Default = 1, or native size. 2 = 2x as big, 0.5 = half size, etc. * @param XOffset The number of pixels between the mouse's screen position and the graphic's top left corner. * @param YOffset The number of pixels between the mouse's screen position and the graphic's top left corner. */ public function show(Graphic:Class=null,Scale:Number=1,XOffset:int=0,YOffset:int=0):void { _cursorContainer.visible = true; if(Graphic != null) load(Graphic,Scale,XOffset,YOffset); else if(_cursor == null) load(); } /** * Hides the mouse cursor */ public function hide():void { _cursorContainer.visible = false; } /** * Read only, check visibility of mouse cursor. */ public function get visible():Boolean { return _cursorContainer.visible; } /** * Load a new mouse cursor graphic * * @param Graphic The image you want to use for the cursor. * @param Scale Change the size of the cursor. * @param XOffset The number of pixels between the mouse's screen position and the graphic's top left corner. * @param YOffset The number of pixels between the mouse's screen position and the graphic's top left corner. */ public function load(Graphic:Class=null,Scale:Number=1,XOffset:int=0,YOffset:int=0):void { if(_cursor != null) _cursorContainer.removeChild(_cursor); if(Graphic == null) Graphic = ImgDefaultCursor; _cursor = new Graphic(); _cursor.x = XOffset; _cursor.y = YOffset; _cursor.scaleX = Scale; _cursor.scaleY = Scale; _cursorContainer.addChild(_cursor); } /** * Unload the current cursor graphic. If the current cursor is visible, * then the default system cursor is loaded up to replace the old one. */ public function unload():void { if(_cursor != null) { if(_cursorContainer.visible) load(); else { _cursorContainer.removeChild(_cursor) _cursor = null; } } } /** * Called by the internal game loop to update the mouse pointer's position in the game world. * Also updates the just pressed/just released flags. * * @param X The current X position of the mouse in the window. * @param Y The current Y position of the mouse in the window. * @param XScroll The amount the game world has scrolled horizontally. * @param YScroll The amount the game world has scrolled vertically. */ public function update(X:int,Y:int):void { _globalScreenPosition.x = X; _globalScreenPosition.y = Y; updateCursor(); if((_last == -1) && (_current == -1)) _current = 0; else if((_last == 2) && (_current == 2)) _current = 1; _last = _current; } /** * Internal function for helping to update the mouse cursor and world coordinates. */ protected function updateCursor():void { //actually position the flixel mouse cursor graphic _cursorContainer.x = _globalScreenPosition.x; _cursorContainer.y = _globalScreenPosition.y; //update the x, y, screenX, and screenY variables based on the default camera. //This is basically a combination of getWorldPosition() and getScreenPosition() var camera:FlxCamera = FlxG.camera; screenX = (_globalScreenPosition.x - camera.x)/camera.zoom; screenY = (_globalScreenPosition.y - camera.y)/camera.zoom; x = screenX + camera.scroll.x; y = screenY + camera.scroll.y; } /** * Fetch the world position of the mouse on any given camera. * NOTE: Mouse.x and Mouse.y also store the world position of the mouse cursor on the main camera. * * @param Camera If unspecified, first/main global camera is used instead. * @param Point An existing point object to store the results (if you don't want a new one created). * * @return The mouse's location in world space. */ public function getWorldPosition(Camera:FlxCamera=null,Point:FlxPoint=null):FlxPoint { if(Camera == null) Camera = FlxG.camera; if(Point == null) Point = new FlxPoint(); getScreenPosition(Camera,_point); Point.x = _point.x + Camera.scroll.x; Point.y = _point.y + Camera.scroll.y; return Point; } /** * Fetch the screen position of the mouse on any given camera. * NOTE: Mouse.screenX and Mouse.screenY also store the screen position of the mouse cursor on the main camera. * * @param Camera If unspecified, first/main global camera is used instead. * @param Point An existing point object to store the results (if you don't want a new one created). * * @return The mouse's location in screen space. */ public function getScreenPosition(Camera:FlxCamera=null,Point:FlxPoint=null):FlxPoint { if(Camera == null) Camera = FlxG.camera; if(Point == null) Point = new FlxPoint(); Point.x = (_globalScreenPosition.x - Camera.x)/Camera.zoom; Point.y = (_globalScreenPosition.y - Camera.y)/Camera.zoom; return Point; } /** * Resets the just pressed/just released flags and sets mouse to not pressed. */ public function reset():void { _current = 0; _last = 0; } /** * Check to see if the mouse is pressed. * * @return Whether the mouse is pressed. */ public function pressed():Boolean { return _current > 0; } /** * Check to see if the mouse was just pressed. * * @return Whether the mouse was just pressed. */ public function justPressed():Boolean { return _current == 2; } /** * Check to see if the mouse was just released. * * @return Whether the mouse was just released. */ public function justReleased():Boolean { return _current == -1; } /** * Event handler so FlxGame can update the mouse. * * @param FlashEvent A <code>MouseEvent</code> object. */ public function handleMouseDown(FlashEvent:MouseEvent):void { if(_current > 0) _current = 1; else _current = 2; } /** * Event handler so FlxGame can update the mouse. * * @param FlashEvent A <code>MouseEvent</code> object. */ public function handleMouseUp(FlashEvent:MouseEvent):void { if(_current > 0) _current = -1; else _current = 0; } /** * Event handler so FlxGame can update the mouse. * * @param FlashEvent A <code>MouseEvent</code> object. */ public function handleMouseWheel(FlashEvent:MouseEvent):void { wheel = FlashEvent.delta; } /** * If the mouse changed state or is pressed, return that info now * * @return An array of key state data. Null if there is no data. */ public function record():MouseRecord { if((_lastX == _globalScreenPosition.x) && (_lastY == _globalScreenPosition.y) && (_current == 0) && (_lastWheel == wheel)) return null; _lastX = _globalScreenPosition.x; _lastY = _globalScreenPosition.y; _lastWheel = wheel; return new MouseRecord(_lastX,_lastY,_current,_lastWheel); } /** * Part of the keystroke recording system. * Takes data about key presses and sets it into array. * * @param KeyStates Array of data about key states. */ public function playback(Record:MouseRecord):void { _current = Record.button; wheel = Record.wheel; _globalScreenPosition.x = Record.x; _globalScreenPosition.y = Record.y; updateCursor(); } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/input/Mouse.as
ActionScript
gpl3
9,806
package org.flixel.system { import flash.display.BitmapData; import flash.geom.Point; import flash.geom.Rectangle; import org.flixel.FlxCamera; import org.flixel.FlxG; import org.flixel.FlxU; /** * A helper object to keep tilemap drawing performance decent across the new multi-camera system. * Pretty much don't even have to think about this class unless you are doing some crazy hacking. * * @author Adam Atomic */ public class FlxTilemapBuffer { /** * The current X position of the buffer. */ public var x:Number; /** * The current Y position of the buffer. */ public var y:Number; /** * The width of the buffer (usually just a few tiles wider than the camera). */ public var width:Number; /** * The height of the buffer (usually just a few tiles taller than the camera). */ public var height:Number; /** * Whether the buffer needs to be redrawn. */ public var dirty:Boolean; /** * How many rows of tiles fit in this buffer. */ public var rows:uint; /** * How many columns of tiles fit in this buffer. */ public var columns:uint; protected var _pixels:BitmapData; protected var _flashRect:Rectangle; /** * Instantiates a new camera-specific buffer for storing the visual tilemap data. * * @param TileWidth The width of the tiles in this tilemap. * @param TileHeight The height of the tiles in this tilemap. * @param WidthInTiles How many tiles wide the tilemap is. * @param HeightInTiles How many tiles tall the tilemap is. * @param Camera Which camera this buffer relates to. */ public function FlxTilemapBuffer(TileWidth:Number,TileHeight:Number,WidthInTiles:uint,HeightInTiles:uint,Camera:FlxCamera=null) { if(Camera == null) Camera = FlxG.camera; columns = FlxU.ceil(Camera.width/TileWidth)+1; if(columns > WidthInTiles) columns = WidthInTiles; rows = FlxU.ceil(Camera.height/TileHeight)+1; if(rows > HeightInTiles) rows = HeightInTiles; _pixels = new BitmapData(columns*TileWidth,rows*TileHeight,true,0); width = _pixels.width; height = _pixels.height; _flashRect = new Rectangle(0,0,width,height); dirty = true; } /** * Clean up memory. */ public function destroy():void { _pixels = null; } /** * Fill the buffer with the specified color. * Default value is transparent. * * @param Color What color to fill with, in 0xAARRGGBB hex format. */ public function fill(Color:uint=0):void { _pixels.fillRect(_flashRect,Color); } /** * Read-only, nab the actual buffer <code>BitmapData</code> object. * * @return The buffer bitmap data. */ public function get pixels():BitmapData { return _pixels; } /** * Just stamps this buffer onto the specified camera at the specified location. * * @param Camera Which camera to draw the buffer onto. * @param FlashPoint Where to draw the buffer at in camera coordinates. */ public function draw(Camera:FlxCamera,FlashPoint:Point):void { Camera.buffer.copyPixels(_pixels,_flashRect,FlashPoint,null,null,true); } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/FlxTilemapBuffer.as
ActionScript
gpl3
3,149
package org.flixel.system { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.text.TextField; import flash.text.TextFormat; import org.flixel.FlxU; /** * A generic, Flash-based window class, created for use in <code>FlxDebugger</code>. * * @author Adam Atomic */ public class FlxWindow extends Sprite { [Embed(source="../data/handle.png")] protected var ImgHandle:Class; /** * Minimum allowed X and Y dimensions for this window. */ public var minSize:Point; /** * Maximum allowed X and Y dimensions for this window. */ public var maxSize:Point; /** * Width of the window. Using Sprite.width is super unreliable for some reason! */ protected var _width:uint; /** * Height of the window. Using Sprite.height is super unreliable for some reason! */ protected var _height:uint; /** * Controls where the window is allowed to be positioned. */ protected var _bounds:Rectangle; /** * Window display element. */ protected var _background:Bitmap; /** * Window display element. */ protected var _header:Bitmap; /** * Window display element. */ protected var _shadow:Bitmap; /** * Window display element. */ protected var _title:TextField; /** * Window display element. */ protected var _handle:Bitmap; /** * Helper for interaction. */ protected var _overHeader:Boolean; /** * Helper for interaction. */ protected var _overHandle:Boolean; /** * Helper for interaction. */ protected var _drag:Point; /** * Helper for interaction. */ protected var _dragging:Boolean; /** * Helper for interaction. */ protected var _resizing:Boolean; /** * Helper for interaction. */ protected var _resizable:Boolean; /** * Creates a new window object. This Flash-based class is mainly (only?) used by <code>FlxDebugger</code>. * * @param Title The name of the window, displayed in the header bar. * @param Width The initial width of the window. * @param Height The initial height of the window. * @param Resizable Whether you can change the size of the window with a drag handle. * @param Bounds A rectangle indicating the valid screen area for the window. * @param BGColor What color the window background should be, default is gray and transparent. * @param TopColor What color the window header bar should be, default is black and transparent. */ public function FlxWindow(Title:String,Width:Number,Height:Number,Resizable:Boolean=true,Bounds:Rectangle=null,BGColor:uint=0x7f7f7f7f, TopColor:uint=0x7f000000) { super(); _width = Width; _height = Height; _bounds = Bounds; minSize = new Point(50,30); if(_bounds != null) maxSize = new Point(_bounds.width,_bounds.height); else maxSize = new Point(Number.MAX_VALUE,Number.MAX_VALUE); _drag = new Point(); _resizable = Resizable; _shadow = new Bitmap(new BitmapData(1,2,true,0xff000000)); addChild(_shadow); _background = new Bitmap(new BitmapData(1,1,true,BGColor)); _background.y = 15; addChild(_background); _header = new Bitmap(new BitmapData(1,15,true,TopColor)); addChild(_header); _title = new TextField(); _title.x = 2; _title.height = 16; _title.selectable = false; _title.multiline = false; _title.defaultTextFormat = new TextFormat("Courier",12,0xffffff); _title.text = Title; addChild(_title); if(_resizable) { _handle = new ImgHandle(); addChild(_handle); } if((_width != 0) || (_height != 0)) updateSize(); bound(); addEventListener(Event.ENTER_FRAME,init); } /** * Clean up memory. */ public function destroy():void { minSize = null; maxSize = null; _bounds = null; removeChild(_shadow); _shadow = null; removeChild(_background); _background = null; removeChild(_header); _header = null; removeChild(_title); _title = null; if(_handle != null) removeChild(_handle); _handle = null; _drag = null; } /** * Resize the window. Subject to pre-specified minimums, maximums, and bounding rectangles. * * @param Width How wide to make the window. * @param Height How tall to make the window. */ public function resize(Width:Number,Height:Number):void { _width = Width; _height = Height; updateSize(); } /** * Change the position of the window. Subject to pre-specified bounding rectangles. * * @param X Desired X position of top left corner of the window. * @param Y Desired Y position of top left corner of the window. */ public function reposition(X:Number,Y:Number):void { x = X; y = Y; bound(); } //***EVENT HANDLERS***// /** * Used to set up basic mouse listeners. * * @param E Flash event. */ protected function init(E:Event=null):void { if(root == null) return; removeEventListener(Event.ENTER_FRAME,init); stage.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove); stage.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown); stage.addEventListener(MouseEvent.MOUSE_UP,onMouseUp); } /** * Mouse movement handler. Figures out if mouse is over handle or header bar or what. * * @param E Flash mouse event. */ protected function onMouseMove(E:MouseEvent=null):void { if(_dragging) //user is moving the window around { _overHeader = true; reposition(parent.mouseX - _drag.x, parent.mouseY - _drag.y); } else if(_resizing) { _overHandle = true; resize(mouseX - _drag.x, mouseY - _drag.y); } else if((mouseX >= 0) && (mouseX <= _width) && (mouseY >= 0) && (mouseY <= _height)) { //not dragging, mouse is over the window _overHeader = (mouseX <= _header.width) && (mouseY <= _header.height); if(_resizable) _overHandle = (mouseX >= _width - _handle.width) && (mouseY >= _height - _handle.height); } else { //not dragging, mouse is NOT over window _overHandle = _overHeader = false; } updateGUI(); } /** * Figure out if window is being repositioned (clicked on header) or resized (clicked on handle). * * @param E Flash mouse event. */ protected function onMouseDown(E:MouseEvent=null):void { if(_overHeader) { _dragging = true; _drag.x = mouseX; _drag.y = mouseY; } else if(_overHandle) { _resizing = true; _drag.x = _width-mouseX; _drag.y = _height-mouseY; } } /** * User let go of header bar or handler (or nothing), so turn off drag and resize behaviors. * * @param E Flash mouse event. */ protected function onMouseUp(E:MouseEvent=null):void { _dragging = false; _resizing = false; } //***MISC GUI MGMT STUFF***// /** * Keep the window within the pre-specified bounding rectangle. */ protected function bound():void { if(_bounds != null) { x = FlxU.bound(x,_bounds.left,_bounds.right-_width); y = FlxU.bound(y,_bounds.top,_bounds.bottom-_height); } } /** * Update the Flash shapes to match the new size, and reposition the header, shadow, and handle accordingly. */ protected function updateSize():void { _width = FlxU.bound(_width,minSize.x,maxSize.x); _height = FlxU.bound(_height,minSize.y,maxSize.y); _header.scaleX = _width; _background.scaleX = _width; _background.scaleY = _height-15; _shadow.scaleX = _width; _shadow.y = _height; _title.width = _width-4; if(_resizable) { _handle.x = _width-_handle.width; _handle.y = _height-_handle.height; } } /** * Figure out if the header or handle are highlighted. */ protected function updateGUI():void { if(_overHeader || _overHandle) { if(_title.alpha != 1.0) _title.alpha = 1.0; } else { if(_title.alpha != 0.65) _title.alpha = 0.65; } } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/FlxWindow.as
ActionScript
gpl3
8,122
package org.flixel.system { import org.flixel.FlxObject; import org.flixel.FlxTilemap; /** * A simple helper object for <code>FlxTilemap</code> that helps expand collision opportunities and control. * You can use <code>FlxTilemap.setTileProperties()</code> to alter the collision properties and * callback functions and filters for this object to do things like one-way tiles or whatever. * * @author Adam Atomic */ public class FlxTile extends FlxObject { /** * This function is called whenever an object hits a tile of this type. * This function should take the form <code>myFunction(Tile:FlxTile,Object:FlxObject):void</code>. * Defaults to null, set through <code>FlxTilemap.setTileProperties()</code>. */ public var callback:Function; /** * Each tile can store its own filter class for their callback functions. * That is, the callback will only be triggered if an object with a class * type matching the filter touched it. * Defaults to null, set through <code>FlxTilemap.setTileProperties()</code>. */ public var filter:Class; /** * A reference to the tilemap this tile object belongs to. */ public var tilemap:FlxTilemap; /** * The index of this tile type in the core map data. * For example, if your map only has 16 kinds of tiles in it, * this number is usually between 0 and 15. */ public var index:uint; /** * The current map index of this tile object at this moment. * You can think of tile objects as moving around the tilemap helping with collisions. * This value is only reliable and useful if used from the callback function. */ public var mapIndex:uint; /** * Instantiate this new tile object. This is usually called from <code>FlxTilemap.loadMap()</code>. * * @param Tilemap A reference to the tilemap object creating the tile. * @param Index The actual core map data index for this tile type. * @param Width The width of the tile. * @param Height The height of the tile. * @param Visible Whether the tile is visible or not. * @param AllowCollisions The collision flags for the object. By default this value is ANY or NONE depending on the parameters sent to loadMap(). */ public function FlxTile(Tilemap:FlxTilemap, Index:uint, Width:Number, Height:Number, Visible:Boolean, AllowCollisions:uint) { super(0, 0, Width, Height); immovable = true; moves = false; callback = null; filter = null; tilemap = Tilemap; index = Index; visible = Visible; allowCollisions = AllowCollisions; mapIndex = 0; } /** * Clean up memory. */ override public function destroy():void { super.destroy(); callback = null; tilemap = null; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/FlxTile.as
ActionScript
gpl3
2,754
package org.flixel.system { /** * Just a helper structure for the FlxSprite animation system. * * @author Adam Atomic */ public class FlxAnim { /** * String name of the animation (e.g. "walk") */ public var name:String; /** * Seconds between frames (basically the framerate) */ public var delay:Number; /** * A list of frames stored as <code>uint</code> objects */ public var frames:Array; /** * Whether or not the animation is looped */ public var looped:Boolean; /** * Constructor * * @param Name What this animation should be called (e.g. "run") * @param Frames An array of numbers indicating what frames to play in what order (e.g. 1, 2, 3) * @param FrameRate The speed in frames per second that the animation should play at (e.g. 40) * @param Looped Whether or not the animation is looped or just plays once */ public function FlxAnim(Name:String, Frames:Array, FrameRate:Number=0, Looped:Boolean=true) { name = Name; delay = 0; if(FrameRate > 0) delay = 1.0/FrameRate; frames = Frames; looped = Looped; } /** * Clean up memory. */ public function destroy():void { frames = null; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/FlxAnim.as
ActionScript
gpl3
1,218
package org.flixel.system { import org.flixel.FlxG; import org.flixel.system.replay.FrameRecord; import org.flixel.system.replay.MouseRecord; /** * The replay object both records and replays game recordings, * as well as handle saving and loading replays to and from files. * Gameplay recordings are essentially a list of keyboard and mouse inputs, * but since Flixel is fairly deterministic, we can use these to play back * recordings of gameplay with a decent amount of fidelity. * * @author Adam Atomic */ public class FlxReplay { /** * The random number generator seed value for this recording. */ public var seed:Number; /** * The current frame for this recording. */ public var frame:int; /** * The number of frames in this recording. */ public var frameCount:int; /** * Whether the replay has finished playing or not. */ public var finished:Boolean; /** * Internal container for all the frames in this replay. */ protected var _frames:Array; /** * Internal tracker for max number of frames we can fit before growing the <code>_frames</code> again. */ protected var _capacity:int; /** * Internal helper variable for keeping track of where we are in <code>_frames</code> during recording or replay. */ protected var _marker:int; /** * Instantiate a new replay object. Doesn't actually do much until you call create() or load(). */ public function FlxReplay() { seed = 0; frame = 0; frameCount = 0; finished = false; _frames = null; _capacity = 0; _marker = 0; } /** * Clean up memory. */ public function destroy():void { if(_frames == null) return; var i:int = frameCount-1; while(i >= 0) (_frames[i--] as FrameRecord).destroy(); _frames = null; } /** * Create a new gameplay recording. Requires the current random number generator seed. * * @param Seed The current seed from the random number generator. */ public function create(Seed:Number):void { destroy(); init(); seed = Seed; rewind(); } /** * Load replay data from a <code>String</code> object. * Strings can come from embedded assets or external * files loaded through the debugger overlay. * * @param FileContents A <code>String</code> object containing a gameplay recording. */ public function load(FileContents:String):void { init(); var lines:Array = FileContents.split("\n"); seed = Number(lines[0]); var line:String; var i:uint = 1; var l:uint = lines.length; while(i < l) { line = lines[i++] as String; if(line.length > 3) { _frames[frameCount++] = new FrameRecord().load(line); if(frameCount >= _capacity) { _capacity *= 2; _frames.length = _capacity; } } } rewind(); } /** * Common initialization terms used by both <code>create()</code> and <code>load()</code> to set up the replay object. */ protected function init():void { _capacity = 100; _frames = new Array(_capacity); frameCount = 0; } /** * Save the current recording data off to a <code>String</code> object. * Basically goes through and calls <code>FrameRecord.save()</code> on each frame in the replay. * * return The gameplay recording in simple ASCII format. */ public function save():String { if(frameCount <= 0) return null; var output:String = seed+"\n"; var i:uint = 0; while(i < frameCount) output += _frames[i++].save() + "\n"; return output; } /** * Get the current input data from the input managers and store it in a new frame record. */ public function recordFrame():void { var keysRecord:Array = FlxG.keys.record(); var mouseRecord:MouseRecord = FlxG.mouse.record(); if((keysRecord == null) && (mouseRecord == null)) { frame++; return; } _frames[frameCount++] = new FrameRecord().create(frame++,keysRecord,mouseRecord); if(frameCount >= _capacity) { _capacity *= 2; _frames.length = _capacity; } } /** * Get the current frame record data and load it into the input managers. */ public function playNextFrame():void { FlxG.resetInput(); if(_marker >= frameCount) { finished = true; return; } if((_frames[_marker] as FrameRecord).frame != frame++) return; var fr:FrameRecord = _frames[_marker++]; if(fr.keys != null) FlxG.keys.playback(fr.keys); if(fr.mouse != null) FlxG.mouse.playback(fr.mouse); } /** * Reset the replay back to the first frame. */ public function rewind():void { _marker = 0; frame = 0; finished = false; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/FlxReplay.as
ActionScript
gpl3
4,742
package org.flixel.system { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.display.MovieClip; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.MouseEvent; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.text.TextField; import flash.text.TextFormat; import flash.utils.getDefinitionByName; import flash.utils.getTimer; import org.flixel.FlxG; /** * This class handles the 8-bit style preloader. */ public class FlxPreloader extends MovieClip { [Embed(source="../data/logo.png")] protected var ImgLogo:Class; [Embed(source="../data/logo_corners.png")] protected var ImgLogoCorners:Class; [Embed(source="../data/logo_light.png")] protected var ImgLogoLight:Class; /** * @private */ protected var _init:Boolean; /** * @private */ protected var _buffer:Sprite; /** * @private */ protected var _bmpBar:Bitmap; /** * @private */ protected var _text:TextField; /** * Useful for storing "real" stage width if you're scaling your preloader graphics. */ protected var _width:uint; /** * Useful for storing "real" stage height if you're scaling your preloader graphics. */ protected var _height:uint; /** * @private */ protected var _logo:Bitmap; /** * @private */ protected var _logoGlow:Bitmap; /** * @private */ protected var _min:uint; /** * This should always be the name of your main project/document class (e.g. GravityHook). */ public var className:String; /** * Set this to your game's URL to use built-in site-locking. */ public var myURL:String; /** * Change this if you want the flixel logo to show for more or less time. Default value is 0 seconds. */ public var minDisplayTime:Number; /** * Constructor */ public function FlxPreloader() { minDisplayTime = 0; stop(); stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; //Check if we are on debug or release mode and set _DEBUG accordingly try { throw new Error("Setting global debug flag..."); } catch(E:Error) { var re:RegExp = /\[.*:[0-9]+\]/; FlxG.debug = re.test(E.getStackTrace()); } var tmp:Bitmap; if(!FlxG.debug && (myURL != null) && (root.loaderInfo.url.indexOf(myURL) < 0)) { tmp = new Bitmap(new BitmapData(stage.stageWidth,stage.stageHeight,true,0xFFFFFFFF)); addChild(tmp); var format:TextFormat = new TextFormat(); format.color = 0x000000; format.size = 16; format.align = "center"; format.bold = true; format.font = "system"; var textField:TextField = new TextField(); textField.width = tmp.width-16; textField.height = tmp.height-16; textField.y = 8; textField.multiline = true; textField.wordWrap = true; textField.embedFonts = true; textField.defaultTextFormat = format; textField.text = "Hi there! It looks like somebody copied this game without my permission. Just click anywhere, or copy-paste this URL into your browser.\n\n"+myURL+"\n\nto play the game at my site. Thanks, and have fun!"; addChild(textField); textField.addEventListener(MouseEvent.CLICK,goToMyURL); tmp.addEventListener(MouseEvent.CLICK,goToMyURL); return; } this._init = false; addEventListener(Event.ENTER_FRAME, onEnterFrame); } private function goToMyURL(event:MouseEvent=null):void { navigateToURL(new URLRequest("http://"+myURL)); } private function onEnterFrame(event:Event):void { if(!this._init) { if((stage.stageWidth <= 0) || (stage.stageHeight <= 0)) return; create(); this._init = true; } graphics.clear(); var time:uint = getTimer(); if((framesLoaded >= totalFrames) && (time > _min)) { removeEventListener(Event.ENTER_FRAME, onEnterFrame); nextFrame(); var mainClass:Class = Class(getDefinitionByName(className)); if(mainClass) { var app:Object = new mainClass(); addChild(app as DisplayObject); } destroy(); } else { var percent:Number = root.loaderInfo.bytesLoaded/root.loaderInfo.bytesTotal; if((_min > 0) && (percent > time/_min)) percent = time/_min; update(percent); } } /** * Override this to create your own preloader objects. * Highly recommended you also override update()! */ protected function create():void { _min = 0; if(!FlxG.debug) _min = minDisplayTime*1000; _buffer = new Sprite(); _buffer.scaleX = 2; _buffer.scaleY = 2; addChild(_buffer); _width = stage.stageWidth/_buffer.scaleX; _height = stage.stageHeight/_buffer.scaleY; _buffer.addChild(new Bitmap(new BitmapData(_width,_height,false,0x00345e))); var bitmap:Bitmap = new ImgLogoLight(); bitmap.smoothing = true; bitmap.width = bitmap.height = _height; bitmap.x = (_width-bitmap.width)/2; _buffer.addChild(bitmap); _bmpBar = new Bitmap(new BitmapData(1,7,false,0x5f6aff)); _bmpBar.x = 4; _bmpBar.y = _height-11; _buffer.addChild(_bmpBar); _text = new TextField(); _text.defaultTextFormat = new TextFormat("system",8,0x5f6aff); _text.embedFonts = true; _text.selectable = false; _text.multiline = false; _text.x = 2; _text.y = _bmpBar.y - 11; _text.width = 80; _buffer.addChild(_text); _logo = new ImgLogo(); _logo.scaleX = _logo.scaleY = _height/8; _logo.x = (_width-_logo.width)/2; _logo.y = (_height-_logo.height)/2; _buffer.addChild(_logo); _logoGlow = new ImgLogo(); _logoGlow.smoothing = true; _logoGlow.blendMode = "screen"; _logoGlow.scaleX = _logoGlow.scaleY = _height/8; _logoGlow.x = (_width-_logoGlow.width)/2; _logoGlow.y = (_height-_logoGlow.height)/2; _buffer.addChild(_logoGlow); bitmap = new ImgLogoCorners(); bitmap.smoothing = true; bitmap.width = _width; bitmap.height = _height; _buffer.addChild(bitmap); bitmap = new Bitmap(new BitmapData(_width,_height,false,0xffffff)); var i:uint = 0; var j:uint = 0; while(i < _height) { j = 0; while(j < _width) bitmap.bitmapData.setPixel(j++,i,0); i+=2; } bitmap.blendMode = "overlay"; bitmap.alpha = 0.25; _buffer.addChild(bitmap); } protected function destroy():void { removeChild(_buffer); _buffer = null; _bmpBar = null; _text = null; _logo = null; _logoGlow = null; } /** * Override this function to manually update the preloader. * * @param Percent How much of the program has loaded. */ protected function update(Percent:Number):void { _bmpBar.scaleX = Percent*(_width-8); _text.text = "FLX v"+FlxG.LIBRARY_MAJOR_VERSION+"."+FlxG.LIBRARY_MINOR_VERSION+" "+Math.floor(Percent*100)+"%"; _text.setTextFormat(_text.defaultTextFormat); if(Percent < 0.1) { _logoGlow.alpha = 0; _logo.alpha = 0; } else if(Percent < 0.15) { _logoGlow.alpha = Math.random(); _logo.alpha = 0; } else if(Percent < 0.2) { _logoGlow.alpha = 0; _logo.alpha = 0; } else if(Percent < 0.25) { _logoGlow.alpha = 0; _logo.alpha = Math.random(); } else if(Percent < 0.7) { _logoGlow.alpha = (Percent-0.45)/0.45; _logo.alpha = 1; } else if((Percent > 0.8) && (Percent < 0.9)) { _logoGlow.alpha = 1-(Percent-0.8)/0.1; _logo.alpha = 0; } else if(Percent > 0.9) { _buffer.alpha = 1-(Percent-0.9)/0.1; } } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/FlxPreloader.as
ActionScript
gpl3
7,896
package org.flixel.system { import org.flixel.FlxBasic; import org.flixel.FlxGroup; import org.flixel.FlxObject; import org.flixel.FlxRect; /** * A fairly generic quad tree structure for rapid overlap checks. * FlxQuadTree is also configured for single or dual list operation. * You can add items either to its A list or its B list. * When you do an overlap check, you can compare the A list to itself, * or the A list against the B list. Handy for different things! */ public class FlxQuadTree extends FlxRect { /** * Flag for specifying that you want to add an object to the A list. */ static public const A_LIST:uint = 0; /** * Flag for specifying that you want to add an object to the B list. */ static public const B_LIST:uint = 1; /** * Controls the granularity of the quad tree. Default is 6 (decent performance on large and small worlds). */ static public var divisions:uint; /** * Whether this branch of the tree can be subdivided or not. */ protected var _canSubdivide:Boolean; /** * Refers to the internal A and B linked lists, * which are used to store objects in the leaves. */ protected var _headA:FlxList; /** * Refers to the internal A and B linked lists, * which are used to store objects in the leaves. */ protected var _tailA:FlxList; /** * Refers to the internal A and B linked lists, * which are used to store objects in the leaves. */ protected var _headB:FlxList; /** * Refers to the internal A and B linked lists, * which are used to store objects in the leaves. */ protected var _tailB:FlxList; /** * Internal, governs and assists with the formation of the tree. */ static protected var _min:uint; /** * Internal, governs and assists with the formation of the tree. */ protected var _northWestTree:FlxQuadTree; /** * Internal, governs and assists with the formation of the tree. */ protected var _northEastTree:FlxQuadTree; /** * Internal, governs and assists with the formation of the tree. */ protected var _southEastTree:FlxQuadTree; /** * Internal, governs and assists with the formation of the tree. */ protected var _southWestTree:FlxQuadTree; /** * Internal, governs and assists with the formation of the tree. */ protected var _leftEdge:Number; /** * Internal, governs and assists with the formation of the tree. */ protected var _rightEdge:Number; /** * Internal, governs and assists with the formation of the tree. */ protected var _topEdge:Number; /** * Internal, governs and assists with the formation of the tree. */ protected var _bottomEdge:Number; /** * Internal, governs and assists with the formation of the tree. */ protected var _halfWidth:Number; /** * Internal, governs and assists with the formation of the tree. */ protected var _halfHeight:Number; /** * Internal, governs and assists with the formation of the tree. */ protected var _midpointX:Number; /** * Internal, governs and assists with the formation of the tree. */ protected var _midpointY:Number; /** * Internal, used to reduce recursive method parameters during object placement and tree formation. */ static protected var _object:FlxObject; /** * Internal, used to reduce recursive method parameters during object placement and tree formation. */ static protected var _objectLeftEdge:Number; /** * Internal, used to reduce recursive method parameters during object placement and tree formation. */ static protected var _objectTopEdge:Number; /** * Internal, used to reduce recursive method parameters during object placement and tree formation. */ static protected var _objectRightEdge:Number; /** * Internal, used to reduce recursive method parameters during object placement and tree formation. */ static protected var _objectBottomEdge:Number; /** * Internal, used during tree processing and overlap checks. */ static protected var _list:uint; /** * Internal, used during tree processing and overlap checks. */ static protected var _useBothLists:Boolean; /** * Internal, used during tree processing and overlap checks. */ static protected var _processingCallback:Function; /** * Internal, used during tree processing and overlap checks. */ static protected var _notifyCallback:Function; /** * Internal, used during tree processing and overlap checks. */ static protected var _iterator:FlxList; /** * Internal, helpers for comparing actual object-to-object overlap - see <code>overlapNode()</code>. */ static protected var _objectHullX:Number; /** * Internal, helpers for comparing actual object-to-object overlap - see <code>overlapNode()</code>. */ static protected var _objectHullY:Number; /** * Internal, helpers for comparing actual object-to-object overlap - see <code>overlapNode()</code>. */ static protected var _objectHullWidth:Number; /** * Internal, helpers for comparing actual object-to-object overlap - see <code>overlapNode()</code>. */ static protected var _objectHullHeight:Number; /** * Internal, helpers for comparing actual object-to-object overlap - see <code>overlapNode()</code>. */ static protected var _checkObjectHullX:Number; /** * Internal, helpers for comparing actual object-to-object overlap - see <code>overlapNode()</code>. */ static protected var _checkObjectHullY:Number; /** * Internal, helpers for comparing actual object-to-object overlap - see <code>overlapNode()</code>. */ static protected var _checkObjectHullWidth:Number; /** * Internal, helpers for comparing actual object-to-object overlap - see <code>overlapNode()</code>. */ static protected var _checkObjectHullHeight:Number; /** * Instantiate a new Quad Tree node. * * @param X The X-coordinate of the point in space. * @param Y The Y-coordinate of the point in space. * @param Width Desired width of this node. * @param Height Desired height of this node. * @param Parent The parent branch or node. Pass null to create a root. */ public function FlxQuadTree(X:Number, Y:Number, Width:Number, Height:Number, Parent:FlxQuadTree=null) { super(X,Y,Width,Height); _headA = _tailA = new FlxList(); _headB = _tailB = new FlxList(); //Copy the parent's children (if there are any) if(Parent != null) { var iterator:FlxList; var ot:FlxList; if(Parent._headA.object != null) { iterator = Parent._headA; while(iterator != null) { if(_tailA.object != null) { ot = _tailA; _tailA = new FlxList(); ot.next = _tailA; } _tailA.object = iterator.object; iterator = iterator.next; } } if(Parent._headB.object != null) { iterator = Parent._headB; while(iterator != null) { if(_tailB.object != null) { ot = _tailB; _tailB = new FlxList(); ot.next = _tailB; } _tailB.object = iterator.object; iterator = iterator.next; } } } else _min = (width + height)/(2*divisions); _canSubdivide = (width > _min) || (height > _min); //Set up comparison/sort helpers _northWestTree = null; _northEastTree = null; _southEastTree = null; _southWestTree = null; _leftEdge = x; _rightEdge = x+width; _halfWidth = width/2; _midpointX = _leftEdge+_halfWidth; _topEdge = y; _bottomEdge = y+height; _halfHeight = height/2; _midpointY = _topEdge+_halfHeight; } /** * Clean up memory. */ public function destroy():void { _headA.destroy(); _headA = null; _tailA.destroy(); _tailA = null; _headB.destroy(); _headB = null; _tailB.destroy(); _tailB = null; if(_northWestTree != null) _northWestTree.destroy(); _northWestTree = null; if(_northEastTree != null) _northEastTree.destroy(); _northEastTree = null; if(_southEastTree != null) _southEastTree.destroy(); _southEastTree = null; if(_southWestTree != null) _southWestTree.destroy(); _southWestTree = null; _object = null; _processingCallback = null; _notifyCallback = null; } /** * Load objects and/or groups into the quad tree, and register notify and processing callbacks. * * @param ObjectOrGroup1 Any object that is or extends FlxObject or FlxGroup. * @param ObjectOrGroup2 Any object that is or extends FlxObject or FlxGroup. If null, the first parameter will be checked against itself. * @param NotifyCallback A function with the form <code>myFunction(Object1:FlxObject,Object2:FlxObject):void</code> that is called whenever two objects are found to overlap in world space, and either no ProcessCallback is specified, or the ProcessCallback returns true. * @param ProcessCallback A function with the form <code>myFunction(Object1:FlxObject,Object2:FlxObject):Boolean</code> that is called whenever two objects are found to overlap in world space. The NotifyCallback is only called if this function returns true. See FlxObject.separate(). */ public function load(ObjectOrGroup1:FlxBasic, ObjectOrGroup2:FlxBasic=null, NotifyCallback:Function=null, ProcessCallback:Function=null):void { add(ObjectOrGroup1, A_LIST); if(ObjectOrGroup2 != null) { add(ObjectOrGroup2, B_LIST); _useBothLists = true; } else _useBothLists = false; _notifyCallback = NotifyCallback; _processingCallback = ProcessCallback; } /** * Call this function to add an object to the root of the tree. * This function will recursively add all group members, but * not the groups themselves. * * @param ObjectOrGroup FlxObjects are just added, FlxGroups are recursed and their applicable members added accordingly. * @param List A <code>uint</code> flag indicating the list to which you want to add the objects. Options are <code>A_LIST</code> and <code>B_LIST</code>. */ public function add(ObjectOrGroup:FlxBasic, List:uint):void { _list = List; if(ObjectOrGroup is FlxGroup) { var i:uint = 0; var basic:FlxBasic; var members:Array = (ObjectOrGroup as FlxGroup).members; var l:uint = (ObjectOrGroup as FlxGroup).length; while(i < l) { basic = members[i++] as FlxBasic; if((basic != null) && basic.exists) { if(basic is FlxGroup) add(basic,List); else if(basic is FlxObject) { _object = basic as FlxObject; if(_object.exists && _object.allowCollisions) { _objectLeftEdge = _object.x; _objectTopEdge = _object.y; _objectRightEdge = _object.x + _object.width; _objectBottomEdge = _object.y + _object.height; addObject(); } } } } } else { _object = ObjectOrGroup as FlxObject; if(_object.exists && _object.allowCollisions) { _objectLeftEdge = _object.x; _objectTopEdge = _object.y; _objectRightEdge = _object.x + _object.width; _objectBottomEdge = _object.y + _object.height; addObject(); } } } /** * Internal function for recursively navigating and creating the tree * while adding objects to the appropriate nodes. */ protected function addObject():void { //If this quad (not its children) lies entirely inside this object, add it here if(!_canSubdivide || ((_leftEdge >= _objectLeftEdge) && (_rightEdge <= _objectRightEdge) && (_topEdge >= _objectTopEdge) && (_bottomEdge <= _objectBottomEdge))) { addToList(); return; } //See if the selected object fits completely inside any of the quadrants if((_objectLeftEdge > _leftEdge) && (_objectRightEdge < _midpointX)) { if((_objectTopEdge > _topEdge) && (_objectBottomEdge < _midpointY)) { if(_northWestTree == null) _northWestTree = new FlxQuadTree(_leftEdge,_topEdge,_halfWidth,_halfHeight,this); _northWestTree.addObject(); return; } if((_objectTopEdge > _midpointY) && (_objectBottomEdge < _bottomEdge)) { if(_southWestTree == null) _southWestTree = new FlxQuadTree(_leftEdge,_midpointY,_halfWidth,_halfHeight,this); _southWestTree.addObject(); return; } } if((_objectLeftEdge > _midpointX) && (_objectRightEdge < _rightEdge)) { if((_objectTopEdge > _topEdge) && (_objectBottomEdge < _midpointY)) { if(_northEastTree == null) _northEastTree = new FlxQuadTree(_midpointX,_topEdge,_halfWidth,_halfHeight,this); _northEastTree.addObject(); return; } if((_objectTopEdge > _midpointY) && (_objectBottomEdge < _bottomEdge)) { if(_southEastTree == null) _southEastTree = new FlxQuadTree(_midpointX,_midpointY,_halfWidth,_halfHeight,this); _southEastTree.addObject(); return; } } //If it wasn't completely contained we have to check out the partial overlaps if((_objectRightEdge > _leftEdge) && (_objectLeftEdge < _midpointX) && (_objectBottomEdge > _topEdge) && (_objectTopEdge < _midpointY)) { if(_northWestTree == null) _northWestTree = new FlxQuadTree(_leftEdge,_topEdge,_halfWidth,_halfHeight,this); _northWestTree.addObject(); } if((_objectRightEdge > _midpointX) && (_objectLeftEdge < _rightEdge) && (_objectBottomEdge > _topEdge) && (_objectTopEdge < _midpointY)) { if(_northEastTree == null) _northEastTree = new FlxQuadTree(_midpointX,_topEdge,_halfWidth,_halfHeight,this); _northEastTree.addObject(); } if((_objectRightEdge > _midpointX) && (_objectLeftEdge < _rightEdge) && (_objectBottomEdge > _midpointY) && (_objectTopEdge < _bottomEdge)) { if(_southEastTree == null) _southEastTree = new FlxQuadTree(_midpointX,_midpointY,_halfWidth,_halfHeight,this); _southEastTree.addObject(); } if((_objectRightEdge > _leftEdge) && (_objectLeftEdge < _midpointX) && (_objectBottomEdge > _midpointY) && (_objectTopEdge < _bottomEdge)) { if(_southWestTree == null) _southWestTree = new FlxQuadTree(_leftEdge,_midpointY,_halfWidth,_halfHeight,this); _southWestTree.addObject(); } } /** * Internal function for recursively adding objects to leaf lists. */ protected function addToList():void { var ot:FlxList; if(_list == A_LIST) { if(_tailA.object != null) { ot = _tailA; _tailA = new FlxList(); ot.next = _tailA; } _tailA.object = _object; } else { if(_tailB.object != null) { ot = _tailB; _tailB = new FlxList(); ot.next = _tailB; } _tailB.object = _object; } if(!_canSubdivide) return; if(_northWestTree != null) _northWestTree.addToList(); if(_northEastTree != null) _northEastTree.addToList(); if(_southEastTree != null) _southEastTree.addToList(); if(_southWestTree != null) _southWestTree.addToList(); } /** * <code>FlxQuadTree</code>'s other main function. Call this after adding objects * using <code>FlxQuadTree.load()</code> to compare the objects that you loaded. * * @return Whether or not any overlaps were found. */ public function execute():Boolean { var overlapProcessed:Boolean = false; var iterator:FlxList; if(_headA.object != null) { iterator = _headA; while(iterator != null) { _object = iterator.object; if(_useBothLists) _iterator = _headB; else _iterator = iterator.next; if( _object.exists && (_object.allowCollisions > 0) && (_iterator != null) && (_iterator.object != null) && _iterator.object.exists &&overlapNode()) { overlapProcessed = true; } iterator = iterator.next; } } //Advance through the tree by calling overlap on each child if((_northWestTree != null) && _northWestTree.execute()) overlapProcessed = true; if((_northEastTree != null) && _northEastTree.execute()) overlapProcessed = true; if((_southEastTree != null) && _southEastTree.execute()) overlapProcessed = true; if((_southWestTree != null) && _southWestTree.execute()) overlapProcessed = true; return overlapProcessed; } /** * An internal function for comparing an object against the contents of a node. * * @return Whether or not any overlaps were found. */ protected function overlapNode():Boolean { //Walk the list and check for overlaps var overlapProcessed:Boolean = false; var checkObject:FlxObject; while(_iterator != null) { if(!_object.exists || (_object.allowCollisions <= 0)) break; checkObject = _iterator.object; if((_object === checkObject) || !checkObject.exists || (checkObject.allowCollisions <= 0)) { _iterator = _iterator.next; continue; } //calculate bulk hull for _object _objectHullX = (_object.x < _object.last.x)?_object.x:_object.last.x; _objectHullY = (_object.y < _object.last.y)?_object.y:_object.last.y; _objectHullWidth = _object.x - _object.last.x; _objectHullWidth = _object.width + ((_objectHullWidth>0)?_objectHullWidth:-_objectHullWidth); _objectHullHeight = _object.y - _object.last.y; _objectHullHeight = _object.height + ((_objectHullHeight>0)?_objectHullHeight:-_objectHullHeight); //calculate bulk hull for checkObject _checkObjectHullX = (checkObject.x < checkObject.last.x)?checkObject.x:checkObject.last.x; _checkObjectHullY = (checkObject.y < checkObject.last.y)?checkObject.y:checkObject.last.y; _checkObjectHullWidth = checkObject.x - checkObject.last.x; _checkObjectHullWidth = checkObject.width + ((_checkObjectHullWidth>0)?_checkObjectHullWidth:-_checkObjectHullWidth); _checkObjectHullHeight = checkObject.y - checkObject.last.y; _checkObjectHullHeight = checkObject.height + ((_checkObjectHullHeight>0)?_checkObjectHullHeight:-_checkObjectHullHeight); //check for intersection of the two hulls if( (_objectHullX + _objectHullWidth > _checkObjectHullX) && (_objectHullX < _checkObjectHullX + _checkObjectHullWidth) && (_objectHullY + _objectHullHeight > _checkObjectHullY) && (_objectHullY < _checkObjectHullY + _checkObjectHullHeight) ) { //Execute callback functions if they exist if((_processingCallback == null) || _processingCallback(_object,checkObject)) overlapProcessed = true; if(overlapProcessed && (_notifyCallback != null)) _notifyCallback(_object,checkObject); } _iterator = _iterator.next; } return overlapProcessed; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/FlxQuadTree.as
ActionScript
gpl3
18,684
package org.flixel.system.replay { /** * A helper class for the frame records, part of the replay/demo/recording system. * * @author Adam Atomic */ public class MouseRecord { /** * The main X value of the mouse in screen space. */ public var x:int; /** * The main Y value of the mouse in screen space. */ public var y:int; /** * The state of the left mouse button. */ public var button:int; /** * The state of the mouse wheel. */ public var wheel:int; /** * Instantiate a new mouse input record. * * @param X The main X value of the mouse in screen space. * @param Y The main Y value of the mouse in screen space. * @param Button The state of the left mouse button. * @param Wheel The state of the mouse wheel. */ public function MouseRecord(X:int,Y:int,Button:int,Wheel:int) { x = X; y = Y; button = Button; wheel = Wheel; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/replay/MouseRecord.as
ActionScript
gpl3
933
package org.flixel.system.replay { /** * Helper class for the new replay system. Represents all the game inputs for one "frame" or "step" of the game loop. * * @author Adam Atomic */ public class FrameRecord { /** * Which frame of the game loop this record is from or for. */ public var frame:int; /** * An array of simple integer pairs referring to what key is pressed, and what state its in. */ public var keys:Array; /** * A container for the 4 mouse state integers. */ public var mouse:MouseRecord; /** * Instantiate array new frame record. */ public function FrameRecord() { frame = 0; keys = null; mouse = null; } /** * Load this frame record with input data from the input managers. * * @param Frame What frame it is. * @param Keys Keyboard data from the keyboard manager. * @param Mouse Mouse data from the mouse manager. * * @return A reference to this <code>FrameRecord</code> object. * */ public function create(Frame:Number,Keys:Array=null,Mouse:MouseRecord=null):FrameRecord { frame = Frame; keys = Keys; mouse = Mouse; return this; } /** * Clean up memory. */ public function destroy():void { keys = null; mouse = null; } /** * Save the frame record data to array simple ASCII string. * * @return A <code>String</code> object containing the relevant frame record data. */ public function save():String { var output:String = frame+"k"; if(keys != null) { var object:Object; var i:uint = 0; var l:uint = keys.length; while(i < l) { if(i > 0) output += ","; object = keys[i++]; output += object.code+":"+object.value; } } output += "m"; if(mouse != null) output += mouse.x + "," + mouse.y + "," + mouse.button + "," + mouse.wheel; return output; } /** * Load the frame record data from array simple ASCII string. * * @param Data A <code>String</code> object containing the relevant frame record data. */ public function load(Data:String):FrameRecord { var i:uint; var l:uint; //get frame number var array:Array = Data.split("k"); frame = int(array[0] as String); //split up keyboard and mouse data array = (array[1] as String).split("m"); var keyData:String = array[0]; var mouseData:String = array[1]; //parse keyboard data if(keyData.length > 0) { //get keystroke data pairs array = keyData.split(","); //go through each data pair and enter it into this frame's key state var keyPair:Array; i = 0; l = array.length; while(i < l) { keyPair = (array[i++] as String).split(":"); if(keyPair.length == 2) { if(keys == null) keys = new Array(); keys.push({code:int(keyPair[0] as String),value:int(keyPair[1] as String)}); } } } //mouse data is just 4 integers, easy peezy if(mouseData.length > 0) { array = mouseData.split(","); if(array.length >= 4) mouse = new MouseRecord(int(array[0] as String),int(array[1] as String),int(array[2] as String),int(array[3] as String)); } return this; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/system/replay/FrameRecord.as
ActionScript
gpl3
3,249
package org.flixel { import flash.events.MouseEvent; /** * A simple button class that calls a function when clicked by the mouse. * * @author Adam Atomic */ public class FlxButton extends FlxSprite { [Embed(source="data/button.png")] protected var ImgDefaultButton:Class; [Embed(source="data/beep.mp3")] protected var SndBeep:Class; /** * Used with public variable <code>status</code>, means not highlighted or pressed. */ static public var NORMAL:uint = 0; /** * Used with public variable <code>status</code>, means highlighted (usually from mouse over). */ static public var HIGHLIGHT:uint = 1; /** * Used with public variable <code>status</code>, means pressed (usually from mouse click). */ static public var PRESSED:uint = 2; /** * The text that appears on the button. */ public var label:FlxText; /** * Controls the offset (from top left) of the text from the button. */ public var labelOffset:FlxPoint; /** * This function is called when the button is released. * We recommend assigning your main button behavior to this function * via the <code>FlxButton</code> constructor. */ public var onUp:Function; /** * This function is called when the button is pressed down. */ public var onDown:Function; /** * This function is called when the mouse goes over the button. */ public var onOver:Function; /** * This function is called when the mouse leaves the button area. */ public var onOut:Function; /** * Shows the current state of the button. */ public var status:uint; /** * Set this to play a sound when the mouse goes over the button. * We recommend using the helper function setSounds()! */ public var soundOver:FlxSound; /** * Set this to play a sound when the mouse leaves the button. * We recommend using the helper function setSounds()! */ public var soundOut:FlxSound; /** * Set this to play a sound when the button is pressed down. * We recommend using the helper function setSounds()! */ public var soundDown:FlxSound; /** * Set this to play a sound when the button is released. * We recommend using the helper function setSounds()! */ public var soundUp:FlxSound; /** * Used for checkbox-style behavior. */ protected var _onToggle:Boolean; /** * Tracks whether or not the button is currently pressed. */ protected var _pressed:Boolean; /** * Whether or not the button has initialized itself yet. */ protected var _initialized:Boolean; /** * Creates a new <code>FlxButton</code> object with a gray background * and a callback function on the UI thread. * * @param X The X position of the button. * @param Y The Y position of the button. * @param Label The text that you want to appear on the button. * @param OnClick The function to call whenever the button is clicked. */ public function FlxButton(X:Number=0,Y:Number=0,Label:String=null,OnClick:Function=null) { super(X,Y); if(Label != null) { label = new FlxText(0,0,80,Label); label.setFormat(null,8,0x333333,"center"); labelOffset = new FlxPoint(-1,3); } loadGraphic(ImgDefaultButton,true,false,80,20); onUp = OnClick; onDown = null; onOut = null; onOver = null; soundOver = null; soundOut = null; soundDown = null; soundUp = null; status = NORMAL; _onToggle = false; _pressed = false; _initialized = false; } /** * Called by the game state when state is changed (if this object belongs to the state) */ override public function destroy():void { if(FlxG.stage != null) FlxG.stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp); if(label != null) { label.destroy(); label = null; } onUp = null; onDown = null; onOut = null; onOver = null; if(soundOver != null) soundOver.destroy(); if(soundOut != null) soundOut.destroy(); if(soundDown != null) soundDown.destroy(); if(soundUp != null) soundUp.destroy(); super.destroy(); } /** * Since button uses its own mouse handler for thread reasons, * we run a little pre-check here to make sure that we only add * the mouse handler when it is actually safe to do so. */ override public function preUpdate():void { super.preUpdate(); if(!_initialized) { if(FlxG.stage != null) { FlxG.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp); _initialized = true; } } } /** * Called by the game loop automatically, handles mouseover and click detection. */ override public function update():void { updateButton(); //Basic button logic //Default button appearance is to simply update // the label appearance based on animation frame. if(label == null) return; switch(frame) { case HIGHLIGHT: //Extra behavior to accomodate checkbox logic. label.alpha = 1.0; break; case PRESSED: label.alpha = 0.5; label.y++; break; case NORMAL: default: label.alpha = 0.8; break; } } /** * Basic button update logic */ protected function updateButton():void { //Figure out if the button is highlighted or pressed or what // (ignore checkbox behavior for now). if(FlxG.mouse.visible) { if(cameras == null) cameras = FlxG.cameras; var camera:FlxCamera; var i:uint = 0; var l:uint = cameras.length; var offAll:Boolean = true; while(i < l) { camera = cameras[i++] as FlxCamera; FlxG.mouse.getWorldPosition(camera,_point); if(overlapsPoint(_point,true,camera)) { offAll = false; if(FlxG.mouse.justPressed()) { status = PRESSED; if(onDown != null) onDown(); if(soundDown != null) soundDown.play(true); } if(status == NORMAL) { status = HIGHLIGHT; if(onOver != null) onOver(); if(soundOver != null) soundOver.play(true); } } } if(offAll) { if(status != NORMAL) { if(onOut != null) onOut(); if(soundOut != null) soundOut.play(true); } status = NORMAL; } } //Then if the label and/or the label offset exist, // position them to match the button. if(label != null) { label.x = x; label.y = y; } if(labelOffset != null) { label.x += labelOffset.x; label.y += labelOffset.y; } //Then pick the appropriate frame of animation if((status == HIGHLIGHT) && _onToggle) frame = NORMAL; else frame = status; } /** * Just draws the button graphic and text label to the screen. */ override public function draw():void { super.draw(); if(label != null) { label.scrollFactor = scrollFactor; label.cameras = cameras; label.draw(); } } /** * Updates the size of the text field to match the button. */ override protected function resetHelpers():void { super.resetHelpers(); if(label != null) label.width = width; } /** * Set sounds to play during mouse-button interactions. * These operations can be done manually as well, and the public * sound variables can be used after this for more fine-tuning, * such as positional audio, etc. * * @param SoundOver What embedded sound effect to play when the mouse goes over the button. Default is null, or no sound. * @param SoundOverVolume How load the that sound should be. * @param SoundOut What embedded sound effect to play when the mouse leaves the button area. Default is null, or no sound. * @param SoundOutVolume How load the that sound should be. * @param SoundDown What embedded sound effect to play when the mouse presses the button down. Default is null, or no sound. * @param SoundDownVolume How load the that sound should be. * @param SoundUp What embedded sound effect to play when the mouse releases the button. Default is null, or no sound. * @param SoundUpVolume How load the that sound should be. */ public function setSounds(SoundOver:Class=null, SoundOverVolume:Number=1.0, SoundOut:Class=null, SoundOutVolume:Number=1.0, SoundDown:Class=null, SoundDownVolume:Number=1.0, SoundUp:Class=null, SoundUpVolume:Number=1.0):void { if(SoundOver != null) soundOver = FlxG.loadSound(SoundOver, SoundOverVolume); if(SoundOut != null) soundOut = FlxG.loadSound(SoundOut, SoundOutVolume); if(SoundDown != null) soundDown = FlxG.loadSound(SoundDown, SoundDownVolume); if(SoundUp != null) soundUp = FlxG.loadSound(SoundUp, SoundUpVolume); } /** * Use this to toggle checkbox-style behavior. */ public function get on():Boolean { return _onToggle; } /** * @private */ public function set on(On:Boolean):void { _onToggle = On; } /** * Internal function for handling the actual callback call (for UI thread dependent calls like <code>FlxU.openURL()</code>). */ protected function onMouseUp(event:MouseEvent):void { if(!exists || !visible || !active || (status != PRESSED)) return; if(onUp != null) onUp(); if(soundUp != null) soundUp.play(true); } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxButton.as
ActionScript
gpl3
9,306
package org.flixel { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Graphics; import flash.geom.ColorTransform; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import org.flixel.system.FlxAnim; /** * The main "game object" class, the sprite is a <code>FlxObject</code> * with a bunch of graphics options and abilities, like animation and stamping. * * @author Adam Atomic */ public class FlxSprite extends FlxObject { [Embed(source="data/default.png")] protected var ImgDefault:Class; /** * WARNING: The origin of the sprite will default to its center. * If you change this, the visuals and the collisions will likely be * pretty out-of-sync if you do any rotation. */ public var origin:FlxPoint; /** * If you changed the size of your sprite object after loading or making the graphic, * you might need to offset the graphic away from the bound box to center it the way you want. */ public var offset:FlxPoint; /** * Change the size of your sprite's graphic. * NOTE: Scale doesn't currently affect collisions automatically, * you will need to adjust the width, height and offset manually. * WARNING: scaling sprites decreases rendering performance for this sprite by a factor of 10x! */ public var scale:FlxPoint; /** * Blending modes, just like Photoshop or whatever. * E.g. "multiply", "screen", etc. * @default null */ public var blend:String; /** * Controls whether the object is smoothed when rotated, affects performance. * @default false */ public var antialiasing:Boolean; /** * Whether the current animation has finished its first (or only) loop. */ public var finished:Boolean; /** * The width of the actual graphic or image being displayed (not necessarily the game object/bounding box). * NOTE: Edit at your own risk!! This is intended to be read-only. */ public var frameWidth:uint; /** * The height of the actual graphic or image being displayed (not necessarily the game object/bounding box). * NOTE: Edit at your own risk!! This is intended to be read-only. */ public var frameHeight:uint; /** * The total number of frames in this image. WARNING: assumes each row in the sprite sheet is full! */ public var frames:uint; /** * The actual Flash <code>BitmapData</code> object representing the current display state of the sprite. */ public var framePixels:BitmapData; /** * Set this flag to true to force the sprite to update during the draw() call. * NOTE: Rarely if ever necessary, most sprite operations will flip this flag automatically. */ public var dirty:Boolean; /** * Internal, stores all the animations that were added to this sprite. */ protected var _animations:Array; /** * Internal, keeps track of whether the sprite was loaded with support for automatic reverse/mirroring. */ protected var _flipped:uint; /** * Internal, keeps track of the current animation being played. */ protected var _curAnim:FlxAnim; /** * Internal, keeps track of the current frame of animation. * This is NOT an index into the tile sheet, but the frame number in the animation object. */ protected var _curFrame:uint; /** * Internal, keeps track of the current index into the tile sheet based on animation or rotation. */ protected var _curIndex:uint; /** * Internal, used to time each frame of animation. */ protected var _frameTimer:Number; /** * Internal tracker for the animation callback. Default is null. * If assigned, will be called each time the current frame changes. * A function that has 3 parameters: a string name, a uint frame number, and a uint frame index. */ protected var _callback:Function; /** * Internal tracker for what direction the sprite is currently facing, used with Flash getter/setter. */ protected var _facing:uint; /** * Internal tracker for opacity, used with Flash getter/setter. */ protected var _alpha:Number; /** * Internal tracker for color tint, used with Flash getter/setter. */ protected var _color:uint; /** * Internal tracker for how many frames of "baked" rotation there are (if any). */ protected var _bakedRotation:Number; /** * Internal, stores the entire source graphic (not the current displayed animation frame), used with Flash getter/setter. */ protected var _pixels:BitmapData; /** * Internal, reused frequently during drawing and animating. */ protected var _flashPoint:Point; /** * Internal, reused frequently during drawing and animating. */ protected var _flashRect:Rectangle; /** * Internal, reused frequently during drawing and animating. */ protected var _flashRect2:Rectangle; /** * Internal, reused frequently during drawing and animating. Always contains (0,0). */ protected var _flashPointZero:Point; /** * Internal, helps with animation, caching and drawing. */ protected var _colorTransform:ColorTransform; /** * Internal, helps with animation, caching and drawing. */ protected var _matrix:Matrix; /** * Creates a white 8x8 square <code>FlxSprite</code> at the specified position. * Optionally can load a simple, one-frame graphic instead. * * @param X The initial X position of the sprite. * @param Y The initial Y position of the sprite. * @param SimpleGraphic The graphic you want to display (OPTIONAL - for simple stuff only, do NOT use for animated images!). */ public function FlxSprite(X:Number=0,Y:Number=0,SimpleGraphic:Class=null) { super(X,Y); health = 1; _flashPoint = new Point(); _flashRect = new Rectangle(); _flashRect2 = new Rectangle(); _flashPointZero = new Point(); offset = new FlxPoint(); origin = new FlxPoint(); scale = new FlxPoint(1.0,1.0); _alpha = 1; _color = 0x00ffffff; blend = null; antialiasing = false; cameras = null; finished = false; _facing = RIGHT; _animations = new Array(); _flipped = 0; _curAnim = null; _curFrame = 0; _curIndex = 0; _frameTimer = 0; _matrix = new Matrix(); _callback = null; if(SimpleGraphic == null) SimpleGraphic = ImgDefault; loadGraphic(SimpleGraphic); } /** * Clean up memory. */ override public function destroy():void { if(_animations != null) { var a:FlxAnim; var i:uint = 0; var l:uint = _animations.length; while(i < l) { a = _animations[i++]; if(a != null) a.destroy(); } _animations = null; } _flashPoint = null; _flashRect = null; _flashRect2 = null; _flashPointZero = null; offset = null; origin = null; scale = null; _curAnim = null; _matrix = null; _callback = null; framePixels = null; } /** * Load an image from an embedded graphic file. * * @param Graphic The image you want to use. * @param Animated Whether the Graphic parameter is a single sprite or a row of sprites. * @param Reverse Whether you need this class to generate horizontally flipped versions of the animation frames. * @param Width Optional, specify the width of your sprite (helps FlxSprite figure out what to do with non-square sprites or sprite sheets). * @param Height Optional, specify the height of your sprite (helps FlxSprite figure out what to do with non-square sprites or sprite sheets). * @param Unique Optional, whether the graphic should be a unique instance in the graphics cache. Default is false. * * @return This FlxSprite instance (nice for chaining stuff together, if you're into that). */ public function loadGraphic(Graphic:Class,Animated:Boolean=false,Reverse:Boolean=false,Width:uint=0,Height:uint=0,Unique:Boolean=false):FlxSprite { _bakedRotation = 0; _pixels = FlxG.addBitmap(Graphic,Reverse,Unique); if(Reverse) _flipped = _pixels.width>>1; else _flipped = 0; if(Width == 0) { if(Animated) Width = _pixels.height; else if(_flipped > 0) Width = _pixels.width*0.5; else Width = _pixels.width; } width = frameWidth = Width; if(Height == 0) { if(Animated) Height = width; else Height = _pixels.height; } height = frameHeight = Height; resetHelpers(); return this; } /** * Create a pre-rotated sprite sheet from a simple sprite. * This can make a huge difference in graphical performance! * * @param Graphic The image you want to rotate and stamp. * @param Rotations The number of rotation frames the final sprite should have. For small sprites this can be quite a large number (360 even) without any problems. * @param Frame If the Graphic has a single row of square animation frames on it, you can specify which of the frames you want to use here. Default is -1, or "use whole graphic." * @param AntiAliasing Whether to use high quality rotations when creating the graphic. Default is false. * @param AutoBuffer Whether to automatically increase the image size to accomodate rotated corners. Default is false. Will create frames that are 150% larger on each axis than the original frame or graphic. * * @return This FlxSprite instance (nice for chaining stuff together, if you're into that). */ public function loadRotatedGraphic(Graphic:Class, Rotations:uint=16, Frame:int=-1, AntiAliasing:Boolean=false, AutoBuffer:Boolean=false):FlxSprite { //Create the brush and canvas var rows:uint = Math.sqrt(Rotations); var brush:BitmapData = FlxG.addBitmap(Graphic); if(Frame >= 0) { //Using just a segment of the graphic - find the right bit here var full:BitmapData = brush; brush = new BitmapData(full.height,full.height); var rx:uint = Frame*brush.width; var ry:uint = 0; var fw:uint = full.width; if(rx >= fw) { ry = uint(rx/fw)*brush.height; rx %= fw; } _flashRect.x = rx; _flashRect.y = ry; _flashRect.width = brush.width; _flashRect.height = brush.height; brush.copyPixels(full,_flashRect,_flashPointZero); } var max:uint = brush.width; if(brush.height > max) max = brush.height; if(AutoBuffer) max *= 1.5; var columns:uint = FlxU.ceil(Rotations/rows); width = max*columns; height = max*rows; var key:String = String(Graphic) + ":" + Frame + ":" + width + "x" + height; var skipGen:Boolean = FlxG.checkBitmapCache(key); _pixels = FlxG.createBitmap(width, height, 0, true, key); width = frameWidth = _pixels.width; height = frameHeight = _pixels.height; _bakedRotation = 360/Rotations; //Generate a new sheet if necessary, then fix up the width and height if(!skipGen) { var row:uint = 0; var column:uint; var bakedAngle:Number = 0; var halfBrushWidth:uint = brush.width*0.5; var halfBrushHeight:uint = brush.height*0.5; var midpointX:uint = max*0.5; var midpointY:uint = max*0.5; while(row < rows) { column = 0; while(column < columns) { _matrix.identity(); _matrix.translate(-halfBrushWidth,-halfBrushHeight); _matrix.rotate(bakedAngle*0.017453293); _matrix.translate(max*column+midpointX, midpointY); bakedAngle += _bakedRotation; _pixels.draw(brush,_matrix,null,null,null,AntiAliasing); column++; } midpointY += max; row++; } } frameWidth = frameHeight = width = height = max; resetHelpers(); if(AutoBuffer) { width = brush.width; height = brush.height; centerOffsets(); } return this; } /** * This function creates a flat colored square image dynamically. * * @param Width The width of the sprite you want to generate. * @param Height The height of the sprite you want to generate. * @param Color Specifies the color of the generated block. * @param Unique Whether the graphic should be a unique instance in the graphics cache. Default is false. * @param Key Optional parameter - specify a string key to identify this graphic in the cache. Trumps Unique flag. * * @return This FlxSprite instance (nice for chaining stuff together, if you're into that). */ public function makeGraphic(Width:uint,Height:uint,Color:uint=0xffffffff,Unique:Boolean=false,Key:String=null):FlxSprite { _bakedRotation = 0; _pixels = FlxG.createBitmap(Width,Height,Color,Unique,Key); width = frameWidth = _pixels.width; height = frameHeight = _pixels.height; resetHelpers(); return this; } /** * Resets some important variables for sprite optimization and rendering. */ protected function resetHelpers():void { _flashRect.x = 0; _flashRect.y = 0; _flashRect.width = frameWidth; _flashRect.height = frameHeight; _flashRect2.x = 0; _flashRect2.y = 0; _flashRect2.width = _pixels.width; _flashRect2.height = _pixels.height; if((framePixels == null) || (framePixels.width != width) || (framePixels.height != height)) framePixels = new BitmapData(width,height); origin.make(frameWidth*0.5,frameHeight*0.5); framePixels.copyPixels(_pixels,_flashRect,_flashPointZero); frames = (_flashRect2.width / _flashRect.width) * (_flashRect2.height / _flashRect.height); if(_colorTransform != null) framePixels.colorTransform(_flashRect,_colorTransform); _curIndex = 0; } /** * Automatically called after update() by the game loop, * this function just calls updateAnimation(). */ override public function postUpdate():void { super.postUpdate(); updateAnimation(); } /** * Called by game loop, updates then blits or renders current frame of animation to the screen */ override public function draw():void { if(_flickerTimer != 0) { _flicker = !_flicker; if(_flicker) return; } if(dirty) //rarely calcFrame(); if(cameras == null) cameras = FlxG.cameras; var camera:FlxCamera; var i:uint = 0; var l:uint = cameras.length; while(i < l) { camera = cameras[i++]; if(!onScreen(camera)) continue; _point.x = x - int(camera.scroll.x*scrollFactor.x) - offset.x; _point.y = y - int(camera.scroll.y*scrollFactor.y) - offset.y; _point.x += (_point.x > 0)?0.0000001:-0.0000001; _point.y += (_point.y > 0)?0.0000001:-0.0000001; if(((angle == 0) || (_bakedRotation > 0)) && (scale.x == 1) && (scale.y == 1) && (blend == null)) { //Simple render _flashPoint.x = _point.x; _flashPoint.y = _point.y; camera.buffer.copyPixels(framePixels,_flashRect,_flashPoint,null,null,true); } else { //Advanced render _matrix.identity(); _matrix.translate(-origin.x,-origin.y); _matrix.scale(scale.x,scale.y); if((angle != 0) && (_bakedRotation <= 0)) _matrix.rotate(angle * 0.017453293); _matrix.translate(_point.x+origin.x,_point.y+origin.y); camera.buffer.draw(framePixels,_matrix,null,blend,null,antialiasing); } _VISIBLECOUNT++; if(FlxG.visualDebug && !ignoreDrawDebug) drawDebug(camera); } } /** * This function draws or stamps one <code>FlxSprite</code> onto another. * This function is NOT intended to replace <code>draw()</code>! * * @param Brush The image you want to use as a brush or stamp or pen or whatever. * @param X The X coordinate of the brush's top left corner on this sprite. * @param Y They Y coordinate of the brush's top left corner on this sprite. */ public function stamp(Brush:FlxSprite,X:int=0,Y:int=0):void { Brush.drawFrame(); var bitmapData:BitmapData = Brush.framePixels; //Simple draw if(((Brush.angle == 0) || (Brush._bakedRotation > 0)) && (Brush.scale.x == 1) && (Brush.scale.y == 1) && (Brush.blend == null)) { _flashPoint.x = X; _flashPoint.y = Y; _flashRect2.width = bitmapData.width; _flashRect2.height = bitmapData.height; _pixels.copyPixels(bitmapData,_flashRect2,_flashPoint,null,null,true); _flashRect2.width = _pixels.width; _flashRect2.height = _pixels.height; calcFrame(); return; } //Advanced draw _matrix.identity(); _matrix.translate(-Brush.origin.x,-Brush.origin.y); _matrix.scale(Brush.scale.x,Brush.scale.y); if(Brush.angle != 0) _matrix.rotate(Brush.angle * 0.017453293); _matrix.translate(X+Brush.origin.x,Y+Brush.origin.y); _pixels.draw(bitmapData,_matrix,null,Brush.blend,null,Brush.antialiasing); calcFrame(); } /** * This function draws a line on this sprite from position X1,Y1 * to position X2,Y2 with the specified color. * * @param StartX X coordinate of the line's start point. * @param StartY Y coordinate of the line's start point. * @param EndX X coordinate of the line's end point. * @param EndY Y coordinate of the line's end point. * @param Color The line's color. * @param Thickness How thick the line is in pixels (default value is 1). */ public function drawLine(StartX:Number,StartY:Number,EndX:Number,EndY:Number,Color:uint,Thickness:uint=1):void { //Draw line var gfx:Graphics = FlxG.flashGfx; gfx.clear(); gfx.moveTo(StartX,StartY); var alphaComponent:Number = Number((Color >> 24) & 0xFF) / 255; if(alphaComponent <= 0) alphaComponent = 1; gfx.lineStyle(Thickness,Color,alphaComponent); gfx.lineTo(EndX,EndY); //Cache line to bitmap _pixels.draw(FlxG.flashGfxSprite); dirty = true; } /** * Fills this sprite's graphic with a specific color. * * @param Color The color with which to fill the graphic, format 0xAARRGGBB. */ public function fill(Color:uint):void { _pixels.fillRect(_flashRect2,Color); if(_pixels != framePixels) dirty = true; } /** * Internal function for updating the sprite's animation. * Useful for cases when you need to update this but are buried down in too many supers. * This function is called automatically by <code>FlxSprite.postUpdate()</code>. */ protected function updateAnimation():void { if(_bakedRotation > 0) { var oldIndex:uint = _curIndex; var angleHelper:int = angle%360; if(angleHelper < 0) angleHelper += 360; _curIndex = angleHelper/_bakedRotation + 0.5; if(oldIndex != _curIndex) dirty = true; } else if((_curAnim != null) && (_curAnim.delay > 0) && (_curAnim.looped || !finished)) { _frameTimer += FlxG.elapsed; while(_frameTimer > _curAnim.delay) { _frameTimer = _frameTimer - _curAnim.delay; if(_curFrame == _curAnim.frames.length-1) { if(_curAnim.looped) _curFrame = 0; finished = true; } else _curFrame++; _curIndex = _curAnim.frames[_curFrame]; dirty = true; } } if(dirty) calcFrame(); } /** * Request (or force) that the sprite update the frame before rendering. * Useful if you are doing procedural generation or other weirdness! * * @param Force Force the frame to redraw, even if its not flagged as necessary. */ public function drawFrame(Force:Boolean=false):void { if(Force || dirty) calcFrame(); } /** * Adds a new animation to the sprite. * * @param Name What this animation should be called (e.g. "run"). * @param Frames An array of numbers indicating what frames to play in what order (e.g. 1, 2, 3). * @param FrameRate The speed in frames per second that the animation should play at (e.g. 40 fps). * @param Looped Whether or not the animation is looped or just plays once. */ public function addAnimation(Name:String, Frames:Array, FrameRate:Number=0, Looped:Boolean=true):void { _animations.push(new FlxAnim(Name,Frames,FrameRate,Looped)); } /** * Pass in a function to be called whenever this sprite's animation changes. * * @param AnimationCallback A function that has 3 parameters: a string name, a uint frame number, and a uint frame index. */ public function addAnimationCallback(AnimationCallback:Function):void { _callback = AnimationCallback; } /** * Plays an existing animation (e.g. "run"). * If you call an animation that is already playing it will be ignored. * * @param AnimName The string name of the animation you want to play. * @param Force Whether to force the animation to restart. */ public function play(AnimName:String,Force:Boolean=false):void { if(!Force && (_curAnim != null) && (AnimName == _curAnim.name) && (_curAnim.looped || !finished)) return; _curFrame = 0; _curIndex = 0; _frameTimer = 0; var i:uint = 0; var l:uint = _animations.length; while(i < l) { if(_animations[i].name == AnimName) { _curAnim = _animations[i]; if(_curAnim.delay <= 0) finished = true; else finished = false; _curIndex = _curAnim.frames[_curFrame]; dirty = true; return; } i++; } FlxG.log("WARNING: No animation called \""+AnimName+"\""); } /** * Tell the sprite to change to a random frame of animation * Useful for instantiating particles or other weird things. */ public function randomFrame():void { _curAnim = null; _curIndex = int(FlxG.random()*(_pixels.width/frameWidth)); dirty = true; } /** * Helper function that just sets origin to (0,0) */ public function setOriginToCorner():void { origin.x = origin.y = 0; } /** * Helper function that adjusts the offset automatically to center the bounding box within the graphic. * * @param AdjustPosition Adjusts the actual X and Y position just once to match the offset change. Default is false. */ public function centerOffsets(AdjustPosition:Boolean=false):void { offset.x = (frameWidth-width)*0.5; offset.y = (frameHeight-height)*0.5; if(AdjustPosition) { x += offset.x; y += offset.y; } } public function replaceColor(Color:uint,NewColor:uint,FetchPositions:Boolean=false):Array { var positions:Array = null; if(FetchPositions) positions = new Array(); var row:uint = 0; var column:uint; var rows:uint = _pixels.height; var columns:uint = _pixels.width; while(row < rows) { column = 0; while(column < columns) { if(_pixels.getPixel32(column,row) == Color) { _pixels.setPixel32(column,row,NewColor); if(FetchPositions) positions.push(new FlxPoint(column,row)); dirty = true; } column++; } row++; } return positions; } /** * Set <code>pixels</code> to any <code>BitmapData</code> object. * Automatically adjust graphic size and render helpers. */ public function get pixels():BitmapData { return _pixels; } /** * @private */ public function set pixels(Pixels:BitmapData):void { _pixels = Pixels; width = frameWidth = _pixels.width; height = frameHeight = _pixels.height; resetHelpers(); } /** * Set <code>facing</code> using <code>FlxSprite.LEFT</code>,<code>RIGHT</code>, * <code>UP</code>, and <code>DOWN</code> to take advantage of * flipped sprites and/or just track player orientation more easily. */ public function get facing():uint { return _facing; } /** * @private */ public function set facing(Direction:uint):void { if(_facing != Direction) dirty = true; _facing = Direction; } /** * Set <code>alpha</code> to a number between 0 and 1 to change the opacity of the sprite. */ public function get alpha():Number { return _alpha; } /** * @private */ public function set alpha(Alpha:Number):void { if(Alpha > 1) Alpha = 1; if(Alpha < 0) Alpha = 0; if(Alpha == _alpha) return; _alpha = Alpha; if((_alpha != 1) || (_color != 0x00ffffff)) _colorTransform = new ColorTransform((_color>>16)*0.00392,(_color>>8&0xff)*0.00392,(_color&0xff)*0.00392,_alpha); else _colorTransform = null; dirty = true; } /** * Set <code>color</code> to a number in this format: 0xRRGGBB. * <code>color</code> IGNORES ALPHA. To change the opacity use <code>alpha</code>. * Tints the whole sprite to be this color (similar to OpenGL vertex colors). */ public function get color():uint { return _color; } /** * @private */ public function set color(Color:uint):void { Color &= 0x00ffffff; if(_color == Color) return; _color = Color; if((_alpha != 1) || (_color != 0x00ffffff)) _colorTransform = new ColorTransform((_color>>16)*0.00392,(_color>>8&0xff)*0.00392,(_color&0xff)*0.00392,_alpha); else _colorTransform = null; dirty = true; } /** * Tell the sprite to change to a specific frame of animation. * * @param Frame The frame you want to display. */ public function get frame():uint { return _curIndex; } /** * @private */ public function set frame(Frame:uint):void { _curAnim = null; _curIndex = Frame; dirty = true; } /** * Check and see if this object is currently on screen. * Differs from <code>FlxObject</code>'s implementation * in that it takes the actual graphic into account, * not just the hitbox or bounding box or whatever. * * @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera. * * @return Whether the object is on screen or not. */ override public function onScreen(Camera:FlxCamera=null):Boolean { if(Camera == null) Camera = FlxG.camera; getScreenXY(_point,Camera); _point.x = _point.x - offset.x; _point.y = _point.y - offset.y; if(((angle == 0) || (_bakedRotation > 0)) && (scale.x == 1) && (scale.y == 1)) return ((_point.x + frameWidth > 0) && (_point.x < Camera.width) && (_point.y + frameHeight > 0) && (_point.y < Camera.height)); var halfWidth:Number = frameWidth/2; var halfHeight:Number = frameHeight/2; var absScaleX:Number = (scale.x>0)?scale.x:-scale.x; var absScaleY:Number = (scale.y>0)?scale.y:-scale.y; var radius:Number = Math.sqrt(halfWidth*halfWidth+halfHeight*halfHeight)*((absScaleX >= absScaleY)?absScaleX:absScaleY); _point.x += halfWidth; _point.y += halfHeight; return ((_point.x + radius > 0) && (_point.x - radius < Camera.width) && (_point.y + radius > 0) && (_point.y - radius < Camera.height)); } /** * Checks to see if a point in 2D world space overlaps this <code>FlxSprite</code> object's current displayed pixels. * This check is ALWAYS made in screen space, and always takes scroll factors into account. * * @param Point The point in world space you want to check. * @param Mask Used in the pixel hit test to determine what counts as solid. * @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera. * * @return Whether or not the point overlaps this object. */ public function pixelsOverlapPoint(Point:FlxPoint,Mask:uint=0xFF,Camera:FlxCamera=null):Boolean { if(Camera == null) Camera = FlxG.camera; getScreenXY(_point,Camera); _point.x = _point.x - offset.x; _point.y = _point.y - offset.y; _flashPoint.x = (Point.x - Camera.scroll.x) - _point.x; _flashPoint.y = (Point.y - Camera.scroll.y) - _point.y; return framePixels.hitTest(_flashPointZero,Mask,_flashPoint); } /** * Internal function to update the current animation frame. */ protected function calcFrame():void { var indexX:uint = _curIndex*frameWidth; var indexY:uint = 0; //Handle sprite sheets var widthHelper:uint = _flipped?_flipped:_pixels.width; if(indexX >= widthHelper) { indexY = uint(indexX/widthHelper)*frameHeight; indexX %= widthHelper; } //handle reversed sprites if(_flipped && (_facing == LEFT)) indexX = (_flipped<<1)-indexX-frameWidth; //Update display bitmap _flashRect.x = indexX; _flashRect.y = indexY; framePixels.copyPixels(_pixels,_flashRect,_flashPointZero); _flashRect.x = _flashRect.y = 0; if(_colorTransform != null) framePixels.colorTransform(_flashRect,_colorTransform); if(_callback != null) _callback(((_curAnim != null)?(_curAnim.name):null),_curFrame,_curIndex); dirty = false; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxSprite.as
ActionScript
gpl3
28,447
package org.flixel { import flash.events.NetStatusEvent; import flash.net.SharedObject; import flash.net.SharedObjectFlushStatus; /** * A class to help automate and simplify save game functionality. * Basicaly a wrapper for the Flash SharedObject thing, but * handles some annoying storage request stuff too. * * @author Adam Atomic */ public class FlxSave extends Object { static protected var SUCCESS:uint = 0; static protected var PENDING:uint = 1; static protected var ERROR:uint = 2; /** * Allows you to directly access the data container in the local shared object. * @default null */ public var data:Object; /** * The name of the local shared object. * @default null */ public var name:String; /** * The local shared object itself. * @default null */ protected var _sharedObject:SharedObject; /** * Internal tracker for callback function in case save takes too long. */ protected var _onComplete:Function; /** * Internal tracker for save object close request. */ protected var _closeRequested:Boolean; /** * Blanks out the containers. */ public function FlxSave() { destroy(); } /** * Clean up memory. */ public function destroy():void { _sharedObject = null; name = null; data = null; _onComplete = null; _closeRequested = false; } /** * Automatically creates or reconnects to locally saved data. * * @param Name The name of the object (should be the same each time to access old data). * * @return Whether or not you successfully connected to the save data. */ public function bind(Name:String):Boolean { destroy(); name = Name; try { _sharedObject = SharedObject.getLocal(name); } catch(e:Error) { FlxG.log("ERROR: There was a problem binding to\nthe shared object data from FlxSave."); destroy(); return false; } data = _sharedObject.data; return true; } /** * A way to safely call <code>flush()</code> and <code>destroy()</code> on your save file. * Will correctly handle storage size popups and all that good stuff. * If you don't want to save your changes first, just call <code>destroy()</code> instead. * * @param MinFileSize If you need X amount of space for your save, specify it here. * @param OnComplete This callback will be triggered when the data is written successfully. * * @return The result of result of the <code>flush()</code> call (see below for more details). */ public function close(MinFileSize:uint=0,OnComplete:Function=null):Boolean { _closeRequested = true; return flush(MinFileSize,OnComplete); } /** * Writes the local shared object to disk immediately. Leaves the object open in memory. * * @param MinFileSize If you need X amount of space for your save, specify it here. * @param OnComplete This callback will be triggered when the data is written successfully. * * @return Whether or not the data was written immediately. False could be an error OR a storage request popup. */ public function flush(MinFileSize:uint=0,OnComplete:Function=null):Boolean { if(!checkBinding()) return false; _onComplete = OnComplete; var result:String = null; try { result = _sharedObject.flush(MinFileSize); } catch (e:Error) { return onDone(ERROR); } if(result == SharedObjectFlushStatus.PENDING) _sharedObject.addEventListener(NetStatusEvent.NET_STATUS,onFlushStatus); return onDone((result == SharedObjectFlushStatus.FLUSHED)?SUCCESS:PENDING); } /** * Erases everything stored in the local shared object. * Data is immediately erased and the object is saved that way, * so use with caution! * * @return Returns false if the save object is not bound yet. */ public function erase():Boolean { if(!checkBinding()) return false; _sharedObject.clear(); return true; } /** * Event handler for special case storage requests. * * @param E Flash net status event. */ protected function onFlushStatus(E:NetStatusEvent):void { _sharedObject.removeEventListener(NetStatusEvent.NET_STATUS,onFlushStatus); onDone((E.info.code == "SharedObject.Flush.Success")?SUCCESS:ERROR); } /** * Event handler for special case storage requests. * Handles logging of errors and calling of callback. * * @param Result One of the result codes (PENDING, ERROR, or SUCCESS). * * @return Whether the operation was a success or not. */ protected function onDone(Result:uint):Boolean { switch(Result) { case PENDING: FlxG.log("FLIXEL: FlxSave is requesting extra storage space."); break; case ERROR: FlxG.log("ERROR: There was a problem flushing\nthe shared object data from FlxSave."); break; default: break; } if(_onComplete != null) _onComplete(Result == SUCCESS); if(_closeRequested) destroy(); return Result == SUCCESS; } /** * Handy utility function for checking and warning if the shared object is bound yet or not. * * @return Whether the shared object was bound yet. */ protected function checkBinding():Boolean { if(_sharedObject == null) { FlxG.log("FLIXEL: You must call FlxSave.bind()\nbefore you can read or write data."); return false; } return true; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxSave.as
ActionScript
gpl3
5,407
package org.flixel { /** * <code>FlxEmitter</code> is a lightweight particle emitter. * It can be used for one-time explosions or for * continuous fx like rain and fire. <code>FlxEmitter</code> * is not optimized or anything; all it does is launch * <code>FlxParticle</code> objects out at set intervals * by setting their positions and velocities accordingly. * It is easy to use and relatively efficient, * relying on <code>FlxGroup</code>'s RECYCLE POWERS. * * @author Adam Atomic */ public class FlxEmitter extends FlxGroup { /** * The X position of the top left corner of the emitter in world space. */ public var x:Number; /** * The Y position of the top left corner of emitter in world space. */ public var y:Number; /** * The width of the emitter. Particles can be randomly generated from anywhere within this box. */ public var width:Number; /** * The height of the emitter. Particles can be randomly generated from anywhere within this box. */ public var height:Number; /** * The minimum possible velocity of a particle. * The default value is (-100,-100). */ public var minParticleSpeed:FlxPoint; /** * The maximum possible velocity of a particle. * The default value is (100,100). */ public var maxParticleSpeed:FlxPoint; /** * The X and Y drag component of particles launched from the emitter. */ public var particleDrag:FlxPoint; /** * The minimum possible angular velocity of a particle. The default value is -360. * NOTE: rotating particles are more expensive to draw than non-rotating ones! */ public var minRotation:Number; /** * The maximum possible angular velocity of a particle. The default value is 360. * NOTE: rotating particles are more expensive to draw than non-rotating ones! */ public var maxRotation:Number; /** * Sets the <code>acceleration.y</code> member of each particle to this value on launch. */ public var gravity:Number; /** * Determines whether the emitter is currently emitting particles. * It is totally safe to directly toggle this. */ public var on:Boolean; /** * How often a particle is emitted (if emitter is started with Explode == false). */ public var frequency:Number; /** * How long each particle lives once it is emitted. * Set lifespan to 'zero' for particles to live forever. */ public var lifespan:Number; /** * How much each particle should bounce. 1 = full bounce, 0 = no bounce. */ public var bounce:Number; /** * Set your own particle class type here. * Default is <code>FlxParticle</code>. */ public var particleClass:Class; /** * Internal helper for deciding how many particles to launch. */ protected var _quantity:uint; /** * Internal helper for the style of particle emission (all at once, or one at a time). */ protected var _explode:Boolean; /** * Internal helper for deciding when to launch particles or kill them. */ protected var _timer:Number; /** * Internal counter for figuring out how many particles to launch. */ protected var _counter:uint; /** * Internal point object, handy for reusing for memory mgmt purposes. */ protected var _point:FlxPoint; /** * Creates a new <code>FlxEmitter</code> object at a specific position. * Does NOT automatically generate or attach particles! * * @param X The X position of the emitter. * @param Y The Y position of the emitter. * @param Size Optional, specifies a maximum capacity for this emitter. */ public function FlxEmitter(X:Number=0, Y:Number=0, Size:Number=0) { super(Size); x = X; y = Y; width = 0; height = 0; minParticleSpeed = new FlxPoint(-100,-100); maxParticleSpeed = new FlxPoint(100,100); minRotation = -360; maxRotation = 360; gravity = 0; particleClass = null; particleDrag = new FlxPoint(); frequency = 0.1; lifespan = 3; bounce = 0; _quantity = 0; _counter = 0; _explode = true; on = false; _point = new FlxPoint(); } /** * Clean up memory. */ override public function destroy():void { minParticleSpeed = null; maxParticleSpeed = null; particleDrag = null; particleClass = null; _point = null; super.destroy(); } /** * This function generates a new array of particle sprites to attach to the emitter. * * @param Graphics If you opted to not pre-configure an array of FlxSprite objects, you can simply pass in a particle image or sprite sheet. * @param Quantity The number of particles to generate when using the "create from image" option. * @param BakedRotations How many frames of baked rotation to use (boosts performance). Set to zero to not use baked rotations. * @param Multiple Whether the image in the Graphics param is a single particle or a bunch of particles (if it's a bunch, they need to be square!). * @param Collide Whether the particles should be flagged as not 'dead' (non-colliding particles are higher performance). 0 means no collisions, 0-1 controls scale of particle's bounding box. * * @return This FlxEmitter instance (nice for chaining stuff together, if you're into that). */ public function makeParticles(Graphics:Class, Quantity:uint=50, BakedRotations:uint=16, Multiple:Boolean=false, Collide:Number=0.8):FlxEmitter { maxSize = Quantity; var totalFrames:uint = 1; if(Multiple) { var sprite:FlxSprite = new FlxSprite(); sprite.loadGraphic(Graphics,true); totalFrames = sprite.frames; sprite.destroy(); } var randomFrame:uint; var particle:FlxParticle; var i:uint = 0; while(i < Quantity) { if(particleClass == null) particle = new FlxParticle(); else particle = new particleClass(); if(Multiple) { randomFrame = FlxG.random()*totalFrames; if(BakedRotations > 0) particle.loadRotatedGraphic(Graphics,BakedRotations,randomFrame); else { particle.loadGraphic(Graphics,true); particle.frame = randomFrame; } } else { if(BakedRotations > 0) particle.loadRotatedGraphic(Graphics,BakedRotations); else particle.loadGraphic(Graphics); } if(Collide > 0) { particle.width *= Collide; particle.height *= Collide; particle.centerOffsets(); } else particle.allowCollisions = FlxObject.NONE; particle.exists = false; add(particle); i++; } return this; } /** * Called automatically by the game loop, decides when to launch particles and when to "die". */ override public function update():void { if(on) { if(_explode) { on = false; var i:uint = 0; var l:uint = _quantity; if((l <= 0) || (l > length)) l = length; while(i < l) { emitParticle(); i++; } _quantity = 0; } else { _timer += FlxG.elapsed; while((frequency > 0) && (_timer > frequency) && on) { _timer -= frequency; emitParticle(); if((_quantity > 0) && (++_counter >= _quantity)) { on = false; _quantity = 0; } } } } super.update(); } /** * Call this function to turn off all the particles and the emitter. */ override public function kill():void { on = false; super.kill(); } /** * Call this function to start emitting particles. * * @param Explode Whether the particles should all burst out at once. * @param Lifespan How long each particle lives once emitted. 0 = forever. * @param Frequency Ignored if Explode is set to true. Frequency is how often to emit a particle. 0 = never emit, 0.1 = 1 particle every 0.1 seconds, 5 = 1 particle every 5 seconds. * @param Quantity How many particles to launch. 0 = "all of the particles". */ public function start(Explode:Boolean=true,Lifespan:Number=0,Frequency:Number=0.1,Quantity:uint=0):void { revive(); visible = true; on = true; _explode = Explode; lifespan = Lifespan; frequency = Frequency; _quantity += Quantity; _counter = 0; _timer = 0; } /** * This function can be used both internally and externally to emit the next particle. */ public function emitParticle():void { var particle:FlxParticle = recycle(FlxParticle) as FlxParticle; particle.lifespan = lifespan; particle.elasticity = bounce; particle.reset(x - (particle.width>>1) + FlxG.random()*width, y - (particle.height>>1) + FlxG.random()*height); particle.visible = true; if(minParticleSpeed.x != maxParticleSpeed.x) particle.velocity.x = minParticleSpeed.x + FlxG.random()*(maxParticleSpeed.x-minParticleSpeed.x); else particle.velocity.x = minParticleSpeed.x; if(minParticleSpeed.y != maxParticleSpeed.y) particle.velocity.y = minParticleSpeed.y + FlxG.random()*(maxParticleSpeed.y-minParticleSpeed.y); else particle.velocity.y = minParticleSpeed.y; particle.acceleration.y = gravity; if(minRotation != maxRotation) particle.angularVelocity = minRotation + FlxG.random()*(maxRotation-minRotation); else particle.angularVelocity = minRotation; if(particle.angularVelocity != 0) particle.angle = FlxG.random()*360-180; particle.drag.x = particleDrag.x; particle.drag.y = particleDrag.y; particle.onEmit(); } /** * A more compact way of setting the width and height of the emitter. * * @param Width The desired width of the emitter (particles are spawned randomly within these dimensions). * @param Height The desired height of the emitter. */ public function setSize(Width:uint,Height:uint):void { width = Width; height = Height; } /** * A more compact way of setting the X velocity range of the emitter. * * @param Min The minimum value for this range. * @param Max The maximum value for this range. */ public function setXSpeed(Min:Number=0,Max:Number=0):void { minParticleSpeed.x = Min; maxParticleSpeed.x = Max; } /** * A more compact way of setting the Y velocity range of the emitter. * * @param Min The minimum value for this range. * @param Max The maximum value for this range. */ public function setYSpeed(Min:Number=0,Max:Number=0):void { minParticleSpeed.y = Min; maxParticleSpeed.y = Max; } /** * A more compact way of setting the angular velocity constraints of the emitter. * * @param Min The minimum value for this range. * @param Max The maximum value for this range. */ public function setRotation(Min:Number=0,Max:Number=0):void { minRotation = Min; maxRotation = Max; } /** * Change the emitter's midpoint to match the midpoint of a <code>FlxObject</code>. * * @param Object The <code>FlxObject</code> that you want to sync up with. */ public function at(Object:FlxObject):void { Object.getMidpoint(_point); x = _point.x - (width>>1); y = _point.y - (height>>1); } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxEmitter.as
ActionScript
gpl3
11,101
package org.flixel { /** * This is an organizational class that can update and render a bunch of <code>FlxBasic</code>s. * NOTE: Although <code>FlxGroup</code> extends <code>FlxBasic</code>, it will not automatically * add itself to the global collisions quad tree, it will only add its members. * * @author Adam Atomic */ public class FlxGroup extends FlxBasic { /** * Use with <code>sort()</code> to sort in ascending order. */ static public const ASCENDING:int = -1; /** * Use with <code>sort()</code> to sort in descending order. */ static public const DESCENDING:int = 1; /** * Array of all the <code>FlxBasic</code>s that exist in this group. */ public var members:Array; /** * The number of entries in the members array. * For performance and safety you should check this variable * instead of members.length unless you really know what you're doing! */ public var length:Number; /** * Internal tracker for the maximum capacity of the group. * Default is 0, or no max capacity. */ protected var _maxSize:uint; /** * Internal helper variable for recycling objects a la <code>FlxEmitter</code>. */ protected var _marker:uint; /** * Helper for sort. */ protected var _sortIndex:String; /** * Helper for sort. */ protected var _sortOrder:int; /** * Constructor */ public function FlxGroup(MaxSize:uint=0) { super(); members = new Array(); length = 0; _maxSize = MaxSize; _marker = 0; _sortIndex = null; } /** * Override this function to handle any deleting or "shutdown" type operations you might need, * such as removing traditional Flash children like Sprite objects. */ override public function destroy():void { if(members != null) { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if(basic != null) basic.destroy(); } members.length = 0; members = null; } _sortIndex = null; } /** * Just making sure we don't increment the active objects count. */ override public function preUpdate():void { } /** * Automatically goes through and calls update on everything you added. */ override public function update():void { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if((basic != null) && basic.exists && basic.active) { basic.preUpdate(); basic.update(); basic.postUpdate(); } } } /** * Automatically goes through and calls render on everything you added. */ override public function draw():void { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if((basic != null) && basic.exists && basic.visible) basic.draw(); } } /** * The maximum capacity of this group. Default is 0, meaning no max capacity, and the group can just grow. */ public function get maxSize():uint { return _maxSize; } /** * @private */ public function set maxSize(Size:uint):void { _maxSize = Size; if(_marker >= _maxSize) _marker = 0; if((_maxSize == 0) || (members == null) || (_maxSize >= members.length)) return; //If the max size has shrunk, we need to get rid of some objects var basic:FlxBasic; var i:uint = _maxSize; var l:uint = members.length; while(i < l) { basic = members[i++] as FlxBasic; if(basic != null) basic.destroy(); } length = members.length = _maxSize; } /** * Adds a new <code>FlxBasic</code> subclass (FlxBasic, FlxSprite, Enemy, etc) to the group. * FlxGroup will try to replace a null member of the array first. * Failing that, FlxGroup will add it to the end of the member array, * assuming there is room for it, and doubling the size of the array if necessary. * * <p>WARNING: If the group has a maxSize that has already been met, * the object will NOT be added to the group!</p> * * @param Object The object you want to add to the group. * * @return The same <code>FlxBasic</code> object that was passed in. */ public function add(Object:FlxBasic):FlxBasic { //Don't bother adding an object twice. if(members.indexOf(Object) >= 0) return Object; //First, look for a null entry where we can add the object. var i:uint = 0; var l:uint = members.length; while(i < l) { if(members[i] == null) { members[i] = Object; if(i >= length) length = i+1; return Object; } i++; } //Failing that, expand the array (if we can) and add the object. if(_maxSize > 0) { if(members.length >= _maxSize) return Object; else if(members.length * 2 <= _maxSize) members.length *= 2; else members.length = _maxSize; } else members.length *= 2; //If we made it this far, then we successfully grew the group, //and we can go ahead and add the object at the first open slot. members[i] = Object; length = i+1; return Object; } /** * Recycling is designed to help you reuse game objects without always re-allocating or "newing" them. * * <p>If you specified a maximum size for this group (like in FlxEmitter), * then recycle will employ what we're calling "rotating" recycling. * Recycle() will first check to see if the group is at capacity yet. * If group is not yet at capacity, recycle() returns a new object. * If the group IS at capacity, then recycle() just returns the next object in line.</p> * * <p>If you did NOT specify a maximum size for this group, * then recycle() will employ what we're calling "grow-style" recycling. * Recycle() will return either the first object with exists == false, * or, finding none, add a new object to the array, * doubling the size of the array if necessary.</p> * * <p>WARNING: If this function needs to create a new object, * and no object class was provided, it will return null * instead of a valid object!</p> * * @param ObjectClass The class type you want to recycle (e.g. FlxSprite, EvilRobot, etc). Do NOT "new" the class in the parameter! * * @return A reference to the object that was created. Don't forget to cast it back to the Class you want (e.g. myObject = myGroup.recycle(myObjectClass) as myObjectClass;). */ public function recycle(ObjectClass:Class=null):FlxBasic { var basic:FlxBasic; if(_maxSize > 0) { if(length < _maxSize) { if(ObjectClass == null) return null; return add(new ObjectClass() as FlxBasic); } else { basic = members[_marker++]; if(_marker >= _maxSize) _marker = 0; return basic; } } else { basic = getFirstAvailable(ObjectClass); if(basic != null) return basic; if(ObjectClass == null) return null; return add(new ObjectClass() as FlxBasic); } } /** * Removes an object from the group. * * @param Object The <code>FlxBasic</code> you want to remove. * @param Splice Whether the object should be cut from the array entirely or not. * * @return The removed object. */ public function remove(Object:FlxBasic,Splice:Boolean=false):FlxBasic { var index:int = members.indexOf(Object); if((index < 0) || (index >= members.length)) return null; if(Splice) { members.splice(index,1); length--; } else members[index] = null; return Object; } /** * Replaces an existing <code>FlxBasic</code> with a new one. * * @param OldObject The object you want to replace. * @param NewObject The new object you want to use instead. * * @return The new object. */ public function replace(OldObject:FlxBasic,NewObject:FlxBasic):FlxBasic { var index:int = members.indexOf(OldObject); if((index < 0) || (index >= members.length)) return null; members[index] = NewObject; return NewObject; } /** * Call this function to sort the group according to a particular value and order. * For example, to sort game objects for Zelda-style overlaps you might call * <code>myGroup.sort("y",ASCENDING)</code> at the bottom of your * <code>FlxState.update()</code> override. To sort all existing objects after * a big explosion or bomb attack, you might call <code>myGroup.sort("exists",DESCENDING)</code>. * * @param Index The <code>String</code> name of the member variable you want to sort on. Default value is "y". * @param Order A <code>FlxGroup</code> constant that defines the sort order. Possible values are <code>ASCENDING</code> and <code>DESCENDING</code>. Default value is <code>ASCENDING</code>. */ public function sort(Index:String="y",Order:int=ASCENDING):void { _sortIndex = Index; _sortOrder = Order; members.sort(sortHandler); } /** * Go through and set the specified variable to the specified value on all members of the group. * * @param VariableName The string representation of the variable name you want to modify, for example "visible" or "scrollFactor". * @param Value The value you want to assign to that variable. * @param Recurse Default value is true, meaning if <code>setAll()</code> encounters a member that is a group, it will call <code>setAll()</code> on that group rather than modifying its variable. */ public function setAll(VariableName:String,Value:Object,Recurse:Boolean=true):void { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if(basic != null) { if(Recurse && (basic is FlxGroup)) (basic as FlxGroup).setAll(VariableName,Value,Recurse); else basic[VariableName] = Value; } } } /** * Go through and call the specified function on all members of the group. * Currently only works on functions that have no required parameters. * * @param FunctionName The string representation of the function you want to call on each object, for example "kill()" or "init()". * @param Recurse Default value is true, meaning if <code>callAll()</code> encounters a member that is a group, it will call <code>callAll()</code> on that group rather than calling the group's function. */ public function callAll(FunctionName:String,Recurse:Boolean=true):void { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if(basic != null) { if(Recurse && (basic is FlxGroup)) (basic as FlxGroup).callAll(FunctionName,Recurse); else basic[FunctionName](); } } } /** * Call this function to retrieve the first object with exists == false in the group. * This is handy for recycling in general, e.g. respawning enemies. * * @param ObjectClass An optional parameter that lets you narrow the results to instances of this particular class. * * @return A <code>FlxBasic</code> currently flagged as not existing. */ public function getFirstAvailable(ObjectClass:Class=null):FlxBasic { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if((basic != null) && !basic.exists && ((ObjectClass == null) || (basic is ObjectClass))) return basic; } return null; } /** * Call this function to retrieve the first index set to 'null'. * Returns -1 if no index stores a null object. * * @return An <code>int</code> indicating the first null slot in the group. */ public function getFirstNull():int { var basic:FlxBasic; var i:uint = 0; var l:uint = members.length; while(i < l) { if(members[i] == null) return i; else i++; } return -1; } /** * Call this function to retrieve the first object with exists == true in the group. * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. * * @return A <code>FlxBasic</code> currently flagged as existing. */ public function getFirstExtant():FlxBasic { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if((basic != null) && basic.exists) return basic; } return null; } /** * Call this function to retrieve the first object with dead == false in the group. * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. * * @return A <code>FlxBasic</code> currently flagged as not dead. */ public function getFirstAlive():FlxBasic { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if((basic != null) && basic.exists && basic.alive) return basic; } return null; } /** * Call this function to retrieve the first object with dead == true in the group. * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. * * @return A <code>FlxBasic</code> currently flagged as dead. */ public function getFirstDead():FlxBasic { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if((basic != null) && !basic.alive) return basic; } return null; } /** * Call this function to find out how many members of the group are not dead. * * @return The number of <code>FlxBasic</code>s flagged as not dead. Returns -1 if group is empty. */ public function countLiving():int { var count:int = -1; var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if(basic != null) { if(count < 0) count = 0; if(basic.exists && basic.alive) count++; } } return count; } /** * Call this function to find out how many members of the group are dead. * * @return The number of <code>FlxBasic</code>s flagged as dead. Returns -1 if group is empty. */ public function countDead():int { var count:int = -1; var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if(basic != null) { if(count < 0) count = 0; if(!basic.alive) count++; } } return count; } /** * Returns a member at random from the group. * * @param StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. * @param Length Optional restriction on the number of values you want to randomly select from. * * @return A <code>FlxBasic</code> from the members list. */ public function getRandom(StartIndex:uint=0,Length:uint=0):FlxBasic { if(Length == 0) Length = length; return FlxG.getRandom(members,StartIndex,Length) as FlxBasic; } /** * Remove all instances of <code>FlxBasic</code> subclass (FlxSprite, FlxBlock, etc) from the list. * WARNING: does not destroy() or kill() any of these objects! */ public function clear():void { length = members.length = 0; } /** * Calls kill on the group's members and then on the group itself. */ override public function kill():void { var basic:FlxBasic; var i:uint = 0; while(i < length) { basic = members[i++] as FlxBasic; if((basic != null) && basic.exists) basic.kill(); } super.kill(); } /** * Helper function for the sort process. * * @param Obj1 The first object being sorted. * @param Obj2 The second object being sorted. * * @return An integer value: -1 (Obj1 before Obj2), 0 (same), or 1 (Obj1 after Obj2). */ protected function sortHandler(Obj1:FlxBasic,Obj2:FlxBasic):int { if(Obj1[_sortIndex] < Obj2[_sortIndex]) return _sortOrder; else if(Obj1[_sortIndex] > Obj2[_sortIndex]) return -_sortOrder; return 0; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxGroup.as
ActionScript
gpl3
16,015
package org.flixel { import org.flixel.plugin.TimerManager; /** * A simple timer class, leveraging the new plugins system. * Can be used with callbacks or by polling the <code>finished</code> flag. * Not intended to be added to a game state or group; the timer manager * is responsible for actually calling update(), not the user. * * @author Adam Atomic */ public class FlxTimer { /** * How much time the timer was set for. */ public var time:Number; /** * How many loops the timer was set for. */ public var loops:uint; /** * Pauses or checks the pause state of the timer. */ public var paused:Boolean; /** * Check to see if the timer is finished. */ public var finished:Boolean; /** * Internal tracker for the time's-up callback function. * Callback should be formed "onTimer(Timer:FlxTimer);" */ protected var _callback:Function; /** * Internal tracker for the actual timer counting up. */ protected var _timeCounter:Number; /** * Internal tracker for the loops counting up. */ protected var _loopsCounter:uint; /** * Instantiate the timer. Does not set or start the timer. */ public function FlxTimer() { time = 0; loops = 0; _callback = null; _timeCounter = 0; _loopsCounter = 0; paused = false; finished = false; } /** * Clean up memory. */ public function destroy():void { stop(); _callback = null; } /** * Called by the timer manager plugin to update the timer. * If time runs out, the loop counter is advanced, the timer reset, and the callback called if it exists. * If the timer runs out of loops, then the timer calls <code>stop()</code>. * However, callbacks are called AFTER <code>stop()</code> is called. */ public function update():void { _timeCounter += FlxG.elapsed; while((_timeCounter >= time) && !paused && !finished) { _timeCounter -= time; _loopsCounter++; if((loops > 0) && (_loopsCounter >= loops)) stop(); if(_callback != null) _callback(this); } } /** * Starts or resumes the timer. If this timer was paused, * then all the parameters are ignored, and the timer is resumed. * Adds the timer to the timer manager. * * @param Time How many seconds it takes for the timer to go off. * @param Loops How many times the timer should go off. Default is 1, or "just count down once." * @param Callback Optional, triggered whenever the time runs out, once for each loop. Callback should be formed "onTimer(Timer:FlxTimer);" * * @return A reference to itself (handy for chaining or whatever). */ public function start(Time:Number=1,Loops:uint=1,Callback:Function=null):FlxTimer { var timerManager:TimerManager = manager; if(timerManager != null) timerManager.add(this); if(paused) { paused = false; return this; } paused = false; finished = false; time = Time; loops = Loops; _callback = Callback; _timeCounter = 0; _loopsCounter = 0; return this; } /** * Stops the timer and removes it from the timer manager. */ public function stop():void { finished = true; var timerManager:TimerManager = manager; if(timerManager != null) timerManager.remove(this); } /** * Read-only: check how much time is left on the timer. */ public function get timeLeft():Number { return time-_timeCounter; } /** * Read-only: check how many loops are left on the timer. */ public function get loopsLeft():int { return loops-_loopsCounter; } /** * Read-only: how far along the timer is, on a scale of 0.0 to 1.0. */ public function get progress():Number { if(time > 0) return _timeCounter/time; else return 0; } static public function get manager():TimerManager { return FlxG.getPlugin(TimerManager) as TimerManager; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxTimer.as
ActionScript
gpl3
3,971
package org.flixel { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; import flash.geom.ColorTransform; import flash.geom.Point; import flash.geom.Rectangle; /** * The camera class is used to display the game's visuals in the Flash player. * By default one camera is created automatically, that is the same size as the Flash player. * You can add more cameras or even replace the main camera using utilities in <code>FlxG</code>. * * @author Adam Atomic */ public class FlxCamera extends FlxBasic { /** * Camera "follow" style preset: camera has no deadzone, just tracks the focus object directly. */ static public const STYLE_LOCKON:uint = 0; /** * Camera "follow" style preset: camera deadzone is narrow but tall. */ static public const STYLE_PLATFORMER:uint = 1; /** * Camera "follow" style preset: camera deadzone is a medium-size square around the focus object. */ static public const STYLE_TOPDOWN:uint = 2; /** * Camera "follow" style preset: camera deadzone is a small square around the focus object. */ static public const STYLE_TOPDOWN_TIGHT:uint = 3; /** * Camera "shake" effect preset: shake camera on both the X and Y axes. */ static public const SHAKE_BOTH_AXES:uint = 0; /** * Camera "shake" effect preset: shake camera on the X axis only. */ static public const SHAKE_HORIZONTAL_ONLY:uint = 1; /** * Camera "shake" effect preset: shake camera on the Y axis only. */ static public const SHAKE_VERTICAL_ONLY:uint = 2; /** * While you can alter the zoom of each camera after the fact, * this variable determines what value the camera will start at when created. */ static public var defaultZoom:Number; /** * The X position of this camera's display. Zoom does NOT affect this number. * Measured in pixels from the left side of the flash window. */ public var x:Number; /** * The Y position of this camera's display. Zoom does NOT affect this number. * Measured in pixels from the top of the flash window. */ public var y:Number; /** * How wide the camera display is, in game pixels. */ public var width:uint; /** * How tall the camera display is, in game pixels. */ public var height:uint; /** * Tells the camera to follow this <code>FlxObject</code> object around. */ public var target:FlxObject; /** * You can assign a "dead zone" to the camera in order to better control its movement. * The camera will always keep the focus object inside the dead zone, * unless it is bumping up against the bounds rectangle's edges. * The deadzone's coordinates are measured from the camera's upper left corner in game pixels. * For rapid prototyping, you can use the preset deadzones (e.g. <code>STYLE_PLATFORMER</code>) with <code>follow()</code>. */ public var deadzone:FlxRect; /** * The edges of the camera's range, i.e. where to stop scrolling. * Measured in game pixels and world coordinates. */ public var bounds:FlxRect; /** * Stores the basic parallax scrolling values. */ public var scroll:FlxPoint; /** * The actual bitmap data of the camera display itself. */ public var buffer:BitmapData; /** * The natural background color of the camera. Defaults to FlxG.bgColor. * NOTE: can be transparent for crazy FX! */ public var bgColor:uint; /** * Sometimes it's easier to just work with a <code>FlxSprite</code> than it is to work * directly with the <code>BitmapData</code> buffer. This sprite reference will * allow you to do exactly that. */ public var screen:FlxSprite; /** * Indicates how far the camera is zoomed in. */ protected var _zoom:Number; /** * Internal, to help avoid costly allocations. */ protected var _point:FlxPoint; /** * Internal, help with color transforming the flash bitmap. */ protected var _color:uint; /** * Internal, used to render buffer to screen space. */ protected var _flashBitmap:Bitmap; /** * Internal, used to render buffer to screen space. */ internal var _flashSprite:Sprite; /** * Internal, used to render buffer to screen space. */ internal var _flashOffsetX:Number; /** * Internal, used to render buffer to screen space. */ internal var _flashOffsetY:Number; /** * Internal, used to render buffer to screen space. */ protected var _flashRect:Rectangle; /** * Internal, used to render buffer to screen space. */ protected var _flashPoint:Point; /** * Internal, used to control the "flash" special effect. */ protected var _fxFlashColor:uint; /** * Internal, used to control the "flash" special effect. */ protected var _fxFlashDuration:Number; /** * Internal, used to control the "flash" special effect. */ protected var _fxFlashComplete:Function; /** * Internal, used to control the "flash" special effect. */ protected var _fxFlashAlpha:Number; /** * Internal, used to control the "fade" special effect. */ protected var _fxFadeColor:uint; /** * Internal, used to control the "fade" special effect. */ protected var _fxFadeDuration:Number; /** * Internal, used to control the "fade" special effect. */ protected var _fxFadeComplete:Function; /** * Internal, used to control the "fade" special effect. */ protected var _fxFadeAlpha:Number; /** * Internal, used to control the "shake" special effect. */ protected var _fxShakeIntensity:Number; /** * Internal, used to control the "shake" special effect. */ protected var _fxShakeDuration:Number; /** * Internal, used to control the "shake" special effect. */ protected var _fxShakeComplete:Function; /** * Internal, used to control the "shake" special effect. */ protected var _fxShakeOffset:FlxPoint; /** * Internal, used to control the "shake" special effect. */ protected var _fxShakeDirection:uint; /** * Internal helper variable for doing better wipes/fills between renders. */ protected var _fill:BitmapData; /** * Instantiates a new camera at the specified location, with the specified size and zoom level. * * @param X X location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. * @param Y Y location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. * @param Width The width of the camera display in pixels. * @param Height The height of the camera display in pixels. * @param Zoom The initial zoom level of the camera. A zoom level of 2 will make all pixels display at 2x resolution. */ public function FlxCamera(X:int,Y:int,Width:int,Height:int,Zoom:Number=0) { x = X; y = Y; width = Width; height = Height; target = null; deadzone = null; scroll = new FlxPoint(); _point = new FlxPoint(); bounds = null; screen = new FlxSprite(); screen.makeGraphic(width,height,0,true); screen.setOriginToCorner(); buffer = screen.pixels; bgColor = FlxG.bgColor; _color = 0xffffff; _flashBitmap = new Bitmap(buffer); _flashBitmap.x = -width*0.5; _flashBitmap.y = -height*0.5; _flashSprite = new Sprite(); zoom = Zoom; //sets the scale of flash sprite, which in turn loads flashoffset values _flashOffsetX = width*0.5*zoom; _flashOffsetY = height*0.5*zoom; _flashSprite.x = x + _flashOffsetX; _flashSprite.y = y + _flashOffsetY; _flashSprite.addChild(_flashBitmap); _flashRect = new Rectangle(0,0,width,height); _flashPoint = new Point(); _fxFlashColor = 0; _fxFlashDuration = 0.0; _fxFlashComplete = null; _fxFlashAlpha = 0.0; _fxFadeColor = 0; _fxFadeDuration = 0.0; _fxFadeComplete = null; _fxFadeAlpha = 0.0; _fxShakeIntensity = 0.0; _fxShakeDuration = 0.0; _fxShakeComplete = null; _fxShakeOffset = new FlxPoint(); _fxShakeDirection = 0; _fill = new BitmapData(width,height,true,0); } /** * Clean up memory. */ override public function destroy():void { screen.destroy(); screen = null; target = null; scroll = null; deadzone = null; bounds = null; buffer = null; _flashBitmap = null; _flashRect = null; _flashPoint = null; _fxFlashComplete = null; _fxFadeComplete = null; _fxShakeComplete = null; _fxShakeOffset = null; _fill = null; } /** * Updates the camera scroll as well as special effects like screen-shake or fades. */ override public function update():void { //Either follow the object closely, //or doublecheck our deadzone and update accordingly. if(target != null) { if(deadzone == null) focusOn(target.getMidpoint(_point)); else { var edge:Number; var targetX:Number = target.x + ((target.x > 0)?0.0000001:-0.0000001); var targetY:Number = target.y + ((target.y > 0)?0.0000001:-0.0000001); edge = targetX - deadzone.x; if(scroll.x > edge) scroll.x = edge; edge = targetX + target.width - deadzone.x - deadzone.width; if(scroll.x < edge) scroll.x = edge; edge = targetY - deadzone.y; if(scroll.y > edge) scroll.y = edge; edge = targetY + target.height - deadzone.y - deadzone.height; if(scroll.y < edge) scroll.y = edge; } } //Make sure we didn't go outside the camera's bounds if(bounds != null) { if(scroll.x < bounds.left) scroll.x = bounds.left; if(scroll.x > bounds.right - width) scroll.x = bounds.right - width; if(scroll.y < bounds.top) scroll.y = bounds.top; if(scroll.y > bounds.bottom - height) scroll.y = bounds.bottom - height; } //Update the "flash" special effect if(_fxFlashAlpha > 0.0) { _fxFlashAlpha -= FlxG.elapsed/_fxFlashDuration; if((_fxFlashAlpha <= 0) && (_fxFlashComplete != null)) _fxFlashComplete(); } //Update the "fade" special effect if((_fxFadeAlpha > 0.0) && (_fxFadeAlpha < 1.0)) { _fxFadeAlpha += FlxG.elapsed/_fxFadeDuration; if(_fxFadeAlpha >= 1.0) { _fxFadeAlpha = 1.0; if(_fxFadeComplete != null) _fxFadeComplete(); } } //Update the "shake" special effect if(_fxShakeDuration > 0) { _fxShakeDuration -= FlxG.elapsed; if(_fxShakeDuration <= 0) { _fxShakeOffset.make(); if(_fxShakeComplete != null) _fxShakeComplete(); } else { if((_fxShakeDirection == SHAKE_BOTH_AXES) || (_fxShakeDirection == SHAKE_HORIZONTAL_ONLY)) _fxShakeOffset.x = (FlxG.random()*_fxShakeIntensity*width*2-_fxShakeIntensity*width)*_zoom; if((_fxShakeDirection == SHAKE_BOTH_AXES) || (_fxShakeDirection == SHAKE_VERTICAL_ONLY)) _fxShakeOffset.y = (FlxG.random()*_fxShakeIntensity*height*2-_fxShakeIntensity*height)*_zoom; } } } /** * Tells this camera object what <code>FlxObject</code> to track. * * @param Target The object you want the camera to track. Set to null to not follow anything. * @param Style Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling <code>follow()</code>. */ public function follow(Target:FlxObject, Style:uint=STYLE_LOCKON):void { target = Target; var helper:Number; switch(Style) { case STYLE_PLATFORMER: var w:Number = width/8; var h:Number = height/3; deadzone = new FlxRect((width-w)/2,(height-h)/2 - h*0.25,w,h); break; case STYLE_TOPDOWN: helper = FlxU.max(width,height)/4; deadzone = new FlxRect((width-helper)/2,(height-helper)/2,helper,helper); break; case STYLE_TOPDOWN_TIGHT: helper = FlxU.max(width,height)/8; deadzone = new FlxRect((width-helper)/2,(height-helper)/2,helper,helper); break; case STYLE_LOCKON: default: deadzone = null; break; } } /** * Move the camera focus to this location instantly. * * @param Point Where you want the camera to focus. */ public function focusOn(Point:FlxPoint):void { Point.x += (Point.x > 0)?0.0000001:-0.0000001; Point.y += (Point.y > 0)?0.0000001:-0.0000001; scroll.make(Point.x - width*0.5,Point.y - height*0.5); } /** * Specify the boundaries of the level or where the camera is allowed to move. * * @param X The smallest X value of your level (usually 0). * @param Y The smallest Y value of your level (usually 0). * @param Width The largest X value of your level (usually the level width). * @param Height The largest Y value of your level (usually the level height). * @param UpdateWorld Whether the global quad-tree's dimensions should be updated to match (default: false). */ public function setBounds(X:Number=0, Y:Number=0, Width:Number=0, Height:Number=0, UpdateWorld:Boolean=false):void { if(bounds == null) bounds = new FlxRect(); bounds.make(X,Y,Width,Height); if(UpdateWorld) FlxG.worldBounds.copyFrom(bounds); update(); } /** * The screen is filled with this color and gradually returns to normal. * * @param Color The color you want to use. * @param Duration How long it takes for the flash to fade. * @param OnComplete A function you want to run when the flash finishes. * @param Force Force the effect to reset. */ public function flash(Color:uint=0xffffffff, Duration:Number=1, OnComplete:Function=null, Force:Boolean=false):void { if(!Force && (_fxFlashAlpha > 0.0)) return; _fxFlashColor = Color; if(Duration <= 0) Duration = Number.MIN_VALUE; _fxFlashDuration = Duration; _fxFlashComplete = OnComplete; _fxFlashAlpha = 1.0; } /** * The screen is gradually filled with this color. * * @param Color The color you want to use. * @param Duration How long it takes for the fade to finish. * @param OnComplete A function you want to run when the fade finishes. * @param Force Force the effect to reset. */ public function fade(Color:uint=0xff000000, Duration:Number=1, OnComplete:Function=null, Force:Boolean=false):void { if(!Force && (_fxFadeAlpha > 0.0)) return; _fxFadeColor = Color; if(Duration <= 0) Duration = Number.MIN_VALUE; _fxFadeDuration = Duration; _fxFadeComplete = OnComplete; _fxFadeAlpha = Number.MIN_VALUE; } /** * A simple screen-shake effect. * * @param Intensity Percentage of screen size representing the maximum distance that the screen can move while shaking. * @param Duration The length in seconds that the shaking effect should last. * @param OnComplete A function you want to run when the shake effect finishes. * @param Force Force the effect to reset (default = true, unlike flash() and fade()!). * @param Direction Whether to shake on both axes, just up and down, or just side to side (use class constants SHAKE_BOTH_AXES, SHAKE_VERTICAL_ONLY, or SHAKE_HORIZONTAL_ONLY). */ public function shake(Intensity:Number=0.05, Duration:Number=0.5, OnComplete:Function=null, Force:Boolean=true, Direction:uint=SHAKE_BOTH_AXES):void { if(!Force && ((_fxShakeOffset.x != 0) || (_fxShakeOffset.y != 0))) return; _fxShakeIntensity = Intensity; _fxShakeDuration = Duration; _fxShakeComplete = OnComplete; _fxShakeDirection = Direction; _fxShakeOffset.make(); } /** * Just turns off all the camera effects instantly. */ public function stopFX():void { _fxFlashAlpha = 0.0; _fxFadeAlpha = 0.0; _fxShakeDuration = 0; _flashSprite.x = x + width*0.5; _flashSprite.y = y + height*0.5; } /** * Copy the bounds, focus object, and deadzone info from an existing camera. * * @param Camera The camera you want to copy from. * * @return A reference to this <code>FlxCamera</code> object. */ public function copyFrom(Camera:FlxCamera):FlxCamera { if(Camera.bounds == null) bounds = null; else { if(bounds == null) bounds = new FlxRect(); bounds.copyFrom(Camera.bounds); } target = Camera.target; if(target != null) { if(Camera.deadzone == null) deadzone = null; else { if(deadzone == null) deadzone = new FlxRect(); deadzone.copyFrom(Camera.deadzone); } } return this; } /** * The zoom level of this camera. 1 = 1:1, 2 = 2x zoom, etc. */ public function get zoom():Number { return _zoom; } /** * @private */ public function set zoom(Zoom:Number):void { if(Zoom == 0) _zoom = defaultZoom; else _zoom = Zoom; setScale(_zoom,_zoom); } /** * The alpha value of this camera display (a Number between 0.0 and 1.0). */ public function get alpha():Number { return _flashBitmap.alpha; } /** * @private */ public function set alpha(Alpha:Number):void { _flashBitmap.alpha = Alpha; } /** * The angle of the camera display (in degrees). * Currently yields weird display results, * since cameras aren't nested in an extra display object yet. */ public function get angle():Number { return _flashSprite.rotation; } /** * @private */ public function set angle(Angle:Number):void { _flashSprite.rotation = Angle; } /** * The color tint of the camera display. */ public function get color():uint { return _color; } /** * @private */ public function set color(Color:uint):void { _color = Color; var colorTransform:ColorTransform = _flashBitmap.transform.colorTransform; colorTransform.redMultiplier = (_color>>16)*0.00392; colorTransform.greenMultiplier = (_color>>8&0xff)*0.00392; colorTransform.blueMultiplier = (_color&0xff)*0.00392; _flashBitmap.transform.colorTransform = colorTransform; } /** * Whether the camera display is smooth and filtered, or chunky and pixelated. * Default behavior is chunky-style. */ public function get antialiasing():Boolean { return _flashBitmap.smoothing; } /** * @private */ public function set antialiasing(Antialiasing:Boolean):void { _flashBitmap.smoothing = Antialiasing; } /** * The scale of the camera object, irrespective of zoom. * Currently yields weird display results, * since cameras aren't nested in an extra display object yet. */ public function getScale():FlxPoint { return _point.make(_flashSprite.scaleX,_flashSprite.scaleY); } /** * @private */ public function setScale(X:Number,Y:Number):void { _flashSprite.scaleX = X; _flashSprite.scaleY = Y; } /** * Fetches a reference to the Flash <code>Sprite</code> object * that contains the camera display in the Flash display list. * Uses include 3D projection, advanced display list modification, and more. * NOTE: We don't recommend modifying this directly unless you are * fairly experienced. For simple changes to the camera display, * like scaling, rotation, and color tinting, we recommend * using the existing <code>FlxCamera</code> variables. * * @return A Flash <code>Sprite</code> object containing the camera display. */ public function getContainerSprite():Sprite { return _flashSprite; } /** * Fill the camera with the specified color. * * @param Color The color to fill with in 0xAARRGGBB hex format. * @param BlendAlpha Whether to blend the alpha value or just wipe the previous contents. Default is true. */ public function fill(Color:uint,BlendAlpha:Boolean=true):void { _fill.fillRect(_flashRect,Color); buffer.copyPixels(_fill,_flashRect,_flashPoint,null,null,BlendAlpha); } /** * Internal helper function, handles the actual drawing of all the special effects. */ internal function drawFX():void { var alphaComponent:Number; //Draw the "flash" special effect onto the buffer if(_fxFlashAlpha > 0.0) { alphaComponent = _fxFlashColor>>24; fill((uint(((alphaComponent <= 0)?0xff:alphaComponent)*_fxFlashAlpha)<<24)+(_fxFlashColor&0x00ffffff)); } //Draw the "fade" special effect onto the buffer if(_fxFadeAlpha > 0.0) { alphaComponent = _fxFadeColor>>24; fill((uint(((alphaComponent <= 0)?0xff:alphaComponent)*_fxFadeAlpha)<<24)+(_fxFadeColor&0x00ffffff)); } if((_fxShakeOffset.x != 0) || (_fxShakeOffset.y != 0)) { _flashSprite.x = x + _flashOffsetX + _fxShakeOffset.x; _flashSprite.y = y + _flashOffsetY + _fxShakeOffset.y; } } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxCamera.as
ActionScript
gpl3
20,658
package org.flixel { import flash.geom.Point; /** * Stores a 2D floating point coordinate. * * @author Adam Atomic */ public class FlxPoint { /** * @default 0 */ public var x:Number; /** * @default 0 */ public var y:Number; /** * Instantiate a new point object. * * @param X The X-coordinate of the point in space. * @param Y The Y-coordinate of the point in space. */ public function FlxPoint(X:Number=0, Y:Number=0) { x = X; y = Y; } /** * Instantiate a new point object. * * @param X The X-coordinate of the point in space. * @param Y The Y-coordinate of the point in space. */ public function make(X:Number=0, Y:Number=0):FlxPoint { x = X; y = Y; return this; } /** * Helper function, just copies the values from the specified point. * * @param Point Any <code>FlxPoint</code>. * * @return A reference to itself. */ public function copyFrom(Point:FlxPoint):FlxPoint { x = Point.x; y = Point.y; return this; } /** * Helper function, just copies the values from this point to the specified point. * * @param Point Any <code>FlxPoint</code>. * * @return A reference to the altered point parameter. */ public function copyTo(Point:FlxPoint):FlxPoint { Point.x = x; Point.y = y; return Point; } /** * Helper function, just copies the values from the specified Flash point. * * @param Point Any <code>Point</code>. * * @return A reference to itself. */ public function copyFromFlash(FlashPoint:Point):FlxPoint { x = FlashPoint.x; y = FlashPoint.y; return this; } /** * Helper function, just copies the values from this point to the specified Flash point. * * @param Point Any <code>Point</code>. * * @return A reference to the altered point parameter. */ public function copyToFlash(FlashPoint:Point):Point { FlashPoint.x = x; FlashPoint.y = y; return FlashPoint; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxPoint.as
ActionScript
gpl3
2,037
package org.flixel { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Graphics; import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.*; import flash.geom.Point; import flash.text.AntiAliasType; import flash.text.GridFitType; import flash.text.TextField; import flash.text.TextFormat; import flash.ui.Mouse; import flash.utils.Timer; import flash.utils.getTimer; import org.flixel.plugin.TimerManager; import org.flixel.system.FlxDebugger; import org.flixel.system.FlxReplay; /** * FlxGame is the heart of all flixel games, and contains a bunch of basic game loops and things. * It is a long and sloppy file that you shouldn't have to worry about too much! * It is basically only used to create your game object in the first place, * after that FlxG and FlxState have all the useful stuff you actually need. * * @author Adam Atomic */ public class FlxGame extends Sprite { [Embed(source="data/nokiafc22.ttf",fontFamily="system",embedAsCFF="false")] protected var junk:String; [Embed(source="data/beep.mp3")] protected var SndBeep:Class; [Embed(source="data/logo.png")] protected var ImgLogo:Class; /** * Sets 0, -, and + to control the global volume sound volume. * @default true */ public var useSoundHotKeys:Boolean; /** * Tells flixel to use the default system mouse cursor instead of custom Flixel mouse cursors. * @default false */ public var useSystemCursor:Boolean; /** * Initialize and allow the flixel debugger overlay even in release mode. * Also useful if you don't use FlxPreloader! * @default false */ public var forceDebugger:Boolean; /** * Current game state. */ internal var _state:FlxState; /** * Mouse cursor. */ internal var _mouse:Sprite; /** * Class type of the initial/first game state for the game, usually MenuState or something like that. */ protected var _iState:Class; /** * Whether the game object's basic initialization has finished yet. */ protected var _created:Boolean; /** * Total number of milliseconds elapsed since game start. */ protected var _total:uint; /** * Total number of milliseconds elapsed since last update loop. * Counts down as we step through the game loop. */ protected var _accumulator:int; /** * Whether the Flash player lost focus. */ protected var _lostFocus:Boolean; /** * Milliseconds of time per step of the game loop. FlashEvent.g. 60 fps = 16ms. */ internal var _step:uint; /** * Framerate of the Flash player (NOT the game loop). Default = 30. */ internal var _flashFramerate:uint; /** * Max allowable accumulation (see _accumulator). * Should always (and automatically) be set to roughly 2x the flash player framerate. */ internal var _maxAccumulation:uint; /** * If a state change was requested, the new state object is stored here until we switch to it. */ internal var _requestedState:FlxState; /** * A flag for keeping track of whether a game reset was requested or not. */ internal var _requestedReset:Boolean; /** * The "focus lost" screen (see <code>createFocusScreen()</code>). */ protected var _focus:Sprite; /** * The sound tray display container (see <code>createSoundTray()</code>). */ protected var _soundTray:Sprite; /** * Helps us auto-hide the sound tray after a volume change. */ protected var _soundTrayTimer:Number; /** * Helps display the volume bars on the sound tray. */ protected var _soundTrayBars:Array; /** * The debugger overlay object. */ internal var _debugger:FlxDebugger; /** * A handy boolean that keeps track of whether the debugger exists and is currently visible. */ internal var _debuggerUp:Boolean; /** * Container for a game replay object. */ internal var _replay:FlxReplay; /** * Flag for whether a playback of a recording was requested. */ internal var _replayRequested:Boolean; /** * Flag for whether a new recording was requested. */ internal var _recordingRequested:Boolean; /** * Flag for whether a replay is currently playing. */ internal var _replaying:Boolean; /** * Flag for whether a new recording is being made. */ internal var _recording:Boolean; /** * Array that keeps track of keypresses that can cancel a replay. * Handy for skipping cutscenes or getting out of attract modes! */ internal var _replayCancelKeys:Array; /** * Helps time out a replay if necessary. */ internal var _replayTimer:int; /** * This function, if set, is triggered when the callback stops playing. */ internal var _replayCallback:Function; /** * Instantiate a new game object. * * @param GameSizeX The width of your game in game pixels, not necessarily final display pixels (see Zoom). * @param GameSizeY The height of your game in game pixels, not necessarily final display pixels (see Zoom). * @param InitialState The class name of the state you want to create and switch to first (e.g. MenuState). * @param Zoom The default level of zoom for the game's cameras (e.g. 2 = all pixels are now drawn at 2x). Default = 1. * @param GameFramerate How frequently the game should update (default is 60 times per second). * @param FlashFramerate Sets the actual display framerate for Flash player (default is 30 times per second). * @param UseSystemCursor Whether to use the default OS mouse pointer, or to use custom flixel ones. */ public function FlxGame(GameSizeX:uint,GameSizeY:uint,InitialState:Class,Zoom:Number=1,GameFramerate:uint=60,FlashFramerate:uint=30,UseSystemCursor:Boolean=false) { //super high priority init stuff (focus, mouse, etc) _lostFocus = false; _focus = new Sprite(); _focus.visible = false; _soundTray = new Sprite(); _mouse = new Sprite() //basic display and update setup stuff FlxG.init(this,GameSizeX,GameSizeY,Zoom); FlxG.framerate = GameFramerate; FlxG.flashFramerate = FlashFramerate; _accumulator = _step; _total = 0; _state = null; useSoundHotKeys = true; useSystemCursor = UseSystemCursor; if(!useSystemCursor) flash.ui.Mouse.hide(); forceDebugger = false; _debuggerUp = false; //replay data _replay = new FlxReplay(); _replayRequested = false; _recordingRequested = false; _replaying = false; _recording = false; //then get ready to create the game object for real _iState = InitialState; _requestedState = null; _requestedReset = true; _created = false; addEventListener(Event.ENTER_FRAME, create); } /** * Makes the little volume tray slide out. * * @param Silent Whether or not it should beep. */ internal function showSoundTray(Silent:Boolean=false):void { if(!Silent) FlxG.play(SndBeep); _soundTrayTimer = 1; _soundTray.y = 0; _soundTray.visible = true; var globalVolume:uint = Math.round(FlxG.volume*10); if(FlxG.mute) globalVolume = 0; for (var i:uint = 0; i < _soundTrayBars.length; i++) { if(i < globalVolume) _soundTrayBars[i].alpha = 1; else _soundTrayBars[i].alpha = 0.5; } } /** * Internal event handler for input and focus. * * @param FlashEvent Flash keyboard event. */ protected function onKeyUp(FlashEvent:KeyboardEvent):void { if(_debuggerUp && _debugger.watch.editing) return; if(!FlxG.mobile) { if((_debugger != null) && ((FlashEvent.keyCode == 192) || (FlashEvent.keyCode == 220))) { _debugger.visible = !_debugger.visible; _debuggerUp = _debugger.visible; if(_debugger.visible) flash.ui.Mouse.show(); else if(!useSystemCursor) flash.ui.Mouse.hide(); //_console.toggle(); return; } if(useSoundHotKeys) { var c:int = FlashEvent.keyCode; var code:String = String.fromCharCode(FlashEvent.charCode); switch(c) { case 48: case 96: FlxG.mute = !FlxG.mute; if(FlxG.volumeHandler != null) FlxG.volumeHandler(FlxG.mute?0:FlxG.volume); showSoundTray(); return; case 109: case 189: FlxG.mute = false; FlxG.volume = FlxG.volume - 0.1; showSoundTray(); return; case 107: case 187: FlxG.mute = false; FlxG.volume = FlxG.volume + 0.1; showSoundTray(); return; default: break; } } } if(_replaying) return; FlxG.keys.handleKeyUp(FlashEvent); } /** * Internal event handler for input and focus. * * @param FlashEvent Flash keyboard event. */ protected function onKeyDown(FlashEvent:KeyboardEvent):void { if(_debuggerUp && _debugger.watch.editing) return; if(_replaying && (_replayCancelKeys != null) && (_debugger == null) && (FlashEvent.keyCode != 192) && (FlashEvent.keyCode != 220)) { var cancel:Boolean = false; var replayCancelKey:String; var i:uint = 0; var l:uint = _replayCancelKeys.length; while(i < l) { replayCancelKey = _replayCancelKeys[i++]; if((replayCancelKey == "ANY") || (FlxG.keys.getKeyCode(replayCancelKey) == FlashEvent.keyCode)) { if(_replayCallback != null) { _replayCallback(); _replayCallback = null; } else FlxG.stopReplay(); break; } } return; } FlxG.keys.handleKeyDown(FlashEvent); } /** * Internal event handler for input and focus. * * @param FlashEvent Flash mouse event. */ protected function onMouseDown(FlashEvent:MouseEvent):void { if(_debuggerUp) { if(_debugger.hasMouse) return; if(_debugger.watch.editing) _debugger.watch.submit(); } if(_replaying && (_replayCancelKeys != null)) { var replayCancelKey:String; var i:uint = 0; var l:uint = _replayCancelKeys.length; while(i < l) { replayCancelKey = _replayCancelKeys[i++] as String; if((replayCancelKey == "MOUSE") || (replayCancelKey == "ANY")) { if(_replayCallback != null) { _replayCallback(); _replayCallback = null; } else FlxG.stopReplay(); break; } } return; } FlxG.mouse.handleMouseDown(FlashEvent); } /** * Internal event handler for input and focus. * * @param FlashEvent Flash mouse event. */ protected function onMouseUp(FlashEvent:MouseEvent):void { if((_debuggerUp && _debugger.hasMouse) || _replaying) return; FlxG.mouse.handleMouseUp(FlashEvent); } /** * Internal event handler for input and focus. * * @param FlashEvent Flash mouse event. */ protected function onMouseWheel(FlashEvent:MouseEvent):void { if((_debuggerUp && _debugger.hasMouse) || _replaying) return; FlxG.mouse.handleMouseWheel(FlashEvent); } /** * Internal event handler for input and focus. * * @param FlashEvent Flash event. */ protected function onFocus(FlashEvent:Event=null):void { if(!_debuggerUp && !useSystemCursor) flash.ui.Mouse.hide(); FlxG.resetInput(); _lostFocus = _focus.visible = false; stage.frameRate = _flashFramerate; FlxG.resumeSounds(); } /** * Internal event handler for input and focus. * * @param FlashEvent Flash event. */ protected function onFocusLost(FlashEvent:Event=null):void { if((x != 0) || (y != 0)) { x = 0; y = 0; } flash.ui.Mouse.show(); _lostFocus = _focus.visible = true; stage.frameRate = 10; FlxG.pauseSounds(); } /** * Handles the onEnterFrame call and figures out how many updates and draw calls to do. * * @param FlashEvent Flash event. */ protected function onEnterFrame(FlashEvent:Event=null):void { var mark:uint = getTimer(); var elapsedMS:uint = mark-_total; _total = mark; updateSoundTray(elapsedMS); if(!_lostFocus) { if((_debugger != null) && _debugger.vcr.paused) { if(_debugger.vcr.stepRequested) { _debugger.vcr.stepRequested = false; step(); } } else { _accumulator += elapsedMS; if(_accumulator > _maxAccumulation) _accumulator = _maxAccumulation; while(_accumulator >= _step) { step(); _accumulator = _accumulator - _step; } } FlxBasic._VISIBLECOUNT = 0; draw(); if(_debuggerUp) { _debugger.perf.flash(elapsedMS); _debugger.perf.visibleObjects(FlxBasic._VISIBLECOUNT); _debugger.perf.update(); _debugger.watch.update(); } } } /** * If there is a state change requested during the update loop, * this function handles actual destroying the old state and related processes, * and calls creates on the new state and plugs it into the game object. */ protected function switchState():void { //Basic reset stuff FlxG.resetCameras(); FlxG.resetInput(); FlxG.destroySounds(); FlxG.clearBitmapCache(); //Clear the debugger overlay's Watch window if(_debugger != null) _debugger.watch.removeAll(); //Clear any timers left in the timer manager var timerManager:TimerManager = FlxTimer.manager; if(timerManager != null) timerManager.clear(); //Destroy the old state (if there is an old state) if(_state != null) _state.destroy(); //Finally assign and create the new state _state = _requestedState; _state.create(); } /** * This is the main game update logic section. * The onEnterFrame() handler is in charge of calling this * the appropriate number of times each frame. * This block handles state changes, replays, all that good stuff. */ protected function step():void { //handle game reset request if(_requestedReset) { _requestedReset = false; _requestedState = new _iState(); _replayTimer = 0; _replayCancelKeys = null; FlxG.reset(); } //handle replay-related requests if(_recordingRequested) { _recordingRequested = false; _replay.create(FlxG.globalSeed); _recording = true; if(_debugger != null) { _debugger.vcr.recording(); FlxG.log("FLIXEL: starting new flixel gameplay record."); } } else if(_replayRequested) { _replayRequested = false; _replay.rewind(); FlxG.globalSeed = _replay.seed; if(_debugger != null) _debugger.vcr.playing(); _replaying = true; } //handle state switching requests if(_state != _requestedState) switchState(); //finally actually step through the game physics FlxBasic._ACTIVECOUNT = 0; if(_replaying) { _replay.playNextFrame(); if(_replayTimer > 0) { _replayTimer -= _step; if(_replayTimer <= 0) { if(_replayCallback != null) { _replayCallback(); _replayCallback = null; } else FlxG.stopReplay(); } } if(_replaying && _replay.finished) { FlxG.stopReplay(); if(_replayCallback != null) { _replayCallback(); _replayCallback = null; } } if(_debugger != null) _debugger.vcr.updateRuntime(_step); } else FlxG.updateInput(); if(_recording) { _replay.recordFrame(); if(_debugger != null) _debugger.vcr.updateRuntime(_step); } update(); FlxG.mouse.wheel = 0; if(_debuggerUp) _debugger.perf.activeObjects(FlxBasic._ACTIVECOUNT); } /** * This function just updates the soundtray object. */ protected function updateSoundTray(MS:Number):void { //animate stupid sound tray thing if(_soundTray != null) { if(_soundTrayTimer > 0) _soundTrayTimer -= MS/1000; else if(_soundTray.y > -_soundTray.height) { _soundTray.y -= (MS/1000)*FlxG.height*2; if(_soundTray.y <= -_soundTray.height) { _soundTray.visible = false; //Save sound preferences var soundPrefs:FlxSave = new FlxSave(); if(soundPrefs.bind("flixel")) { if(soundPrefs.data.sound == null) soundPrefs.data.sound = new Object; soundPrefs.data.sound.mute = FlxG.mute; soundPrefs.data.sound.volume = FlxG.volume; soundPrefs.close(); } } } } } /** * This function is called by step() and updates the actual game state. * May be called multiple times per "frame" or draw call. */ protected function update():void { var mark:uint = getTimer(); FlxG.elapsed = FlxG.timeScale*(_step/1000); FlxG.updateSounds(); FlxG.updatePlugins(); _state.update(); FlxG.updateCameras(); if(_debuggerUp) _debugger.perf.flixelUpdate(getTimer()-mark); } /** * Goes through the game state and draws all the game objects and special effects. */ protected function draw():void { var mark:uint = getTimer(); FlxG.lockCameras(); _state.draw(); FlxG.drawPlugins(); FlxG.unlockCameras(); if(_debuggerUp) _debugger.perf.flixelDraw(getTimer()-mark); } /** * Used to instantiate the guts of the flixel game object once we have a valid reference to the root. * * @param FlashEvent Just a Flash system event, not too important for our purposes. */ protected function create(FlashEvent:Event):void { if(root == null) return; removeEventListener(Event.ENTER_FRAME, create); _total = getTimer(); //Set up the view window and double buffering stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; stage.frameRate = _flashFramerate; //Add basic input event listeners and mouse container stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown); stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp); stage.addEventListener(MouseEvent.MOUSE_WHEEL, onMouseWheel); stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp); addChild(_mouse); //Let mobile devs opt out of unnecessary overlays. if(!FlxG.mobile) { //Debugger overlay if(FlxG.debug || forceDebugger) { _debugger = new FlxDebugger(FlxG.width*FlxCamera.defaultZoom,FlxG.height*FlxCamera.defaultZoom); addChild(_debugger); } //Volume display tab createSoundTray(); //Focus gained/lost monitoring stage.addEventListener(Event.DEACTIVATE, onFocusLost); stage.addEventListener(Event.ACTIVATE, onFocus); createFocusScreen(); } //Finally, set up an event for the actual game loop stuff. addEventListener(Event.ENTER_FRAME, onEnterFrame); } /** * Sets up the "sound tray", the little volume meter that pops down sometimes. */ protected function createSoundTray():void { _soundTray.visible = false; _soundTray.scaleX = 2; _soundTray.scaleY = 2; var tmp:Bitmap = new Bitmap(new BitmapData(80,30,true,0x7F000000)); _soundTray.x = (FlxG.width/2)*FlxCamera.defaultZoom-(tmp.width/2)*_soundTray.scaleX; _soundTray.addChild(tmp); var text:TextField = new TextField(); text.width = tmp.width; text.height = tmp.height; text.multiline = true; text.wordWrap = true; text.selectable = false; text.embedFonts = true; text.antiAliasType = AntiAliasType.NORMAL; text.gridFitType = GridFitType.PIXEL; text.defaultTextFormat = new TextFormat("system",8,0xffffff,null,null,null,null,null,"center");; _soundTray.addChild(text); text.text = "VOLUME"; text.y = 16; var bx:uint = 10; var by:uint = 14; _soundTrayBars = new Array(); var i:uint = 0; while(i < 10) { tmp = new Bitmap(new BitmapData(4,++i,false,0xffffff)); tmp.x = bx; tmp.y = by; _soundTrayBars.push(_soundTray.addChild(tmp)); bx += 6; by--; } _soundTray.y = -_soundTray.height; _soundTray.visible = false; addChild(_soundTray); //load saved sound preferences for this game if they exist var soundPrefs:FlxSave = new FlxSave(); if(soundPrefs.bind("flixel") && (soundPrefs.data.sound != null)) { if(soundPrefs.data.sound.volume != null) FlxG.volume = soundPrefs.data.sound.volume; if(soundPrefs.data.sound.mute != null) FlxG.mute = soundPrefs.data.sound.mute; soundPrefs.destroy(); } } /** * Sets up the darkened overlay with the big white "play" button that appears when a flixel game loses focus. */ protected function createFocusScreen():void { var gfx:Graphics = _focus.graphics; var screenWidth:uint = FlxG.width*FlxCamera.defaultZoom; var screenHeight:uint = FlxG.height*FlxCamera.defaultZoom; //draw transparent black backdrop gfx.moveTo(0,0); gfx.beginFill(0,0.5); gfx.lineTo(screenWidth,0); gfx.lineTo(screenWidth,screenHeight); gfx.lineTo(0,screenHeight); gfx.lineTo(0,0); gfx.endFill(); //draw white arrow var halfWidth:uint = screenWidth/2; var halfHeight:uint = screenHeight/2; var helper:uint = FlxU.min(halfWidth,halfHeight)/3; gfx.moveTo(halfWidth-helper,halfHeight-helper); gfx.beginFill(0xffffff,0.65); gfx.lineTo(halfWidth+helper,halfHeight); gfx.lineTo(halfWidth-helper,halfHeight+helper); gfx.lineTo(halfWidth-helper,halfHeight-helper); gfx.endFill(); var logo:Bitmap = new ImgLogo(); logo.scaleX = int(helper/10); if(logo.scaleX < 1) logo.scaleX = 1; logo.scaleY = logo.scaleX; logo.x -= logo.scaleX; logo.alpha = 0.35; _focus.addChild(logo); addChild(_focus); } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxGame.as
ActionScript
gpl3
21,659
package org.flixel { import org.flixel.system.FlxQuadTree; /** * This is the basic game "state" object - e.g. in a simple game * you might have a menu state and a play state. * It is for all intents and purpose a fancy FlxGroup. * And really, it's not even that fancy. * * @author Adam Atomic */ public class FlxState extends FlxGroup { /** * This function is called after the game engine successfully switches states. * Override this function, NOT the constructor, to initialize or set up your game state. * We do NOT recommend overriding the constructor, unless you want some crazy unpredictable things to happen! */ public function create():void { } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxState.as
ActionScript
gpl3
703
package org.flixel { import flash.display.BitmapData; import flash.geom.Rectangle; /** * This is a basic "environment object" class, used to create simple walls and floors. * It can be filled with a random selection of tiles to quickly add detail. * * @author Adam Atomic */ public class FlxTileblock extends FlxSprite { /** * Creates a new <code>FlxBlock</code> object with the specified position and size. * * @param X The X position of the block. * @param Y The Y position of the block. * @param Width The width of the block. * @param Height The height of the block. */ public function FlxTileblock(X:int,Y:int,Width:uint,Height:uint) { super(X,Y); makeGraphic(Width,Height,0,true); active = false; immovable = true; } /** * Fills the block with a randomly arranged selection of graphics from the image provided. * * @param TileGraphic The graphic class that contains the tiles that should fill this block. * @param TileWidth The width of a single tile in the graphic. * @param TileHeight The height of a single tile in the graphic. * @param Empties The number of "empty" tiles to add to the auto-fill algorithm (e.g. 8 tiles + 4 empties = 1/3 of block will be open holes). */ public function loadTiles(TileGraphic:Class,TileWidth:uint=0,TileHeight:uint=0,Empties:uint=0):FlxTileblock { if(TileGraphic == null) return this; //First create a tile brush var sprite:FlxSprite = new FlxSprite().loadGraphic(TileGraphic,true,false,TileWidth,TileHeight); var spriteWidth:uint = sprite.width; var spriteHeight:uint = sprite.height; var total:uint = sprite.frames + Empties; //Then prep the "canvas" as it were (just doublechecking that the size is on tile boundaries) var regen:Boolean = false; if(width % sprite.width != 0) { width = uint(width/spriteWidth+1)*spriteWidth; regen = true; } if(height % sprite.height != 0) { height = uint(height/spriteHeight+1)*spriteHeight; regen = true; } if(regen) makeGraphic(width,height,0,true); else this.fill(0); //Stamp random tiles onto the canvas var row:uint = 0; var column:uint; var destinationX:uint; var destinationY:uint = 0; var widthInTiles:uint = width/spriteWidth; var heightInTiles:uint = height/spriteHeight; while(row < heightInTiles) { destinationX = 0; column = 0; while(column < widthInTiles) { if(FlxG.random()*total > Empties) { sprite.randomFrame(); sprite.drawFrame(); stamp(sprite,destinationX,destinationY); } destinationX += spriteWidth; column++; } destinationY += spriteHeight; row++; } return this; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxTileblock.as
ActionScript
gpl3
2,774
package org.flixel { /** * This is a useful "generic" Flixel object. * Both <code>FlxObject</code> and <code>FlxGroup</code> extend this class, * as do the plugins. Has no size, position or graphical data. * * @author Adam Atomic */ public class FlxBasic { static internal var _ACTIVECOUNT:uint; static internal var _VISIBLECOUNT:uint; /** * IDs seem like they could be pretty useful, huh? * They're not actually used for anything yet though. */ public var ID:int; /** * Controls whether <code>update()</code> and <code>draw()</code> are automatically called by FlxState/FlxGroup. */ public var exists:Boolean; /** * Controls whether <code>update()</code> is automatically called by FlxState/FlxGroup. */ public var active:Boolean; /** * Controls whether <code>draw()</code> is automatically called by FlxState/FlxGroup. */ public var visible:Boolean; /** * Useful state for many game objects - "dead" (!alive) vs alive. * <code>kill()</code> and <code>revive()</code> both flip this switch (along with exists, but you can override that). */ public var alive:Boolean; /** * An array of camera objects that this object will use during <code>draw()</code>. * This value will initialize itself during the first draw to automatically * point at the main camera list out in <code>FlxG</code> unless you already set it. * You can also change it afterward too, very flexible! */ public var cameras:Array; /** * Setting this to true will prevent the object from appearing * when the visual debug mode in the debugger overlay is toggled on. */ public var ignoreDrawDebug:Boolean; /** * Instantiate the basic flixel object. */ public function FlxBasic() { ID = -1; exists = true; active = true; visible = true; alive = true; ignoreDrawDebug = false; } /** * Override this function to null out variables or manually call * <code>destroy()</code> on class members if necessary. * Don't forget to call <code>super.destroy()</code>! */ public function destroy():void {} /** * Pre-update is called right before <code>update()</code> on each object in the game loop. */ public function preUpdate():void { _ACTIVECOUNT++; } /** * Override this function to update your class's position and appearance. * This is where most of your game rules and behavioral code will go. */ public function update():void { } /** * Post-update is called right after <code>update()</code> on each object in the game loop. */ public function postUpdate():void { } /** * Override this function to control how the object is drawn. * Overriding <code>draw()</code> is rarely necessary, but can be very useful. */ public function draw():void { if(cameras == null) cameras = FlxG.cameras; var camera:FlxCamera; var i:uint = 0; var l:uint = cameras.length; while(i < l) { camera = cameras[i++]; _VISIBLECOUNT++; if(FlxG.visualDebug && !ignoreDrawDebug) drawDebug(camera); } } /** * Override this function to draw custom "debug mode" graphics to the * specified camera while the debugger's visual mode is toggled on. * * @param Camera Which camera to draw the debug visuals to. */ public function drawDebug(Camera:FlxCamera=null):void { } /** * Handy function for "killing" game objects. * Default behavior is to flag them as nonexistent AND dead. * However, if you want the "corpse" to remain in the game, * like to animate an effect or whatever, you should override this, * setting only alive to false, and leaving exists true. */ public function kill():void { alive = false; exists = false; } /** * Handy function for bringing game objects "back to life". Just sets alive and exists back to true. * In practice, this function is most often called by <code>FlxObject.reset()</code>. */ public function revive():void { alive = true; exists = true; } /** * Convert object to readable string name. Useful for debugging, save games, etc. */ public function toString():String { return FlxU.getClassName(this,true); } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxBasic.as
ActionScript
gpl3
4,265
package org.flixel { import flash.events.Event; import flash.media.Sound; import flash.media.SoundChannel; import flash.media.SoundTransform; import flash.net.URLRequest; /** * This is the universal flixel sound object, used for streaming, music, and sound effects. * * @author Adam Atomic */ public class FlxSound extends FlxBasic { /** * The X position of this sound in world coordinates. * Only really matters if you are doing proximity/panning stuff. */ public var x:Number; /** * The Y position of this sound in world coordinates. * Only really matters if you are doing proximity/panning stuff. */ public var y:Number; /** * Whether or not this sound should be automatically destroyed when you switch states. */ public var survive:Boolean; /** * The ID3 song name. Defaults to null. Currently only works for streamed sounds. */ public var name:String; /** * The ID3 artist name. Defaults to null. Currently only works for streamed sounds. */ public var artist:String; /** * Stores the average wave amplitude of both stereo channels */ public var amplitude:Number; /** * Just the amplitude of the left stereo channel */ public var amplitudeLeft:Number; /** * Just the amplitude of the left stereo channel */ public var amplitudeRight:Number; /** * Whether to call destroy() when the sound has finished. */ public var autoDestroy:Boolean; /** * Internal tracker for a Flash sound object. */ protected var _sound:Sound; /** * Internal tracker for a Flash sound channel object. */ protected var _channel:SoundChannel; /** * Internal tracker for a Flash sound transform object. */ protected var _transform:SoundTransform; /** * Internal tracker for the position in runtime of the music playback. */ protected var _position:Number; /** * Internal tracker for how loud the sound is. */ protected var _volume:Number; /** * Internal tracker for total volume adjustment. */ protected var _volumeAdjust:Number; /** * Internal tracker for whether the sound is looping or not. */ protected var _looped:Boolean; /** * Internal tracker for the sound's "target" (for proximity and panning). */ protected var _target:FlxObject; /** * Internal tracker for the maximum effective radius of this sound (for proximity and panning). */ protected var _radius:Number; /** * Internal tracker for whether to pan the sound left and right. Default is false. */ protected var _pan:Boolean; /** * Internal timer used to keep track of requests to fade out the sound playback. */ protected var _fadeOutTimer:Number; /** * Internal helper for fading out sounds. */ protected var _fadeOutTotal:Number; /** * Internal flag for whether to pause or stop the sound when it's done fading out. */ protected var _pauseOnFadeOut:Boolean; /** * Internal timer for fading in the sound playback. */ protected var _fadeInTimer:Number; /** * Internal helper for fading in sounds. */ protected var _fadeInTotal:Number; /** * The FlxSound constructor gets all the variables initialized, but NOT ready to play a sound yet. */ public function FlxSound() { super(); createSound(); } /** * An internal function for clearing all the variables used by sounds. */ protected function createSound():void { destroy(); x = 0; y = 0; if(_transform == null) _transform = new SoundTransform(); _transform.pan = 0; _sound = null; _position = 0; _volume = 1.0; _volumeAdjust = 1.0; _looped = false; _target = null; _radius = 0; _pan = false; _fadeOutTimer = 0; _fadeOutTotal = 0; _pauseOnFadeOut = false; _fadeInTimer = 0; _fadeInTotal = 0; exists = false; active = false; visible = false; name = null; artist = null; amplitude = 0; amplitudeLeft = 0; amplitudeRight = 0; autoDestroy = false; } /** * Clean up memory. */ override public function destroy():void { kill(); _transform = null; _sound = null; _channel = null; _target = null; name = null; artist = null; super.destroy(); } /** * Handles fade out, fade in, panning, proximity, and amplitude operations each frame. */ override public function update():void { if(_position != 0) return; var radial:Number = 1.0; var fade:Number = 1.0; //Distance-based volume control if(_target != null) { radial = FlxU.getDistance(new FlxPoint(_target.x,_target.y),new FlxPoint(x,y))/_radius; if(radial < 0) radial = 0; if(radial > 1) radial = 1; if(_pan) { var d:Number = (_target.x-x)/_radius; if(d < -1) d = -1; else if(d > 1) d = 1; _transform.pan = d; } } //Cross-fading volume control if(_fadeOutTimer > 0) { _fadeOutTimer -= FlxG.elapsed; if(_fadeOutTimer <= 0) { if(_pauseOnFadeOut) pause(); else stop(); } fade = _fadeOutTimer/_fadeOutTotal; if(fade < 0) fade = 0; } else if(_fadeInTimer > 0) { _fadeInTimer -= FlxG.elapsed; fade = _fadeInTimer/_fadeInTotal; if(fade < 0) fade = 0; fade = 1 - fade; } _volumeAdjust = radial*fade; updateTransform(); if((_transform.volume > 0) && (_channel != null)) { amplitudeLeft = _channel.leftPeak/_transform.volume; amplitudeRight = _channel.rightPeak/_transform.volume; amplitude = (amplitudeLeft+amplitudeRight)*0.5; } } override public function kill():void { super.kill(); if(_channel != null) stop(); } /** * One of two main setup functions for sounds, this function loads a sound from an embedded MP3. * * @param EmbeddedSound An embedded Class object representing an MP3 file. * @param Looped Whether or not this sound should loop endlessly. * @param AutoDestroy Whether or not this <code>FlxSound</code> instance should be destroyed when the sound finishes playing. Default value is false, but FlxG.play() and FlxG.stream() will set it to true by default. * * @return This <code>FlxSound</code> instance (nice for chaining stuff together, if you're into that). */ public function loadEmbedded(EmbeddedSound:Class, Looped:Boolean=false, AutoDestroy:Boolean=false):FlxSound { stop(); createSound(); _sound = new EmbeddedSound(); //NOTE: can't pull ID3 info from embedded sound currently _looped = Looped; updateTransform(); exists = true; return this; } /** * One of two main setup functions for sounds, this function loads a sound from a URL. * * @param EmbeddedSound A string representing the URL of the MP3 file you want to play. * @param Looped Whether or not this sound should loop endlessly. * @param AutoDestroy Whether or not this <code>FlxSound</code> instance should be destroyed when the sound finishes playing. Default value is false, but FlxG.play() and FlxG.stream() will set it to true by default. * * @return This <code>FlxSound</code> instance (nice for chaining stuff together, if you're into that). */ public function loadStream(SoundURL:String, Looped:Boolean=false, AutoDestroy:Boolean=false):FlxSound { stop(); createSound(); _sound = new Sound(); _sound.addEventListener(Event.ID3, gotID3); _sound.load(new URLRequest(SoundURL)); _looped = Looped; updateTransform(); exists = true; return this; } /** * Call this function if you want this sound's volume to change * based on distance from a particular FlxCore object. * * @param X The X position of the sound. * @param Y The Y position of the sound. * @param Object The object you want to track. * @param Radius The maximum distance this sound can travel. * @param Pan Whether the sound should pan in addition to the volume changes (default: true). * * @return This FlxSound instance (nice for chaining stuff together, if you're into that). */ public function proximity(X:Number,Y:Number,Object:FlxObject,Radius:Number,Pan:Boolean=true):FlxSound { x = X; y = Y; _target = Object; _radius = Radius; _pan = Pan; return this; } /** * Call this function to play the sound - also works on paused sounds. * * @param ForceRestart Whether to start the sound over or not. Default value is false, meaning if the sound is already playing or was paused when you call <code>play()</code>, it will continue playing from its current position, NOT start again from the beginning. */ public function play(ForceRestart:Boolean=false):void { if(_position < 0) return; if(ForceRestart) { var oldAutoDestroy:Boolean = autoDestroy; autoDestroy = false; stop(); autoDestroy = oldAutoDestroy; } if(_looped) { if(_position == 0) { if(_channel == null) _channel = _sound.play(0,9999,_transform); if(_channel == null) exists = false; } else { _channel = _sound.play(_position,0,_transform); if(_channel == null) exists = false; else _channel.addEventListener(Event.SOUND_COMPLETE, looped); } } else { if(_position == 0) { if(_channel == null) { _channel = _sound.play(0,0,_transform); if(_channel == null) exists = false; else _channel.addEventListener(Event.SOUND_COMPLETE, stopped); } } else { _channel = _sound.play(_position,0,_transform); if(_channel == null) exists = false; } } active = (_channel != null); _position = 0; } /** * Unpause a sound. Only works on sounds that have been paused. */ public function resume():void { if(_position <= 0) return; if(_looped) { _channel = _sound.play(_position,0,_transform); if(_channel == null) exists = false; else _channel.addEventListener(Event.SOUND_COMPLETE, looped); } else { _channel = _sound.play(_position,0,_transform); if(_channel == null) exists = false; } active = (_channel != null); } /** * Call this function to pause this sound. */ public function pause():void { if(_channel == null) { _position = -1; return; } _position = _channel.position; _channel.stop(); if(_looped) { while(_position >= _sound.length) _position -= _sound.length; } if(_position <= 0) _position = 1; _channel = null; active = false; } /** * Call this function to stop this sound. */ public function stop():void { _position = 0; if(_channel != null) { _channel.stop(); stopped(); } } /** * Call this function to make this sound fade out over a certain time interval. * * @param Seconds The amount of time the fade out operation should take. * @param PauseInstead Tells the sound to pause on fadeout, instead of stopping. */ public function fadeOut(Seconds:Number,PauseInstead:Boolean=false):void { _pauseOnFadeOut = PauseInstead; _fadeInTimer = 0; _fadeOutTimer = Seconds; _fadeOutTotal = _fadeOutTimer; } /** * Call this function to make a sound fade in over a certain * time interval (calls <code>play()</code> automatically). * * @param Seconds The amount of time the fade-in operation should take. */ public function fadeIn(Seconds:Number):void { _fadeOutTimer = 0; _fadeInTimer = Seconds; _fadeInTotal = _fadeInTimer; play(); } /** * Set <code>volume</code> to a value between 0 and 1 to change how this sound is. */ public function get volume():Number { return _volume; } /** * @private */ public function set volume(Volume:Number):void { _volume = Volume; if(_volume < 0) _volume = 0; else if(_volume > 1) _volume = 1; updateTransform(); } /** * Returns the currently selected "real" volume of the sound (takes fades and proximity into account). * * @return The adjusted volume of the sound. */ public function getActualVolume():Number { return _volume*_volumeAdjust; } /** * Call after adjusting the volume to update the sound channel's settings. */ internal function updateTransform():void { _transform.volume = (FlxG.mute?0:1)*FlxG.volume*_volume*_volumeAdjust; if(_channel != null) _channel.soundTransform = _transform; } /** * An internal helper function used to help Flash resume playing a looped sound. * * @param event An <code>Event</code> object. */ protected function looped(event:Event=null):void { if (_channel == null) return; _channel.removeEventListener(Event.SOUND_COMPLETE,looped); _channel = null; play(); } /** * An internal helper function used to help Flash clean up and re-use finished sounds. * * @param event An <code>Event</code> object. */ protected function stopped(event:Event=null):void { if(!_looped) _channel.removeEventListener(Event.SOUND_COMPLETE,stopped); else _channel.removeEventListener(Event.SOUND_COMPLETE,looped); _channel = null; active = false; if(autoDestroy) destroy(); } /** * Internal event handler for ID3 info (i.e. fetching the song name). * * @param event An <code>Event</code> object. */ protected function gotID3(event:Event=null):void { FlxG.log("got ID3 info!"); if(_sound.id3.songName.length > 0) name = _sound.id3.songName; if(_sound.id3.artist.length > 0) artist = _sound.id3.artist; _sound.removeEventListener(Event.ID3, gotID3); } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxSound.as
ActionScript
gpl3
13,801
package org.flixel { import flash.display.Graphics; import flash.display.Sprite; import flash.geom.Point; import org.flixel.FlxBasic; /** * This is the base class for most of the display objects (<code>FlxSprite</code>, <code>FlxText</code>, etc). * It includes some basic attributes about game objects, including retro-style flickering, * basic state information, sizes, scrolling, and basic physics and motion. * * @author Adam Atomic */ public class FlxObject extends FlxBasic { /** * Generic value for "left" Used by <code>facing</code>, <code>allowCollisions</code>, and <code>touching</code>. */ static public const LEFT:uint = 0x0001; /** * Generic value for "right" Used by <code>facing</code>, <code>allowCollisions</code>, and <code>touching</code>. */ static public const RIGHT:uint = 0x0010; /** * Generic value for "up" Used by <code>facing</code>, <code>allowCollisions</code>, and <code>touching</code>. */ static public const UP:uint = 0x0100; /** * Generic value for "down" Used by <code>facing</code>, <code>allowCollisions</code>, and <code>touching</code>. */ static public const DOWN:uint = 0x1000; /** * Special-case constant meaning no collisions, used mainly by <code>allowCollisions</code> and <code>touching</code>. */ static public const NONE:uint = 0; /** * Special-case constant meaning up, used mainly by <code>allowCollisions</code> and <code>touching</code>. */ static public const CEILING:uint= UP; /** * Special-case constant meaning down, used mainly by <code>allowCollisions</code> and <code>touching</code>. */ static public const FLOOR:uint = DOWN; /** * Special-case constant meaning only the left and right sides, used mainly by <code>allowCollisions</code> and <code>touching</code>. */ static public const WALL:uint = LEFT | RIGHT; /** * Special-case constant meaning any direction, used mainly by <code>allowCollisions</code> and <code>touching</code>. */ static public const ANY:uint = LEFT | RIGHT | UP | DOWN; /** * Handy constant used during collision resolution (see <code>separateX()</code> and <code>separateY()</code>). */ static public const OVERLAP_BIAS:Number = 4; /** * Path behavior controls: move from the start of the path to the end then stop. */ static public const PATH_FORWARD:uint = 0x000000; /** * Path behavior controls: move from the end of the path to the start then stop. */ static public const PATH_BACKWARD:uint = 0x000001; /** * Path behavior controls: move from the start of the path to the end then directly back to the start, and start over. */ static public const PATH_LOOP_FORWARD:uint = 0x000010; /** * Path behavior controls: move from the end of the path to the start then directly back to the end, and start over. */ static public const PATH_LOOP_BACKWARD:uint = 0x000100; /** * Path behavior controls: move from the start of the path to the end then turn around and go back to the start, over and over. */ static public const PATH_YOYO:uint = 0x001000; /** * Path behavior controls: ignores any vertical component to the path data, only follows side to side. */ static public const PATH_HORIZONTAL_ONLY:uint = 0x010000; /** * Path behavior controls: ignores any horizontal component to the path data, only follows up and down. */ static public const PATH_VERTICAL_ONLY:uint = 0x100000; /** * X position of the upper left corner of this object in world space. */ public var x:Number; /** * Y position of the upper left corner of this object in world space. */ public var y:Number; /** * The width of this object. */ public var width:Number; /** * The height of this object. */ public var height:Number; /** * Whether an object will move/alter position after a collision. */ public var immovable:Boolean; /** * The basic speed of this object. */ public var velocity:FlxPoint; /** * The virtual mass of the object. Default value is 1. * Currently only used with <code>elasticity</code> during collision resolution. * Change at your own risk; effects seem crazy unpredictable so far! */ public var mass:Number; /** * The bounciness of this object. Only affects collisions. Default value is 0, or "not bouncy at all." */ public var elasticity:Number; /** * How fast the speed of this object is changing. * Useful for smooth movement and gravity. */ public var acceleration:FlxPoint; /** * This isn't drag exactly, more like deceleration that is only applied * when acceleration is not affecting the sprite. */ public var drag:FlxPoint; /** * If you are using <code>acceleration</code>, you can use <code>maxVelocity</code> with it * to cap the speed automatically (very useful!). */ public var maxVelocity:FlxPoint; /** * Set the angle of a sprite to rotate it. * WARNING: rotating sprites decreases rendering * performance for this sprite by a factor of 10x! */ public var angle:Number; /** * This is how fast you want this sprite to spin. */ public var angularVelocity:Number; /** * How fast the spin speed should change. */ public var angularAcceleration:Number; /** * Like <code>drag</code> but for spinning. */ public var angularDrag:Number; /** * Use in conjunction with <code>angularAcceleration</code> for fluid spin speed control. */ public var maxAngular:Number; /** * Should always represent (0,0) - useful for different things, for avoiding unnecessary <code>new</code> calls. */ static protected const _pZero:FlxPoint = new FlxPoint(); /** * A point that can store numbers from 0 to 1 (for X and Y independently) * that governs how much this object is affected by the camera subsystem. * 0 means it never moves, like a HUD element or far background graphic. * 1 means it scrolls along a the same speed as the foreground layer. * scrollFactor is initialized as (1,1) by default. */ public var scrollFactor:FlxPoint; /** * Internal helper used for retro-style flickering. */ protected var _flicker:Boolean; /** * Internal helper used for retro-style flickering. */ protected var _flickerTimer:Number; /** * Handy for storing health percentage or armor points or whatever. */ public var health:Number; /** * This is just a pre-allocated x-y point container to be used however you like */ protected var _point:FlxPoint; /** * This is just a pre-allocated rectangle container to be used however you like */ protected var _rect:FlxRect; /** * Set this to false if you want to skip the automatic motion/movement stuff (see <code>updateMotion()</code>). * FlxObject and FlxSprite default to true. * FlxText, FlxTileblock, FlxTilemap and FlxSound default to false. */ public var moves:Boolean; /** * Bit field of flags (use with UP, DOWN, LEFT, RIGHT, etc) indicating surface contacts. * Use bitwise operators to check the values stored here, or use touching(), justStartedTouching(), etc. * You can even use them broadly as boolean values if you're feeling saucy! */ public var touching:uint; /** * Bit field of flags (use with UP, DOWN, LEFT, RIGHT, etc) indicating surface contacts from the previous game loop step. * Use bitwise operators to check the values stored here, or use touching(), justStartedTouching(), etc. * You can even use them broadly as boolean values if you're feeling saucy! */ public var wasTouching:uint; /** * Bit field of flags (use with UP, DOWN, LEFT, RIGHT, etc) indicating collision directions. * Use bitwise operators to check the values stored here. * Useful for things like one-way platforms (e.g. allowCollisions = UP;) * The accessor "solid" just flips this variable between NONE and ANY. */ public var allowCollisions:uint; /** * Important variable for collision processing. * By default this value is set automatically during <code>preUpdate()</code>. */ public var last:FlxPoint; /** * A reference to a path object. Null by default, assigned by <code>followPath()</code>. */ public var path:FlxPath; /** * The speed at which the object is moving on the path. * When an object completes a non-looping path circuit, * the pathSpeed will be zeroed out, but the <code>path</code> reference * will NOT be nulled out. So <code>pathSpeed</code> is a good way * to check if this object is currently following a path or not. */ public var pathSpeed:Number; /** * The angle in degrees between this object and the next node, where 0 is directly upward, and 90 is to the right. */ public var pathAngle:Number; /** * Internal helper, tracks which node of the path this object is moving toward. */ protected var _pathNodeIndex:int; /** * Internal tracker for path behavior flags (like looping, horizontal only, etc). */ protected var _pathMode:uint; /** * Internal helper for node navigation, specifically yo-yo and backwards movement. */ protected var _pathInc:int; /** * Internal flag for whether hte object's angle should be adjusted to the path angle during path follow behavior. */ protected var _pathRotate:Boolean; /** * Instantiates a <code>FlxObject</code>. * * @param X The X-coordinate of the point in space. * @param Y The Y-coordinate of the point in space. * @param Width Desired width of the rectangle. * @param Height Desired height of the rectangle. */ public function FlxObject(X:Number=0,Y:Number=0,Width:Number=0,Height:Number=0) { x = X; y = Y; last = new FlxPoint(x,y); width = Width; height = Height; mass = 1.0; elasticity = 0.0; immovable = false; moves = true; touching = NONE; wasTouching = NONE; allowCollisions = ANY; velocity = new FlxPoint(); acceleration = new FlxPoint(); drag = new FlxPoint(); maxVelocity = new FlxPoint(10000,10000); angle = 0; angularVelocity = 0; angularAcceleration = 0; angularDrag = 0; maxAngular = 10000; scrollFactor = new FlxPoint(1.0,1.0); _flicker = false; _flickerTimer = 0; _point = new FlxPoint(); _rect = new FlxRect(); path = null; pathSpeed = 0; pathAngle = 0; } /** * Override this function to null out variables or * manually call destroy() on class members if necessary. * Don't forget to call super.destroy()! */ override public function destroy():void { velocity = null; acceleration = null; drag = null; maxVelocity = null; scrollFactor = null; _point = null; _rect = null; last = null; cameras = null; if(path != null) path.destroy(); path = null; } /** * Pre-update is called right before <code>update()</code> on each object in the game loop. * In <code>FlxObject</code> it controls the flicker timer, * tracking the last coordinates for collision purposes, * and checking if the object is moving along a path or not. */ override public function preUpdate():void { _ACTIVECOUNT++; if(_flickerTimer != 0) { if(_flickerTimer > 0) { _flickerTimer = _flickerTimer - FlxG.elapsed; if(_flickerTimer <= 0) { _flickerTimer = 0; _flicker = false; } } } last.x = x; last.y = y; if((path != null) && (pathSpeed != 0) && (path.nodes[_pathNodeIndex] != null)) updatePathMotion(); } /** * Post-update is called right after <code>update()</code> on each object in the game loop. * In <code>FlxObject</code> this function handles integrating the objects motion * based on the velocity and acceleration settings, and tracking/clearing the <code>touching</code> flags. */ override public function postUpdate():void { if(moves) updateMotion(); wasTouching = touching; touching = NONE; } /** * Internal function for updating the position and speed of this object. * Useful for cases when you need to update this but are buried down in too many supers. * Does a slightly fancier-than-normal integration to help with higher fidelity framerate-independenct motion. */ protected function updateMotion():void { var delta:Number; var velocityDelta:Number; velocityDelta = (FlxU.computeVelocity(angularVelocity,angularAcceleration,angularDrag,maxAngular) - angularVelocity)/2; angularVelocity += velocityDelta; angle += angularVelocity*FlxG.elapsed; angularVelocity += velocityDelta; velocityDelta = (FlxU.computeVelocity(velocity.x,acceleration.x,drag.x,maxVelocity.x) - velocity.x)/2; velocity.x += velocityDelta; delta = velocity.x*FlxG.elapsed; velocity.x += velocityDelta; x += delta; velocityDelta = (FlxU.computeVelocity(velocity.y,acceleration.y,drag.y,maxVelocity.y) - velocity.y)/2; velocity.y += velocityDelta; delta = velocity.y*FlxG.elapsed; velocity.y += velocityDelta; y += delta; } /** * Rarely called, and in this case just increments the visible objects count and calls <code>drawDebug()</code> if necessary. */ override public function draw():void { if(cameras == null) cameras = FlxG.cameras; var camera:FlxCamera; var i:uint = 0; var l:uint = cameras.length; while(i < l) { camera = cameras[i++]; if(!onScreen(camera)) continue; _VISIBLECOUNT++; if(FlxG.visualDebug && !ignoreDrawDebug) drawDebug(camera); } } /** * Override this function to draw custom "debug mode" graphics to the * specified camera while the debugger's visual mode is toggled on. * * @param Camera Which camera to draw the debug visuals to. */ override public function drawDebug(Camera:FlxCamera=null):void { if(Camera == null) Camera = FlxG.camera; //get bounding box coordinates var boundingBoxX:Number = x - int(Camera.scroll.x*scrollFactor.x); //copied from getScreenXY() var boundingBoxY:Number = y - int(Camera.scroll.y*scrollFactor.y); boundingBoxX = int(boundingBoxX + ((boundingBoxX > 0)?0.0000001:-0.0000001)); boundingBoxY = int(boundingBoxY + ((boundingBoxY > 0)?0.0000001:-0.0000001)); var boundingBoxWidth:int = (width != int(width))?width:width-1; var boundingBoxHeight:int = (height != int(height))?height:height-1; //fill static graphics object with square shape var gfx:Graphics = FlxG.flashGfx; gfx.clear(); gfx.moveTo(boundingBoxX,boundingBoxY); var boundingBoxColor:uint; if(allowCollisions) { if(allowCollisions != ANY) boundingBoxColor = FlxG.PINK; if(immovable) boundingBoxColor = FlxG.GREEN; else boundingBoxColor = FlxG.RED; } else boundingBoxColor = FlxG.BLUE; gfx.lineStyle(1,boundingBoxColor,0.5); gfx.lineTo(boundingBoxX+boundingBoxWidth,boundingBoxY); gfx.lineTo(boundingBoxX+boundingBoxWidth,boundingBoxY+boundingBoxHeight); gfx.lineTo(boundingBoxX,boundingBoxY+boundingBoxHeight); gfx.lineTo(boundingBoxX,boundingBoxY); //draw graphics shape to camera buffer Camera.buffer.draw(FlxG.flashGfxSprite); } /** * Call this function to give this object a path to follow. * If the path does not have at least one node in it, this function * will log a warning message and return. * * @param Path The <code>FlxPath</code> you want this object to follow. * @param Speed How fast to travel along the path in pixels per second. * @param Mode Optional, controls the behavior of the object following the path using the path behavior constants. Can use multiple flags at once, for example PATH_YOYO|PATH_HORIZONTAL_ONLY will make an object move back and forth along the X axis of the path only. * @param AutoRotate Automatically point the object toward the next node. Assumes the graphic is pointing upward. Default behavior is false, or no automatic rotation. */ public function followPath(Path:FlxPath,Speed:Number=100,Mode:uint=PATH_FORWARD,AutoRotate:Boolean=false):void { if(Path.nodes.length <= 0) { FlxG.log("WARNING: Paths need at least one node in them to be followed."); return; } path = Path; pathSpeed = FlxU.abs(Speed); _pathMode = Mode; _pathRotate = AutoRotate; //get starting node if((_pathMode == PATH_BACKWARD) || (_pathMode == PATH_LOOP_BACKWARD)) { _pathNodeIndex = path.nodes.length-1; _pathInc = -1; } else { _pathNodeIndex = 0; _pathInc = 1; } } /** * Tells this object to stop following the path its on. * * @param DestroyPath Tells this function whether to call destroy on the path object. Default value is false. */ public function stopFollowingPath(DestroyPath:Boolean=false):void { pathSpeed = 0; if(DestroyPath && (path != null)) { path.destroy(); path = null; } } /** * Internal function that decides what node in the path to aim for next based on the behavior flags. * * @return The node (a <code>FlxPoint</code> object) we are aiming for next. */ protected function advancePath(Snap:Boolean=true):FlxPoint { if(Snap) { var oldNode:FlxPoint = path.nodes[_pathNodeIndex]; if(oldNode != null) { if((_pathMode & PATH_VERTICAL_ONLY) == 0) x = oldNode.x - width*0.5; if((_pathMode & PATH_HORIZONTAL_ONLY) == 0) y = oldNode.y - height*0.5; } } _pathNodeIndex += _pathInc; if((_pathMode & PATH_BACKWARD) > 0) { if(_pathNodeIndex < 0) { _pathNodeIndex = 0; pathSpeed = 0; } } else if((_pathMode & PATH_LOOP_FORWARD) > 0) { if(_pathNodeIndex >= path.nodes.length) _pathNodeIndex = 0; } else if((_pathMode & PATH_LOOP_BACKWARD) > 0) { if(_pathNodeIndex < 0) { _pathNodeIndex = path.nodes.length-1; if(_pathNodeIndex < 0) _pathNodeIndex = 0; } } else if((_pathMode & PATH_YOYO) > 0) { if(_pathInc > 0) { if(_pathNodeIndex >= path.nodes.length) { _pathNodeIndex = path.nodes.length-2; if(_pathNodeIndex < 0) _pathNodeIndex = 0; _pathInc = -_pathInc; } } else if(_pathNodeIndex < 0) { _pathNodeIndex = 1; if(_pathNodeIndex >= path.nodes.length) _pathNodeIndex = path.nodes.length-1; if(_pathNodeIndex < 0) _pathNodeIndex = 0; _pathInc = -_pathInc; } } else { if(_pathNodeIndex >= path.nodes.length) { _pathNodeIndex = path.nodes.length-1; pathSpeed = 0; } } return path.nodes[_pathNodeIndex]; } /** * Internal function for moving the object along the path. * Generally this function is called automatically by <code>preUpdate()</code>. * The first half of the function decides if the object can advance to the next node in the path, * while the second half handles actually picking a velocity toward the next node. */ protected function updatePathMotion():void { //first check if we need to be pointing at the next node yet _point.x = x + width*0.5; _point.y = y + height*0.5; var node:FlxPoint = path.nodes[_pathNodeIndex]; var deltaX:Number = node.x - _point.x; var deltaY:Number = node.y - _point.y; var horizontalOnly:Boolean = (_pathMode & PATH_HORIZONTAL_ONLY) > 0; var verticalOnly:Boolean = (_pathMode & PATH_VERTICAL_ONLY) > 0; if(horizontalOnly) { if(((deltaX>0)?deltaX:-deltaX) < pathSpeed*FlxG.elapsed) node = advancePath(); } else if(verticalOnly) { if(((deltaY>0)?deltaY:-deltaY) < pathSpeed*FlxG.elapsed) node = advancePath(); } else { if(Math.sqrt(deltaX*deltaX + deltaY*deltaY) < pathSpeed*FlxG.elapsed) node = advancePath(); } //then just move toward the current node at the requested speed if(pathSpeed != 0) { //set velocity based on path mode _point.x = x + width*0.5; _point.y = y + height*0.5; if(horizontalOnly || (_point.y == node.y)) { velocity.x = (_point.x < node.x)?pathSpeed:-pathSpeed; if(velocity.x < 0) pathAngle = -90; else pathAngle = 90; if(!horizontalOnly) velocity.y = 0; } else if(verticalOnly || (_point.x == node.x)) { velocity.y = (_point.y < node.y)?pathSpeed:-pathSpeed; if(velocity.y < 0) pathAngle = 0; else pathAngle = 180; if(!verticalOnly) velocity.x = 0; } else { pathAngle = FlxU.getAngle(_point,node); FlxU.rotatePoint(0,pathSpeed,0,0,pathAngle,velocity); } //then set object rotation if necessary if(_pathRotate) { angularVelocity = 0; angularAcceleration = 0; angle = pathAngle; } } } /** * Checks to see if some <code>FlxObject</code> overlaps this <code>FlxObject</code> or <code>FlxGroup</code>. * If the group has a LOT of things in it, it might be faster to use <code>FlxG.overlaps()</code>. * WARNING: Currently tilemaps do NOT support screen space overlap checks! * * @param ObjectOrGroup The object or group being tested. * @param InScreenSpace Whether to take scroll factors into account when checking for overlap. Default is false, or "only compare in world space." * @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera. * * @return Whether or not the two objects overlap. */ public function overlaps(ObjectOrGroup:FlxBasic,InScreenSpace:Boolean=false,Camera:FlxCamera=null):Boolean { if(ObjectOrGroup is FlxGroup) { var results:Boolean = false; var i:uint = 0; var members:Array = (ObjectOrGroup as FlxGroup).members; while(i < length) { if(overlaps(members[i++],InScreenSpace,Camera)) results = true; } return results; } if(ObjectOrGroup is FlxTilemap) { //Since tilemap's have to be the caller, not the target, to do proper tile-based collisions, // we redirect the call to the tilemap overlap here. return (ObjectOrGroup as FlxTilemap).overlaps(this,InScreenSpace,Camera); } var object:FlxObject = ObjectOrGroup as FlxObject; if(!InScreenSpace) { return (object.x + object.width > x) && (object.x < x + width) && (object.y + object.height > y) && (object.y < y + height); } if(Camera == null) Camera = FlxG.camera; var objectScreenPos:FlxPoint = object.getScreenXY(null,Camera); getScreenXY(_point,Camera); return (objectScreenPos.x + object.width > _point.x) && (objectScreenPos.x < _point.x + width) && (objectScreenPos.y + object.height > _point.y) && (objectScreenPos.y < _point.y + height); } /** * Checks to see if this <code>FlxObject</code> were located at the given position, would it overlap the <code>FlxObject</code> or <code>FlxGroup</code>? * This is distinct from overlapsPoint(), which just checks that point, rather than taking the object's size into account. * WARNING: Currently tilemaps do NOT support screen space overlap checks! * * @param X The X position you want to check. Pretends this object (the caller, not the parameter) is located here. * @param Y The Y position you want to check. Pretends this object (the caller, not the parameter) is located here. * @param ObjectOrGroup The object or group being tested. * @param InScreenSpace Whether to take scroll factors into account when checking for overlap. Default is false, or "only compare in world space." * @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera. * * @return Whether or not the two objects overlap. */ public function overlapsAt(X:Number,Y:Number,ObjectOrGroup:FlxBasic,InScreenSpace:Boolean=false,Camera:FlxCamera=null):Boolean { if(ObjectOrGroup is FlxGroup) { var results:Boolean = false; var basic:FlxBasic; var i:uint = 0; var members:Array = (ObjectOrGroup as FlxGroup).members; while(i < length) { if(overlapsAt(X,Y,members[i++],InScreenSpace,Camera)) results = true; } return results; } if(ObjectOrGroup is FlxTilemap) { //Since tilemap's have to be the caller, not the target, to do proper tile-based collisions, // we redirect the call to the tilemap overlap here. //However, since this is overlapsAt(), we also have to invent the appropriate position for the tilemap. //So we calculate the offset between the player and the requested position, and subtract that from the tilemap. var tilemap:FlxTilemap = ObjectOrGroup as FlxTilemap; return tilemap.overlapsAt(tilemap.x - (X - x),tilemap.y - (Y - y),this,InScreenSpace,Camera); } var object:FlxObject = ObjectOrGroup as FlxObject; if(!InScreenSpace) { return (object.x + object.width > X) && (object.x < X + width) && (object.y + object.height > Y) && (object.y < Y + height); } if(Camera == null) Camera = FlxG.camera; var objectScreenPos:FlxPoint = object.getScreenXY(null,Camera); _point.x = X - int(Camera.scroll.x*scrollFactor.x); //copied from getScreenXY() _point.y = Y - int(Camera.scroll.y*scrollFactor.y); _point.x += (_point.x > 0)?0.0000001:-0.0000001; _point.y += (_point.y > 0)?0.0000001:-0.0000001; return (objectScreenPos.x + object.width > _point.x) && (objectScreenPos.x < _point.x + width) && (objectScreenPos.y + object.height > _point.y) && (objectScreenPos.y < _point.y + height); } /** * Checks to see if a point in 2D world space overlaps this <code>FlxObject</code> object. * * @param Point The point in world space you want to check. * @param InScreenSpace Whether to take scroll factors into account when checking for overlap. * @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera. * * @return Whether or not the point overlaps this object. */ public function overlapsPoint(Point:FlxPoint,InScreenSpace:Boolean=false,Camera:FlxCamera=null):Boolean { if(!InScreenSpace) return (Point.x > x) && (Point.x < x + width) && (Point.y > y) && (Point.y < y + height); if(Camera == null) Camera = FlxG.camera; var X:Number = Point.x - Camera.scroll.x; var Y:Number = Point.y - Camera.scroll.y; getScreenXY(_point,Camera); return (X > _point.x) && (X < _point.x+width) && (Y > _point.y) && (Y < _point.y+height); } /** * Check and see if this object is currently on screen. * * @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera. * * @return Whether the object is on screen or not. */ public function onScreen(Camera:FlxCamera=null):Boolean { if(Camera == null) Camera = FlxG.camera; getScreenXY(_point,Camera); return (_point.x + width > 0) && (_point.x < Camera.width) && (_point.y + height > 0) && (_point.y < Camera.height); } /** * Call this function to figure out the on-screen position of the object. * * @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera. * @param Point Takes a <code>FlxPoint</code> object and assigns the post-scrolled X and Y values of this object to it. * * @return The <code>Point</code> you passed in, or a new <code>Point</code> if you didn't pass one, containing the screen X and Y position of this object. */ public function getScreenXY(Point:FlxPoint=null,Camera:FlxCamera=null):FlxPoint { if(Point == null) Point = new FlxPoint(); if(Camera == null) Camera = FlxG.camera; Point.x = x - int(Camera.scroll.x*scrollFactor.x); Point.y = y - int(Camera.scroll.y*scrollFactor.y); Point.x += (Point.x > 0)?0.0000001:-0.0000001; Point.y += (Point.y > 0)?0.0000001:-0.0000001; return Point; } /** * Tells this object to flicker, retro-style. * Pass a negative value to flicker forever. * * @param Duration How many seconds to flicker for. */ public function flicker(Duration:Number=1):void { _flickerTimer = Duration; if(_flickerTimer == 0) _flicker = false; } /** * Check to see if the object is still flickering. * * @return Whether the object is flickering or not. */ public function get flickering():Boolean { return _flickerTimer != 0; } /** * Whether the object collides or not. For more control over what directions * the object will collide from, use collision constants (like LEFT, FLOOR, etc) * to set the value of allowCollisions directly. */ public function get solid():Boolean { return (allowCollisions & ANY) > NONE; } /** * @private */ public function set solid(Solid:Boolean):void { if(Solid) allowCollisions = ANY; else allowCollisions = NONE; } /** * Retrieve the midpoint of this object in world coordinates. * * @Point Allows you to pass in an existing <code>FlxPoint</code> object if you're so inclined. Otherwise a new one is created. * * @return A <code>FlxPoint</code> object containing the midpoint of this object in world coordinates. */ public function getMidpoint(Point:FlxPoint=null):FlxPoint { if(Point == null) Point = new FlxPoint(); Point.x = x + width*0.5; Point.y = y + height*0.5; return Point; } /** * Handy function for reviving game objects. * Resets their existence flags and position. * * @param X The new X position of this object. * @param Y The new Y position of this object. */ public function reset(X:Number,Y:Number):void { revive(); touching = NONE; wasTouching = NONE; x = X; y = Y; last.x = x; last.y = y; velocity.x = 0; velocity.y = 0; } /** * Handy function for checking if this object is touching a particular surface. * For slightly better performance you can just &amp; the value directly into <code>touching</code>. * However, this method is good for readability and accessibility. * * @param Direction Any of the collision flags (e.g. LEFT, FLOOR, etc). * * @return Whether the object is touching an object in (any of) the specified direction(s) this frame. */ public function isTouching(Direction:uint):Boolean { return (touching & Direction) > NONE; } /** * Handy function for checking if this object is just landed on a particular surface. * * @param Direction Any of the collision flags (e.g. LEFT, FLOOR, etc). * * @return Whether the object just landed on (any of) the specified surface(s) this frame. */ public function justTouched(Direction:uint):Boolean { return ((touching & Direction) > NONE) && ((wasTouching & Direction) <= NONE); } /** * Reduces the "health" variable of this sprite by the amount specified in Damage. * Calls kill() if health drops to or below zero. * * @param Damage How much health to take away (use a negative number to give a health bonus). */ public function hurt(Damage:Number):void { health = health - Damage; if(health <= 0) kill(); } /** * The main collision resolution function in flixel. * * @param Object1 Any <code>FlxObject</code>. * @param Object2 Any other <code>FlxObject</code>. * * @return Whether the objects in fact touched and were separated. */ static public function separate(Object1:FlxObject, Object2:FlxObject):Boolean { var separatedX:Boolean = separateX(Object1,Object2); var separatedY:Boolean = separateY(Object1,Object2); return separatedX || separatedY; } /** * The X-axis component of the object separation process. * * @param Object1 Any <code>FlxObject</code>. * @param Object2 Any other <code>FlxObject</code>. * * @return Whether the objects in fact touched and were separated along the X axis. */ static public function separateX(Object1:FlxObject, Object2:FlxObject):Boolean { //can't separate two immovable objects var obj1immovable:Boolean = Object1.immovable; var obj2immovable:Boolean = Object2.immovable; if(obj1immovable && obj2immovable) return false; //If one of the objects is a tilemap, just pass it off. if(Object1 is FlxTilemap) return (Object1 as FlxTilemap).overlapsWithCallback(Object2,separateX); if(Object2 is FlxTilemap) return (Object2 as FlxTilemap).overlapsWithCallback(Object1,separateX,true); //First, get the two object deltas var overlap:Number = 0; var obj1delta:Number = Object1.x - Object1.last.x; var obj2delta:Number = Object2.x - Object2.last.x; if(obj1delta != obj2delta) { //Check if the X hulls actually overlap var obj1deltaAbs:Number = (obj1delta > 0)?obj1delta:-obj1delta; var obj2deltaAbs:Number = (obj2delta > 0)?obj2delta:-obj2delta; var obj1rect:FlxRect = new FlxRect(Object1.x-((obj1delta > 0)?obj1delta:0),Object1.last.y,Object1.width+((obj1delta > 0)?obj1delta:-obj1delta),Object1.height); var obj2rect:FlxRect = new FlxRect(Object2.x-((obj2delta > 0)?obj2delta:0),Object2.last.y,Object2.width+((obj2delta > 0)?obj2delta:-obj2delta),Object2.height); if((obj1rect.x + obj1rect.width > obj2rect.x) && (obj1rect.x < obj2rect.x + obj2rect.width) && (obj1rect.y + obj1rect.height > obj2rect.y) && (obj1rect.y < obj2rect.y + obj2rect.height)) { var maxOverlap:Number = obj1deltaAbs + obj2deltaAbs + OVERLAP_BIAS; //If they did overlap (and can), figure out by how much and flip the corresponding flags if(obj1delta > obj2delta) { overlap = Object1.x + Object1.width - Object2.x; if((overlap > maxOverlap) || !(Object1.allowCollisions & RIGHT) || !(Object2.allowCollisions & LEFT)) overlap = 0; else { Object1.touching |= RIGHT; Object2.touching |= LEFT; } } else if(obj1delta < obj2delta) { overlap = Object1.x - Object2.width - Object2.x; if((-overlap > maxOverlap) || !(Object1.allowCollisions & LEFT) || !(Object2.allowCollisions & RIGHT)) overlap = 0; else { Object1.touching |= LEFT; Object2.touching |= RIGHT; } } } } //Then adjust their positions and velocities accordingly (if there was any overlap) if(overlap != 0) { var obj1v:Number = Object1.velocity.x; var obj2v:Number = Object2.velocity.x; if(!obj1immovable && !obj2immovable) { overlap *= 0.5; Object1.x = Object1.x - overlap; Object2.x += overlap; var obj1velocity:Number = Math.sqrt((obj2v * obj2v * Object2.mass)/Object1.mass) * ((obj2v > 0)?1:-1); var obj2velocity:Number = Math.sqrt((obj1v * obj1v * Object1.mass)/Object2.mass) * ((obj1v > 0)?1:-1); var average:Number = (obj1velocity + obj2velocity)*0.5; obj1velocity -= average; obj2velocity -= average; Object1.velocity.x = average + obj1velocity * Object1.elasticity; Object2.velocity.x = average + obj2velocity * Object2.elasticity; } else if(!obj1immovable) { Object1.x = Object1.x - overlap; Object1.velocity.x = obj2v - obj1v*Object1.elasticity; } else if(!obj2immovable) { Object2.x += overlap; Object2.velocity.x = obj1v - obj2v*Object2.elasticity; } return true; } else return false; } /** * The Y-axis component of the object separation process. * * @param Object1 Any <code>FlxObject</code>. * @param Object2 Any other <code>FlxObject</code>. * * @return Whether the objects in fact touched and were separated along the Y axis. */ static public function separateY(Object1:FlxObject, Object2:FlxObject):Boolean { //can't separate two immovable objects var obj1immovable:Boolean = Object1.immovable; var obj2immovable:Boolean = Object2.immovable; if(obj1immovable && obj2immovable) return false; //If one of the objects is a tilemap, just pass it off. if(Object1 is FlxTilemap) return (Object1 as FlxTilemap).overlapsWithCallback(Object2,separateY); if(Object2 is FlxTilemap) return (Object2 as FlxTilemap).overlapsWithCallback(Object1,separateY,true); //First, get the two object deltas var overlap:Number = 0; var obj1delta:Number = Object1.y - Object1.last.y; var obj2delta:Number = Object2.y - Object2.last.y; if(obj1delta != obj2delta) { //Check if the Y hulls actually overlap var obj1deltaAbs:Number = (obj1delta > 0)?obj1delta:-obj1delta; var obj2deltaAbs:Number = (obj2delta > 0)?obj2delta:-obj2delta; var obj1rect:FlxRect = new FlxRect(Object1.x,Object1.y-((obj1delta > 0)?obj1delta:0),Object1.width,Object1.height+obj1deltaAbs); var obj2rect:FlxRect = new FlxRect(Object2.x,Object2.y-((obj2delta > 0)?obj2delta:0),Object2.width,Object2.height+obj2deltaAbs); if((obj1rect.x + obj1rect.width > obj2rect.x) && (obj1rect.x < obj2rect.x + obj2rect.width) && (obj1rect.y + obj1rect.height > obj2rect.y) && (obj1rect.y < obj2rect.y + obj2rect.height)) { var maxOverlap:Number = obj1deltaAbs + obj2deltaAbs + OVERLAP_BIAS; //If they did overlap (and can), figure out by how much and flip the corresponding flags if(obj1delta > obj2delta) { overlap = Object1.y + Object1.height - Object2.y; if((overlap > maxOverlap) || !(Object1.allowCollisions & DOWN) || !(Object2.allowCollisions & UP)) overlap = 0; else { Object1.touching |= DOWN; Object2.touching |= UP; } } else if(obj1delta < obj2delta) { overlap = Object1.y - Object2.height - Object2.y; if((-overlap > maxOverlap) || !(Object1.allowCollisions & UP) || !(Object2.allowCollisions & DOWN)) overlap = 0; else { Object1.touching |= UP; Object2.touching |= DOWN; } } } } //Then adjust their positions and velocities accordingly (if there was any overlap) if(overlap != 0) { var obj1v:Number = Object1.velocity.y; var obj2v:Number = Object2.velocity.y; if(!obj1immovable && !obj2immovable) { overlap *= 0.5; Object1.y = Object1.y - overlap; Object2.y += overlap; var obj1velocity:Number = Math.sqrt((obj2v * obj2v * Object2.mass)/Object1.mass) * ((obj2v > 0)?1:-1); var obj2velocity:Number = Math.sqrt((obj1v * obj1v * Object1.mass)/Object2.mass) * ((obj1v > 0)?1:-1); var average:Number = (obj1velocity + obj2velocity)*0.5; obj1velocity -= average; obj2velocity -= average; Object1.velocity.y = average + obj1velocity * Object1.elasticity; Object2.velocity.y = average + obj2velocity * Object2.elasticity; } else if(!obj1immovable) { Object1.y = Object1.y - overlap; Object1.velocity.y = obj2v - obj1v*Object1.elasticity; //This is special case code that handles cases like horizontal moving platforms you can ride if(Object2.active && Object2.moves && (obj1delta > obj2delta)) Object1.x += Object2.x - Object2.last.x; } else if(!obj2immovable) { Object2.y += overlap; Object2.velocity.y = obj1v - obj2v*Object2.elasticity; //This is special case code that handles cases like horizontal moving platforms you can ride if(Object1.active && Object1.moves && (obj1delta < obj2delta)) Object2.x += Object1.x - Object1.last.x; } return true; } else return false; } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxObject.as
ActionScript
gpl3
39,662
package org.flixel { import flash.display.BitmapData; import flash.display.Graphics; import flash.display.Sprite; import flash.display.Stage; import flash.geom.Matrix; import flash.geom.Point; import flash.geom.Rectangle; import org.flixel.plugin.DebugPathDisplay; import org.flixel.plugin.TimerManager; import org.flixel.system.FlxDebugger; import org.flixel.system.FlxQuadTree; import org.flixel.system.input.*; /** * This is a global helper class full of useful functions for audio, * input, basic info, and the camera system among other things. * Utilities for maths and color and things can be found in <code>FlxU</code>. * <code>FlxG</code> is specifically for Flixel-specific properties. * * @author Adam Atomic */ public class FlxG { /** * If you build and maintain your own version of flixel, * you can give it your own name here. */ static public var LIBRARY_NAME:String = "flixel"; /** * Assign a major version to your library. * Appears before the decimal in the console. */ static public var LIBRARY_MAJOR_VERSION:uint = 2; /** * Assign a minor version to your library. * Appears after the decimal in the console. */ static public var LIBRARY_MINOR_VERSION:uint = 55; /** * Debugger overlay layout preset: Wide but low windows at the bottom of the screen. */ static public const DEBUGGER_STANDARD:uint = 0; /** * Debugger overlay layout preset: Tiny windows in the screen corners. */ static public const DEBUGGER_MICRO:uint = 1; /** * Debugger overlay layout preset: Large windows taking up bottom half of screen. */ static public const DEBUGGER_BIG:uint = 2; /** * Debugger overlay layout preset: Wide but low windows at the top of the screen. */ static public const DEBUGGER_TOP:uint = 3; /** * Debugger overlay layout preset: Large windows taking up left third of screen. */ static public const DEBUGGER_LEFT:uint = 4; /** * Debugger overlay layout preset: Large windows taking up right third of screen. */ static public const DEBUGGER_RIGHT:uint = 5; /** * Some handy color presets. Less glaring than pure RGB full values. * Primarily used in the visual debugger mode for bounding box displays. * Red is used to indicate an active, movable, solid object. */ static public const RED:uint = 0xffff0012; /** * Green is used to indicate solid but immovable objects. */ static public const GREEN:uint = 0xff00f225; /** * Blue is used to indicate non-solid objects. */ static public const BLUE:uint = 0xff0090e9; /** * Pink is used to indicate objects that are only partially solid, like one-way platforms. */ static public const PINK:uint = 0xfff01eff; /** * White... for white stuff. */ static public const WHITE:uint = 0xffffffff; /** * And black too. */ static public const BLACK:uint = 0xff000000; /** * Internal tracker for game object. */ static internal var _game:FlxGame; /** * Handy shared variable for implementing your own pause behavior. */ static public var paused:Boolean; /** * Whether you are running in Debug or Release mode. * Set automatically by <code>FlxPreloader</code> during startup. */ static public var debug:Boolean; /** * Represents the amount of time in seconds that passed since last frame. */ static public var elapsed:Number; /** * How fast or slow time should pass in the game; default is 1.0. */ static public var timeScale:Number; /** * The width of the screen in game pixels. */ static public var width:uint; /** * The height of the screen in game pixels. */ static public var height:uint; /** * The dimensions of the game world, used by the quad tree for collisions and overlap checks. */ static public var worldBounds:FlxRect; /** * How many times the quad tree should divide the world on each axis. * Generally, sparse collisions can have fewer divisons, * while denser collision activity usually profits from more. * Default value is 6. */ static public var worldDivisions:uint; /** * Whether to show visual debug displays or not. * Default = false. */ static public var visualDebug:Boolean; /** * Setting this to true will disable/skip stuff that isn't necessary for mobile platforms like Android. [BETA] */ static public var mobile:Boolean; /** * The global random number generator seed (for deterministic behavior in recordings and saves). */ static public var globalSeed:Number; /** * <code>FlxG.levels</code> and <code>FlxG.scores</code> are generic * global variables that can be used for various cross-state stuff. */ static public var levels:Array; static public var level:int; static public var scores:Array; static public var score:int; /** * <code>FlxG.saves</code> is a generic bucket for storing * FlxSaves so you can access them whenever you want. */ static public var saves:Array; static public var save:int; /** * A reference to a <code>FlxMouse</code> object. Important for input! */ static public var mouse:Mouse; /** * A reference to a <code>FlxKeyboard</code> object. Important for input! */ static public var keys:Keyboard; /** * A handy container for a background music object. */ static public var music:FlxSound; /** * A list of all the sounds being played in the game. */ static public var sounds:FlxGroup; /** * Whether or not the game sounds are muted. */ static public var mute:Boolean; /** * Internal volume level, used for global sound control. */ static protected var _volume:Number; /** * An array of <code>FlxCamera</code> objects that are used to draw stuff. * By default flixel creates one camera the size of the screen. */ static public var cameras:Array; /** * By default this just refers to the first entry in the cameras array * declared above, but you can do what you like with it. */ static public var camera:FlxCamera; /** * Allows you to possibly slightly optimize the rendering process IF * you are not doing any pre-processing in your game state's <code>draw()</code> call. * @default false */ static public var useBufferLocking:Boolean; /** * Internal helper variable for clearing the cameras each frame. */ static protected var _cameraRect:Rectangle; /** * An array container for plugins. * By default flixel uses a couple of plugins: * DebugPathDisplay, and TimerManager. */ static public var plugins:Array; /** * Set this hook to get a callback whenever the volume changes. * Function should take the form <code>myVolumeHandler(Volume:Number)</code>. */ static public var volumeHandler:Function; /** * Useful helper objects for doing Flash-specific rendering. * Primarily used for "debug visuals" like drawing bounding boxes directly to the screen buffer. */ static public var flashGfxSprite:Sprite; static public var flashGfx:Graphics; /** * Internal storage system to prevent graphics from being used repeatedly in memory. */ static protected var _cache:Object; static public function getLibraryName():String { return FlxG.LIBRARY_NAME + " v" + FlxG.LIBRARY_MAJOR_VERSION + "." + FlxG.LIBRARY_MINOR_VERSION; } /** * Log data to the debugger. * * @param Data Anything you want to log to the console. */ static public function log(Data:Object):void { if((_game != null) && (_game._debugger != null)) _game._debugger.log.add((Data == null)?"ERROR: null object":Data.toString()); } /** * Add a variable to the watch list in the debugger. * This lets you see the value of the variable all the time. * * @param AnyObject A reference to any object in your game, e.g. Player or Robot or this. * @param VariableName The name of the variable you want to watch, in quotes, as a string: e.g. "speed" or "health". * @param DisplayName Optional, display your own string instead of the class name + variable name: e.g. "enemy count". */ static public function watch(AnyObject:Object,VariableName:String,DisplayName:String=null):void { if((_game != null) && (_game._debugger != null)) _game._debugger.watch.add(AnyObject,VariableName,DisplayName); } /** * Remove a variable from the watch list in the debugger. * Don't pass a Variable Name to remove all watched variables for the specified object. * * @param AnyObject A reference to any object in your game, e.g. Player or Robot or this. * @param VariableName The name of the variable you want to watch, in quotes, as a string: e.g. "speed" or "health". */ static public function unwatch(AnyObject:Object,VariableName:String=null):void { if((_game != null) && (_game._debugger != null)) _game._debugger.watch.remove(AnyObject,VariableName); } /** * How many times you want your game to update each second. * More updates usually means better collisions and smoother motion. * NOTE: This is NOT the same thing as the Flash Player framerate! */ static public function get framerate():Number { return 1000/_game._step; } /** * @private */ static public function set framerate(Framerate:Number):void { _game._step = 1000/Framerate; if(_game._maxAccumulation < _game._step) _game._maxAccumulation = _game._step; } /** * How many times you want your game to update each second. * More updates usually means better collisions and smoother motion. * NOTE: This is NOT the same thing as the Flash Player framerate! */ static public function get flashFramerate():Number { if(_game.root != null) return _game.stage.frameRate; else return 0; } /** * @private */ static public function set flashFramerate(Framerate:Number):void { _game._flashFramerate = Framerate; if(_game.root != null) _game.stage.frameRate = _game._flashFramerate; _game._maxAccumulation = 2000/_game._flashFramerate - 1; if(_game._maxAccumulation < _game._step) _game._maxAccumulation = _game._step; } /** * Generates a random number. Deterministic, meaning safe * to use if you want to record replays in random environments. * * @return A <code>Number</code> between 0 and 1. */ static public function random():Number { return globalSeed = FlxU.srand(globalSeed); } /** * Shuffles the entries in an array into a new random order. * <code>FlxG.shuffle()</code> is deterministic and safe for use with replays/recordings. * HOWEVER, <code>FlxU.shuffle()</code> is NOT deterministic and unsafe for use with replays/recordings. * * @param A A Flash <code>Array</code> object containing...stuff. * @param HowManyTimes How many swaps to perform during the shuffle operation. Good rule of thumb is 2-4 times as many objects are in the list. * * @return The same Flash <code>Array</code> object that you passed in in the first place. */ static public function shuffle(Objects:Array,HowManyTimes:uint):Array { var i:uint = 0; var index1:uint; var index2:uint; var object:Object; while(i < HowManyTimes) { index1 = FlxG.random()*Objects.length; index2 = FlxG.random()*Objects.length; object = Objects[index2]; Objects[index2] = Objects[index1]; Objects[index1] = object; i++; } return Objects; } /** * Fetch a random entry from the given array. * Will return null if random selection is missing, or array has no entries. * <code>FlxG.getRandom()</code> is deterministic and safe for use with replays/recordings. * HOWEVER, <code>FlxU.getRandom()</code> is NOT deterministic and unsafe for use with replays/recordings. * * @param Objects A Flash array of objects. * @param StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. * @param Length Optional restriction on the number of values you want to randomly select from. * * @return The random object that was selected. */ static public function getRandom(Objects:Array,StartIndex:uint=0,Length:uint=0):Object { if(Objects != null) { var l:uint = Length; if((l == 0) || (l > Objects.length - StartIndex)) l = Objects.length - StartIndex; if(l > 0) return Objects[StartIndex + uint(FlxG.random()*l)]; } return null; } /** * Load replay data from a string and play it back. * * @param Data The replay that you want to load. * @param State Optional parameter: if you recorded a state-specific demo or cutscene, pass a new instance of that state here. * @param CancelKeys Optional parameter: an array of string names of keys (see FlxKeyboard) that can be pressed to cancel the playback, e.g. ["ESCAPE","ENTER"]. Also accepts 2 custom key names: "ANY" and "MOUSE" (fairly self-explanatory I hope!). * @param Timeout Optional parameter: set a time limit for the replay. CancelKeys will override this if pressed. * @param Callback Optional parameter: if set, called when the replay finishes. Running to the end, CancelKeys, and Timeout will all trigger Callback(), but only once, and CancelKeys and Timeout will NOT call FlxG.stopReplay() if Callback is set! */ static public function loadReplay(Data:String,State:FlxState=null,CancelKeys:Array=null,Timeout:Number=0,Callback:Function=null):void { _game._replay.load(Data); if(State == null) FlxG.resetGame(); else FlxG.switchState(State); _game._replayCancelKeys = CancelKeys; _game._replayTimer = Timeout*1000; _game._replayCallback = Callback; _game._replayRequested = true; } /** * Resets the game or state and replay requested flag. * * @param StandardMode If true, reload entire game, else just reload current game state. */ static public function reloadReplay(StandardMode:Boolean=true):void { if(StandardMode) FlxG.resetGame(); else FlxG.resetState(); if(_game._replay.frameCount > 0) _game._replayRequested = true; } /** * Stops the current replay. */ static public function stopReplay():void { _game._replaying = false; if(_game._debugger != null) _game._debugger.vcr.stopped(); resetInput(); } /** * Resets the game or state and requests a new recording. * * @param StandardMode If true, reset the entire game, else just reset the current state. */ static public function recordReplay(StandardMode:Boolean=true):void { if(StandardMode) FlxG.resetGame(); else FlxG.resetState(); _game._recordingRequested = true; } /** * Stop recording the current replay and return the replay data. * * @return The replay data in simple ASCII format (see <code>FlxReplay.save()</code>). */ static public function stopRecording():String { _game._recording = false; if(_game._debugger != null) _game._debugger.vcr.stopped(); return _game._replay.save(); } /** * Request a reset of the current game state. */ static public function resetState():void { _game._requestedState = new (FlxU.getClass(FlxU.getClassName(_game._state,false)))(); } /** * Like hitting the reset button on a game console, this will re-launch the game as if it just started. */ static public function resetGame():void { _game._requestedReset = true; } /** * Reset the input helper objects (useful when changing screens or states) */ static public function resetInput():void { keys.reset(); mouse.reset(); } /** * Set up and play a looping background soundtrack. * * @param Music The sound file you want to loop in the background. * @param Volume How loud the sound should be, from 0 to 1. */ static public function playMusic(Music:Class,Volume:Number=1.0):void { if(music == null) music = new FlxSound(); else if(music.active) music.stop(); music.loadEmbedded(Music,true); music.volume = Volume; music.survive = true; music.play(); } /** * Creates a new sound object. * * @param EmbeddedSound The embedded sound resource you want to play. To stream, use the optional URL parameter instead. * @param Volume How loud to play it (0 to 1). * @param Looped Whether to loop this sound. * @param AutoDestroy Whether to destroy this sound when it finishes playing. Leave this value set to "false" if you want to re-use this <code>FlxSound</code> instance. * @param AutoPlay Whether to play the sound. * @param URL Load a sound from an external web resource instead. Only used if EmbeddedSound = null. * * @return A <code>FlxSound</code> object. */ static public function loadSound(EmbeddedSound:Class=null,Volume:Number=1.0,Looped:Boolean=false,AutoDestroy:Boolean=false,AutoPlay:Boolean=false,URL:String=null):FlxSound { if((EmbeddedSound == null) && (URL == null)) { FlxG.log("WARNING: FlxG.loadSound() requires either\nan embedded sound or a URL to work."); return null; } var sound:FlxSound = sounds.recycle(FlxSound) as FlxSound; if(EmbeddedSound != null) sound.loadEmbedded(EmbeddedSound,Looped,AutoDestroy); else sound.loadStream(URL,Looped,AutoDestroy); sound.volume = Volume; if(AutoPlay) sound.play(); return sound; } /** * Creates a new sound object from an embedded <code>Class</code> object. * NOTE: Just calls FlxG.loadSound() with AutoPlay == true. * * @param EmbeddedSound The sound you want to play. * @param Volume How loud to play it (0 to 1). * @param Looped Whether to loop this sound. * @param AutoDestroy Whether to destroy this sound when it finishes playing. Leave this value set to "false" if you want to re-use this <code>FlxSound</code> instance. * * @return A <code>FlxSound</code> object. */ static public function play(EmbeddedSound:Class,Volume:Number=1.0,Looped:Boolean=false,AutoDestroy:Boolean=true):FlxSound { return FlxG.loadSound(EmbeddedSound,Volume,Looped,AutoDestroy,true); } /** * Creates a new sound object from a URL. * NOTE: Just calls FlxG.loadSound() with AutoPlay == true. * * @param URL The URL of the sound you want to play. * @param Volume How loud to play it (0 to 1). * @param Looped Whether or not to loop this sound. * @param AutoDestroy Whether to destroy this sound when it finishes playing. Leave this value set to "false" if you want to re-use this <code>FlxSound</code> instance. * * @return A FlxSound object. */ static public function stream(URL:String,Volume:Number=1.0,Looped:Boolean=false,AutoDestroy:Boolean=true):FlxSound { return FlxG.loadSound(null,Volume,Looped,AutoDestroy,true,URL); } /** * Set <code>volume</code> to a number between 0 and 1 to change the global volume. * * @default 0.5 */ static public function get volume():Number { return _volume; } /** * @private */ static public function set volume(Volume:Number):void { _volume = Volume; if(_volume < 0) _volume = 0; else if(_volume > 1) _volume = 1; if(volumeHandler != null) volumeHandler(FlxG.mute?0:_volume); } /** * Called by FlxGame on state changes to stop and destroy sounds. * * @param ForceDestroy Kill sounds even if they're flagged <code>survive</code>. */ static internal function destroySounds(ForceDestroy:Boolean=false):void { if((music != null) && (ForceDestroy || !music.survive)) { music.destroy(); music = null; } var i:uint = 0; var sound:FlxSound; var l:uint = sounds.members.length; while(i < l) { sound = sounds.members[i++] as FlxSound; if((sound != null) && (ForceDestroy || !sound.survive)) sound.destroy(); } } /** * Called by the game loop to make sure the sounds get updated each frame. */ static internal function updateSounds():void { if((music != null) && music.active) music.update(); if((sounds != null) && sounds.active) sounds.update(); } /** * Pause all sounds currently playing. */ static public function pauseSounds():void { if((music != null) && music.exists && music.active) music.pause(); var i:uint = 0; var sound:FlxSound; var l:uint = sounds.length; while(i < l) { sound = sounds.members[i++] as FlxSound; if((sound != null) && sound.exists && sound.active) sound.pause(); } } /** * Resume playing existing sounds. */ static public function resumeSounds():void { if((music != null) && music.exists) music.play(); var i:uint = 0; var sound:FlxSound; var l:uint = sounds.length; while(i < l) { sound = sounds.members[i++] as FlxSound; if((sound != null) && sound.exists) sound.resume(); } } /** * Check the local bitmap cache to see if a bitmap with this key has been loaded already. * * @param Key The string key identifying the bitmap. * * @return Whether or not this file can be found in the cache. */ static public function checkBitmapCache(Key:String):Boolean { return (_cache[Key] != undefined) && (_cache[Key] != null); } /** * Generates a new <code>BitmapData</code> object (a colored square) and caches it. * * @param Width How wide the square should be. * @param Height How high the square should be. * @param Color What color the square should be (0xAARRGGBB) * @param Unique Ensures that the bitmap data uses a new slot in the cache. * @param Key Force the cache to use a specific Key to index the bitmap. * * @return The <code>BitmapData</code> we just created. */ static public function createBitmap(Width:uint, Height:uint, Color:uint, Unique:Boolean=false, Key:String=null):BitmapData { if(Key == null) { Key = Width+"x"+Height+":"+Color; if(Unique && checkBitmapCache(Key)) { var inc:uint = 0; var ukey:String; do { ukey = Key + inc++; } while(checkBitmapCache(ukey)); Key = ukey; } } if(!checkBitmapCache(Key)) _cache[Key] = new BitmapData(Width,Height,true,Color); return _cache[Key]; } /** * Loads a bitmap from a file, caches it, and generates a horizontally flipped version if necessary. * * @param Graphic The image file that you want to load. * @param Reverse Whether to generate a flipped version. * @param Unique Ensures that the bitmap data uses a new slot in the cache. * @param Key Force the cache to use a specific Key to index the bitmap. * * @return The <code>BitmapData</code> we just created. */ static public function addBitmap(Graphic:Class, Reverse:Boolean=false, Unique:Boolean=false, Key:String=null):BitmapData { var needReverse:Boolean = false; if(Key == null) { Key = String(Graphic)+(Reverse?"_REVERSE_":""); if(Unique && checkBitmapCache(Key)) { var inc:uint = 0; var ukey:String; do { ukey = Key + inc++; } while(checkBitmapCache(ukey)); Key = ukey; } } //If there is no data for this key, generate the requested graphic if(!checkBitmapCache(Key)) { _cache[Key] = (new Graphic).bitmapData; if(Reverse) needReverse = true; } var pixels:BitmapData = _cache[Key]; if(!needReverse && Reverse && (pixels.width == (new Graphic).bitmapData.width)) needReverse = true; if(needReverse) { var newPixels:BitmapData = new BitmapData(pixels.width<<1,pixels.height,true,0x00000000); newPixels.draw(pixels); var mtx:Matrix = new Matrix(); mtx.scale(-1,1); mtx.translate(newPixels.width,0); newPixels.draw(pixels,mtx); pixels = newPixels; _cache[Key] = pixels; } return pixels; } /** * Dumps the cache's image references. */ static public function clearBitmapCache():void { _cache = new Object(); } /** * Read-only: retrieves the Flash stage object (required for event listeners) * Will be null if it's not safe/useful yet. */ static public function get stage():Stage { if(_game.root != null) return _game.stage; return null; } /** * Read-only: access the current game state from anywhere. */ static public function get state():FlxState { return _game._state; } /** * Switch from the current game state to the one specified here. */ static public function switchState(State:FlxState):void { _game._requestedState = State; } /** * Change the way the debugger's windows are laid out. * * @param Layout See the presets above (e.g. <code>DEBUGGER_MICRO</code>, etc). */ static public function setDebuggerLayout(Layout:uint):void { if(_game._debugger != null) _game._debugger.setLayout(Layout); } /** * Just resets the debugger windows to whatever the last selected layout was (<code>DEBUGGER_STANDARD</code> by default). */ static public function resetDebuggerLayout():void { if(_game._debugger != null) _game._debugger.resetLayout(); } /** * Add a new camera object to the game. * Handy for PiP, split-screen, etc. * * @param NewCamera The camera you want to add. * * @return This <code>FlxCamera</code> instance. */ static public function addCamera(NewCamera:FlxCamera):FlxCamera { FlxG._game.addChildAt(NewCamera._flashSprite,FlxG._game.getChildIndex(FlxG._game._mouse)); FlxG.cameras.push(NewCamera); return NewCamera; } /** * Remove a camera from the game. * * @param Camera The camera you want to remove. * @param Destroy Whether to call destroy() on the camera, default value is true. */ static public function removeCamera(Camera:FlxCamera,Destroy:Boolean=true):void { try { FlxG._game.removeChild(Camera._flashSprite); } catch(E:Error) { FlxG.log("Error removing camera, not part of game."); } if(Destroy) Camera.destroy(); } /** * Dumps all the current cameras and resets to just one camera. * Handy for doing split-screen especially. * * @param NewCamera Optional; specify a specific camera object to be the new main camera. */ static public function resetCameras(NewCamera:FlxCamera=null):void { var cam:FlxCamera; var i:uint = 0; var l:uint = cameras.length; while(i < l) { cam = FlxG.cameras[i++] as FlxCamera; FlxG._game.removeChild(cam._flashSprite); cam.destroy(); } FlxG.cameras.length = 0; if(NewCamera == null) NewCamera = new FlxCamera(0,0,FlxG.width,FlxG.height) FlxG.camera = FlxG.addCamera(NewCamera); } /** * All screens are filled with this color and gradually return to normal. * * @param Color The color you want to use. * @param Duration How long it takes for the flash to fade. * @param OnComplete A function you want to run when the flash finishes. * @param Force Force the effect to reset. */ static public function flash(Color:uint=0xffffffff, Duration:Number=1, OnComplete:Function=null, Force:Boolean=false):void { var i:uint = 0; var l:uint = FlxG.cameras.length; while(i < l) (FlxG.cameras[i++] as FlxCamera).flash(Color,Duration,OnComplete,Force); } /** * The screen is gradually filled with this color. * * @param Color The color you want to use. * @param Duration How long it takes for the fade to finish. * @param OnComplete A function you want to run when the fade finishes. * @param Force Force the effect to reset. */ static public function fade(Color:uint=0xff000000, Duration:Number=1, OnComplete:Function=null, Force:Boolean=false):void { var i:uint = 0; var l:uint = FlxG.cameras.length; while(i < l) (FlxG.cameras[i++] as FlxCamera).fade(Color,Duration,OnComplete,Force); } /** * A simple screen-shake effect. * * @param Intensity Percentage of screen size representing the maximum distance that the screen can move while shaking. * @param Duration The length in seconds that the shaking effect should last. * @param OnComplete A function you want to run when the shake effect finishes. * @param Force Force the effect to reset (default = true, unlike flash() and fade()!). * @param Direction Whether to shake on both axes, just up and down, or just side to side (use class constants SHAKE_BOTH_AXES, SHAKE_VERTICAL_ONLY, or SHAKE_HORIZONTAL_ONLY). Default value is SHAKE_BOTH_AXES (0). */ static public function shake(Intensity:Number=0.05, Duration:Number=0.5, OnComplete:Function=null, Force:Boolean=true, Direction:uint=0):void { var i:uint = 0; var l:uint = FlxG.cameras.length; while(i < l) (FlxG.cameras[i++] as FlxCamera).shake(Intensity,Duration,OnComplete,Force,Direction); } /** * Get and set the background color of the game. * Get functionality is equivalent to FlxG.camera.bgColor. * Set functionality sets the background color of all the current cameras. */ static public function get bgColor():uint { if(FlxG.camera == null) return 0xff000000; else return FlxG.camera.bgColor; } static public function set bgColor(Color:uint):void { var i:uint = 0; var l:uint = FlxG.cameras.length; while(i < l) (FlxG.cameras[i++] as FlxCamera).bgColor = Color; } /** * Call this function to see if one <code>FlxObject</code> overlaps another. * Can be called with one object and one group, or two groups, or two objects, * whatever floats your boat! For maximum performance try bundling a lot of objects * together using a <code>FlxGroup</code> (or even bundling groups together!). * * <p>NOTE: does NOT take objects' scrollfactor into account, all overlaps are checked in world space.</p> * * @param ObjectOrGroup1 The first object or group you want to check. * @param ObjectOrGroup2 The second object or group you want to check. If it is the same as the first, flixel knows to just do a comparison within that group. * @param NotifyCallback A function with two <code>FlxObject</code> parameters - e.g. <code>myOverlapFunction(Object1:FlxObject,Object2:FlxObject)</code> - that is called if those two objects overlap. * @param ProcessCallback A function with two <code>FlxObject</code> parameters - e.g. <code>myOverlapFunction(Object1:FlxObject,Object2:FlxObject)</code> - that is called if those two objects overlap. If a ProcessCallback is provided, then NotifyCallback will only be called if ProcessCallback returns true for those objects! * * @return Whether any oevrlaps were detected. */ static public function overlap(ObjectOrGroup1:FlxBasic=null,ObjectOrGroup2:FlxBasic=null,NotifyCallback:Function=null,ProcessCallback:Function=null):Boolean { if(ObjectOrGroup1 == null) ObjectOrGroup1 = FlxG.state; if(ObjectOrGroup2 === ObjectOrGroup1) ObjectOrGroup2 = null; FlxQuadTree.divisions = FlxG.worldDivisions; var quadTree:FlxQuadTree = new FlxQuadTree(FlxG.worldBounds.x,FlxG.worldBounds.y,FlxG.worldBounds.width,FlxG.worldBounds.height); quadTree.load(ObjectOrGroup1,ObjectOrGroup2,NotifyCallback,ProcessCallback); var result:Boolean = quadTree.execute(); quadTree.destroy(); return result; } /** * Call this function to see if one <code>FlxObject</code> collides with another. * Can be called with one object and one group, or two groups, or two objects, * whatever floats your boat! For maximum performance try bundling a lot of objects * together using a <code>FlxGroup</code> (or even bundling groups together!). * * <p>This function just calls FlxG.overlap and presets the ProcessCallback parameter to FlxObject.separate. * To create your own collision logic, write your own ProcessCallback and use FlxG.overlap to set it up.</p> * * <p>NOTE: does NOT take objects' scrollfactor into account, all overlaps are checked in world space.</p> * * @param ObjectOrGroup1 The first object or group you want to check. * @param ObjectOrGroup2 The second object or group you want to check. If it is the same as the first, flixel knows to just do a comparison within that group. * @param NotifyCallback A function with two <code>FlxObject</code> parameters - e.g. <code>myOverlapFunction(Object1:FlxObject,Object2:FlxObject)</code> - that is called if those two objects overlap. * * @return Whether any objects were successfully collided/separated. */ static public function collide(ObjectOrGroup1:FlxBasic=null, ObjectOrGroup2:FlxBasic=null, NotifyCallback:Function=null):Boolean { return overlap(ObjectOrGroup1,ObjectOrGroup2,NotifyCallback,FlxObject.separate); } /** * Adds a new plugin to the global plugin array. * * @param Plugin Any object that extends FlxBasic. Useful for managers and other things. See org.flixel.plugin for some examples! * * @return The same <code>FlxBasic</code>-based plugin you passed in. */ static public function addPlugin(Plugin:FlxBasic):FlxBasic { //Don't add repeats var pluginList:Array = FlxG.plugins; var i:uint = 0; var l:uint = pluginList.length; while(i < l) { if(pluginList[i++].toString() == Plugin.toString()) return Plugin; } //no repeats! safe to add a new instance of this plugin pluginList.push(Plugin); return Plugin; } /** * Retrieves a plugin based on its class name from the global plugin array. * * @param ClassType The class name of the plugin you want to retrieve. See the <code>FlxPath</code> or <code>FlxTimer</code> constructors for example usage. * * @return The plugin object, or null if no matching plugin was found. */ static public function getPlugin(ClassType:Class):FlxBasic { var pluginList:Array = FlxG.plugins; var i:uint = 0; var l:uint = pluginList.length; while(i < l) { if(pluginList[i] is ClassType) return plugins[i]; i++; } return null; } /** * Removes an instance of a plugin from the global plugin array. * * @param Plugin The plugin instance you want to remove. * * @return The same <code>FlxBasic</code>-based plugin you passed in. */ static public function removePlugin(Plugin:FlxBasic):FlxBasic { //Don't add repeats var pluginList:Array = FlxG.plugins; var i:int = pluginList.length-1; while(i >= 0) { if(pluginList[i] == Plugin) pluginList.splice(i,1); i--; } return Plugin; } /** * Removes an instance of a plugin from the global plugin array. * * @param ClassType The class name of the plugin type you want removed from the array. * * @return Whether or not at least one instance of this plugin type was removed. */ static public function removePluginType(ClassType:Class):Boolean { //Don't add repeats var results:Boolean = false; var pluginList:Array = FlxG.plugins; var i:int = pluginList.length-1; while(i >= 0) { if(pluginList[i] is ClassType) { pluginList.splice(i,1); results = true; } i--; } return results; } /** * Called by <code>FlxGame</code> to set up <code>FlxG</code> during <code>FlxGame</code>'s constructor. */ static internal function init(Game:FlxGame,Width:uint,Height:uint,Zoom:Number):void { FlxG._game = Game; FlxG.width = Width; FlxG.height = Height; FlxG.mute = false; FlxG._volume = 0.5; FlxG.sounds = new FlxGroup(); FlxG.volumeHandler = null; FlxG.clearBitmapCache(); if(flashGfxSprite == null) { flashGfxSprite = new Sprite(); flashGfx = flashGfxSprite.graphics; } FlxCamera.defaultZoom = Zoom; FlxG._cameraRect = new Rectangle(); FlxG.cameras = new Array(); useBufferLocking = false; plugins = new Array(); addPlugin(new DebugPathDisplay()); addPlugin(new TimerManager()); FlxG.mouse = new Mouse(FlxG._game._mouse); FlxG.keys = new Keyboard(); FlxG.mobile = false; FlxG.levels = new Array(); FlxG.scores = new Array(); FlxG.visualDebug = false; } /** * Called whenever the game is reset, doesn't have to do quite as much work as the basic initialization stuff. */ static internal function reset():void { FlxG.clearBitmapCache(); FlxG.resetInput(); FlxG.destroySounds(true); FlxG.levels.length = 0; FlxG.scores.length = 0; FlxG.level = 0; FlxG.score = 0; FlxG.paused = false; FlxG.timeScale = 1.0; FlxG.elapsed = 0; FlxG.globalSeed = Math.random(); FlxG.worldBounds = new FlxRect(-10,-10,FlxG.width+20,FlxG.height+20); FlxG.worldDivisions = 6; var debugPathDisplay:DebugPathDisplay = FlxG.getPlugin(DebugPathDisplay) as DebugPathDisplay; if(debugPathDisplay != null) debugPathDisplay.clear(); } /** * Called by the game object to update the keyboard and mouse input tracking objects. */ static internal function updateInput():void { FlxG.keys.update(); if(!_game._debuggerUp || !_game._debugger.hasMouse) FlxG.mouse.update(FlxG._game.mouseX,FlxG._game.mouseY); } /** * Called by the game object to lock all the camera buffers and clear them for the next draw pass. */ static internal function lockCameras():void { var cam:FlxCamera; var cams:Array = FlxG.cameras; var i:uint = 0; var l:uint = cams.length; while(i < l) { cam = cams[i++] as FlxCamera; if((cam == null) || !cam.exists || !cam.visible) continue; if(useBufferLocking) cam.buffer.lock(); cam.fill(cam.bgColor); cam.screen.dirty = true; } } /** * Called by the game object to draw the special FX and unlock all the camera buffers. */ static internal function unlockCameras():void { var cam:FlxCamera; var cams:Array = FlxG.cameras; var i:uint = 0; var l:uint = cams.length; while(i < l) { cam = cams[i++] as FlxCamera; if((cam == null) || !cam.exists || !cam.visible) continue; cam.drawFX(); if(useBufferLocking) cam.buffer.unlock(); } } /** * Called by the game object to update the cameras and their tracking/special effects logic. */ static internal function updateCameras():void { var cam:FlxCamera; var cams:Array = FlxG.cameras; var i:uint = 0; var l:uint = cams.length; while(i < l) { cam = cams[i++] as FlxCamera; if((cam != null) && cam.exists) { if(cam.active) cam.update(); cam._flashSprite.x = cam.x + cam._flashOffsetX; cam._flashSprite.y = cam.y + cam._flashOffsetY; cam._flashSprite.visible = cam.visible; } } } /** * Used by the game object to call <code>update()</code> on all the plugins. */ static internal function updatePlugins():void { var plugin:FlxBasic; var pluginList:Array = FlxG.plugins; var i:uint = 0; var l:uint = pluginList.length; while(i < l) { plugin = pluginList[i++] as FlxBasic; if(plugin.exists && plugin.active) plugin.update(); } } /** * Used by the game object to call <code>draw()</code> on all the plugins. */ static internal function drawPlugins():void { var plugin:FlxBasic; var pluginList:Array = FlxG.plugins; var i:uint = 0; var l:uint = pluginList.length; while(i < l) { plugin = pluginList[i++] as FlxBasic; if(plugin.exists && plugin.visible) plugin.draw(); } } } }
05-may-1gam-blocks-that-grow
trunk/lib/Flixel/org/flixel/FlxG.as
ActionScript
gpl3
39,625
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation indicating that this parameter CANNOT be null. */ @Retention(RetentionPolicy.SOURCE) @Target( { ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD } ) public @interface NonNull { }
110165172-description
TimeriSample/LibAnnot/src/main/java/com/rdrrlabs/example/annotations/NonNull.java
Java
gpl3
1,132
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation indicating the visibility of the method has been * relaxed so that we can access it in unit tests. */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.METHOD) public @interface PublicForTesting { }
110165172-description
TimeriSample/LibAnnot/src/main/java/com/rdrrlabs/example/annotations/PublicForTesting.java
Java
gpl3
1,145
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation indicating that this parameter can be null. */ @Retention(RetentionPolicy.SOURCE) @Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD, ElementType.LOCAL_VARIABLE }) public @interface Null { }
110165172-description
TimeriSample/LibAnnot/src/main/java/com/rdrrlabs/example/annotations/Null.java
Java
gpl3
1,151
#!/bin/bash # # Copyright (C) 2013 rdrrlabs gmail com, # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # if [[ $(uname -o) == "Cygwin" ]]; then function wrap_py27_exec() { P=$(cygpath -w "$(readlink -f $(dirname "$0"))/dev_appserver.py") GAE_HOST="0.0.0.0" cmd.exe /C "c:\Python27\python.exe" "$P" --log_level debug --host $GAE_HOST --admin_host $GAE_HOST $* src } else # Linux function wrap_py27_exec() { P=$(readlink -f $(dirname "$0"))/dev_appserver.py GAE_HOST="0.0.0.0" $P --log_level debug --host $GAE_HOST --admin_host $GAE_HOST $* src && echo "[+EXIT] code $?" || echo "[-EXIT] code $?" } fi . ./_wrap_py27.sh
110165172-description
TimeriSample/TimeriGo/_run.sh
Shell
gpl3
1,287
#!/bin/bash # # Copyright (C) 2013 rdrrlabs gmail com, # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # export CMD_ARGS="" export VERB="test" if [[ "$1" == "-i" ]]; then export CMD_ARGS="-i" shift fi if [[ -z "$1" ]]; then export PKGS=$(find src -name "*_test.go" | sed -e 's@src/@@' -e 's@/[a-z0-9_-]\+_test.go$@@' | sort | uniq) fi if [[ $(uname -o) == "Cygwin" ]]; then export GOPATH=$(cygpath -w "$PWD") else export GOPATH="$PWD" fi # Linux function wrap_py27_exec() { # remove the AE go version from the path GOAE=~/google/go_appengine PATH=${PATH/$GOAE:/} # add the default one if [[ -x ~/go/bin/go ]]; then export PATH=~/go/bin/go:$PATH echo "[PATH] remove go_appengine, add regular go" #--echo "[PATH] Changed to $PATH" fi echo go $VERB -v $CMD_ARGS $* $PKGS go $VERB -v $CMD_ARGS $* $PKGS && echo "[+EXIT] code $?" || echo "[-EXIT] code $?" } . ./_wrap_py27.sh
110165172-description
TimeriSample/TimeriGo/_test.sh
Shell
gpl3
1,546
# # Copyright (C) 2013 rdrrlabs gmail com, # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # if [[ "${PATH/go_appengine/}" == "$PATH" ]]; then echo "[PATH] add go_appengine" export PATH=~/google/go_appengine:"$PATH" fi function mk_link() { if [[ $(readlink $1) != ~/google/go_appengine/$1 ]]; then echo "[Links] adding $1" ln -sfv ~/google/go_appengine/$1 . fi } mk_link appcfg.py mk_link dev_appserver.py
110165172-description
TimeriSample/TimeriGo/_set_go_path.sh
Shell
gpl3
1,042
/** * Created with IntelliJ IDEA. * User: raphael * Date: 4/8/13 * Time: 10:45 PM * To change this template use File | Settings | File Templates. */ package main import "fmt" func main() { fmt.Printf("Hello world!") }
110165172-description
TimeriSample/TimeriGo/src/main.go
Go
gpl3
227
<!-- /* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ --> <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="timeriGCMTable"> <thead><tr> <th>RegID</th> <th>Created</th> <th>Expires</th> </tr></thead> <tbody /> </table> <table><tr><td style="vertical-align: top; padding-right: 10px"> <p><button class="btn" id="timeriGCMRefreshButton" onClick="timeriGCMRefresh()">Refresh</button></p> <p><button class="btn" id="timeriGCMDeleteButton" onClick="timeriGCMDelete()" disabled="disabled">Delete...</button></p> </td><td style="vertical-align: top; border-left: 1px dotted lightgray; padding-left: 10px"> Timer GCM details here... </td></tr></table>
110165172-description
TimeriSample/TimeriGo/src/serv/gcm_template.html
HTML
gpl3
1,364
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package serv import ( "appengine" "appengine/user" "fmt" "html/template" "log" "net/http" "strings" "time" ) func init() { http.HandleFunc("/", handleBootstrapRoot) } func Choice(b bool, a1, a2 int) int { if b { return a1 } return a2 } //------------------------------ var mBootstrapTemplate *template.Template func handleBootstrapRoot(w http.ResponseWriter, r *http.Request) { var err error startTS := time.Now() log.SetPrefix("## serv: ") c := appengine.NewContext(r) u := user.Current(c) _path := r.URL.Path // DEBUG log.Printf("## ROOT %v, path='%v', query='%v'", r.Method, _path, r.URL.RawQuery) type tabInfo struct { Title string URL string Active string // "active" for the current tab handler } // Data for filling the main page HTML template var data struct { Email string UserTooltip string SignLink string LogoutLink string Timestamp string AppVersion string ErrStr string Tabs []tabInfo TabName string TabContent template.HTML TabPathJS string } // Find whether user is signed, compute sign-in or log-out links isSigned := false if u == nil { url, err := user.LoginURL(c, r.URL.String()) if err != nil { log.Println("## user.LoginURL failed: ", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } data.SignLink = url; } else { isSigned = true url, err := user.LogoutURL(c, r.URL.String()) if err != nil { log.Println("## user.LogoutURL failed: ", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } data.Email = u.Email data.LogoutLink = url } // Find our db user info to get groups, adjust if user is admin var accessInfo = FetchAccessInfo(c, u) var isAdmin = isSigned && user.IsAdmin(c) if isAdmin { // Users marked as admin in the AppEngine console have view + create rights too accessInfo.Add(GroupAdmin) accessInfo.Add(GroupView) accessInfo.Add(GroupCreate) } if accessInfo.Groups != nil { data.UserTooltip = "Groups: " + strings.Join(accessInfo.Groups, ", ") if isAdmin { data.UserTooltip += " [GA]" } } returnCode := http.StatusInternalServerError // Find the request handler for the current request, depending on user group. urlBase, urlRest, handler, err := FindRequestHandler(r, isSigned, &accessInfo) if handler != nil { if handler.Handler().Is(HandlerIsTab) { // This is a handler for a UI tab. We'll display the main UI template. log.Printf("## UI-tab match found for %v %v => %v", r.Method, urlBase, urlRest) data.TabContent = handler.CreateTab(r, c, &accessInfo) data.Tabs = make([]tabInfo, 0) for _, h := range FindHandlers(r, true, isSigned, &accessInfo) { ti := tabInfo { h.Handler().Title, h.Handler().URL, "" } if h == handler { ti.Active = "active" data.TabPathJS = "timeri" + strings.Replace(h.Handler().Title, " ", "", -1) data.TabName = h.Handler().Title } data.Tabs = append(data.Tabs, ti) // DEBUG log.Printf("## Add UI Tab: %v", ti) } err = nil returnCode = http.StatusOK } else { // This is a handler for a UI-less request (e.g. Ajax, etc.) log.Printf("## UI-less match found for %v %v => %v", r.Method, urlBase, urlRest) returnCode, err = handler.ProcessRequest(w, r, c, &accessInfo, urlBase, urlRest) if err != nil { if returnCode == http.StatusOK { returnCode = http.StatusInternalServerError } log.Printf("## HTTP Reply with [%d] '%s'", returnCode, err.Error()) http.Error(w, err.Error(), returnCode) } else if returnCode > 0 { w.WriteHeader(returnCode) } return } } data.Timestamp = fmt.Sprintf("%v \u2014 \u0394 %v", time.Now().Format("2006-01-02 15:04:05"), time.Since(startTS)) data.AppVersion = "v" + appengine.VersionID(c) if isAdmin { data.AppVersion += " | " + appengine.ServerSoftware() } if err != nil && isAdmin { // For admins, display errors if any data.ErrStr = err.Error() } if mBootstrapTemplate == nil { mBootstrapTemplate = template.Must(template.New("serv_bootstrap.html").ParseFiles("serv/serv_bootstrap.html")) } err = mBootstrapTemplate.Execute(w, data) if err != nil { http.Error(w, err.Error(), returnCode) } }
110165172-description
TimeriSample/TimeriGo/src/serv/serv_bootstrap.go
Go
gpl3
5,750
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package serv import ( "appengine" "appengine/datastore" "appengine/user" "strings" ) //------------------------------ const kAccessKind = "access" const ( GroupAdmin = "admin" GroupView = "view" GroupCreate = "create" ) var ValidGroups = map[string] bool { GroupAdmin : true, GroupView : true, GroupCreate : true, } // Structure stored in AppEngine's datastore type AccessInfo struct { Email string `crud:"key"` Groups []string `datastore:",noindex"` } func (u AccessInfo) ToJsonTable() []string { // Converts a DataStore entity (the one matching DsStruct) into an array of strings // matching the fields expected in the CRUD html data table. return []string { u.Email, u.GroupsString() } } func (u AccessInfo) GroupsString() string { return strings.Join(u.Groups, ", ") } func (u *AccessInfo) Is(group string) bool { if u.Groups != nil && len(u.Groups) > 0 { for _, g := range u.Groups { if g == group { return true } } } return false } func (u *AccessInfo) Add(group string) { if !u.Is(group) { u.Groups = append(u.Groups, group) } } func FetchAccessInfo(c appengine.Context, u *user.User) (info AccessInfo) { if u != nil { key := datastore.NewKey(c, kAccessKind, u.Email, 0, nil) if err := datastore.Get(c, key, &info); err != nil { // Default is to return a user with no valid group. return AccessInfo { Email: u.Email } } } return } //------------------------------
110165172-description
TimeriSample/TimeriGo/src/serv/access.go
Go
gpl3
2,331
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package serv import ( "appengine" "appengine/datastore" "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "html/template" "log" "net/http" "net/url" "reflect" "strconv" "strings" "time" ) //------------------------------ // "callbacks" implemented by "derived" cruders type Cruder interface { // Register handlers specific to that cruder (typicall the main view page) RegisterHandlers(ci *CrudInfo, handlers Handlers) Handlers // --- ui tab --- // Return true if it's OK to create a UI tab page for this request. CanCreateTab(p *CrudHandler, r *http.Request, c appengine.Context, a *AccessInfo) bool // --- get list --- // --- add/edit --- // Validates and prepare an add/edit request (a PUT/POST). // - values: the parameters given by the UI POST. // - entity: the struct to place in the datastore. MUST be consistent with the DsStruct type and // one of the fields must marked with the tag `crud:"key"` // - err: an optional error. nil on success. Will be part of the HTTP response, so no PII. ValidateAdd(values url.Values) (entity Datastorer, err error) } // Optional interface that Cruder can implement to use ProcessRequest // on non-Crud requests. type CruderProcessRequester interface { // Process UI-less request ProcessRequest(w http.ResponseWriter, r *http.Request, c appengine.Context, a *AccessInfo, urlBase string, urlRest string) (httpCode int, err error) } // The struct type for AppEngine datastore must implement this interface. // One field should have the tag `crud:"key"` type Datastorer interface { // Converts a DataStore entity into an array of strings matching // the fields expected in the CRUD html data table. ToJsonTable() []string } // info struct for the generic crud code type CrudInfo struct { Name string // e.g. "Name", the capitalized title of the pages BaseUrl string // e.g. "/a" will convert to "/a/get" Kind string // e.g. "name", the lower-case AppEngine datastore kind (str) TemplateName string // e.g. "name_template.html", based on the lower-case name DsStruct Datastorer // the struct type for AppEngine datastore; one field should have the tag `crud:"key"` Cruder } // bridge between page/request handlers and the generic crud type CrudHandler struct { *HandlerDesc *CrudInfo } // Creates a new Crud struct. Caller should call RegisterHandlers on it later. func NewCrud(name, baseUrl string, dsStruct Datastorer, c Cruder) *CrudInfo { kname := strings.ToLower(name) kname = strings.Replace(kname, " ", "_", -1) ci := &CrudInfo { Cruder: c, Name: name, BaseUrl: baseUrl, Kind: kname, TemplateName: kname + "_template.html", DsStruct: dsStruct, } return ci } func (ci *CrudInfo) RegisterHandlers(handlers Handlers) Handlers { desc := &HandlerDesc { Title: ci.Name, URL: ci.BaseUrl + "/get", Flags: HandlerIsSigned, Groups: []string { GroupView, GroupAdmin } } handlers = append(handlers, &CrudHandler { desc, ci }) desc = &HandlerDesc { Title: ci.Name, URL: ci.BaseUrl + "/set", Flags: HandlerIsSigned | HandlerIsPost, Groups: []string { GroupView, GroupAdmin } } handlers = append(handlers, &CrudHandler { desc, ci }) desc = &HandlerDesc { Title: ci.Name, URL: ci.BaseUrl + "/del", Flags: HandlerIsSigned | HandlerIsDelete, Groups: []string { GroupView, GroupAdmin } } handlers = append(handlers, &CrudHandler { desc, ci }) return ci.Cruder.RegisterHandlers(ci, handlers) } func (p *CrudHandler) Handler() *HandlerDesc { return p.HandlerDesc } //------------------------------ var mTemplateCrudMap = map[string]*template.Template {} func (p *CrudHandler) CreateTab(r *http.Request, c appengine.Context, a *AccessInfo) template.HTML { ci := p.CrudInfo if !ci.Cruder.CanCreateTab(p, r, c, a) { return template.HTML(`<em>These are not the droids you are looking for.</em>`) } t, ok := mTemplateCrudMap[ci.Name] if !ok { t = template.Must(template.New(ci.TemplateName).ParseFiles("serv/" + ci.TemplateName)) mTemplateCrudMap[ci.Name] = t } var buf bytes.Buffer err := t.Execute(&buf, struct { Title string } { p.Handler().Title } ) if err == nil { return template.HTML(buf.String()) } return template.HTML("internal tab template error: " + err.Error()) } //------------------------------ // Note: made public for unit-tests type CrudEntityLoadSaver struct { Value reflect.Value } // implement type PropertyLoadSaver interface func (e *CrudEntityLoadSaver) Load(c<-chan datastore.Property) error { // Load means we consume datastore Properties and fill the crud-client struct // specified in e.Value // vdst is the destination struct. tdst is its type. vdst := e.Value if vdst.Kind() == reflect.Ptr { vdst = vdst.Elem() } tdst := vdst.Type() vname := tdst.Name() if vdst.Kind() != reflect.Struct { panic(fmt.Sprintf("CRUD Prop Loader [%s]: type %v found, struct was expected.", vname, vdst.Kind())) } errStr := "" for p := range c { name := p.Name vsrc := p.Value tsrc := reflect.TypeOf(vsrc) mult := p.Multiple // requires slice //--log.Printf("[CrudEntityLoadSaver.load] %v => %#v -- mult: %v\n", name, vsrc, mult) // Check dst has the field name var fv reflect.Value for i := 0; i < vdst.NumField(); i++ { // TODO dst type can have "datastore" field tags to rename their fields fs := tdst.Field(i) // reflect.StructField tag := strings.Split(fs.Tag.Get("datastore"), ",") fname := fs.Name if len(tag) > 0 && tag[0] != "" { fname = tag[0] if fname == "-" { // datastore tag says to skip this field name //--log.Printf("##DEBUG LOAD skip field name %v with tag %v", fs.Name, tag) continue } } if name == fname { // fv is the value of the destination struct field. ft is its type. fv = vdst.Field(i) break } } if !fv.IsValid() { errStr += fmt.Sprintf("CRUD Prop Loader [%s]: No matching field found in %v\n", vname, name) } ft := fv.Type() isSlice := ft.Kind() == reflect.Slice if isSlice != mult { // Warn+Ignore the mismatch errStr += fmt.Sprintf("CRUD Prop Loader [%s.%s]: src is slice, dst is %v\n", vname, name, ft.Kind()) } else if !fv.CanSet() { // Warn+Ignore errStr += fmt.Sprintf("CRUD Prop Loader [%s.%s]: dst is not setable\n", vname, name) } else { // load into the field or the slice var vslice reflect.Value if isSlice { // A slice is represented by a serie of Property on the same name. // Just create a new value on the slice and set it below. // Note: new returns a Ptr to the requested type, use Elem() to dereference. vptr := reflect.New(ft.Elem()) // We'll now update a new element, not the slice itself. // We'll update the slice only at the end on success. vslice = fv fv = vptr.Elem() ft = fv.Type() } // Assign to dest value. We don't support all the Property.Value types. mismatch := false switch ft.Kind() { case reflect.Bool: if s, ok := vsrc.(bool); ok { fv.SetBool(s) } else { mismatch = true } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: // datastore property type is an int64. Might overflow when set. if s, ok := vsrc.(int64); ok { fv.SetInt(s) } else { mismatch = true } case reflect.Float32, reflect.Float64: // datastore property type is a float64. Might overflow when set. if s, ok := vsrc.(float64); ok { fv.SetFloat(s) } else { mismatch = true } case reflect.String: // Could be an actual "short" string or a datastore BlobKey if s, ok := vsrc.(appengine.BlobKey); ok { fv.SetString(string(s)) break } if s, ok := p.Value.(string); ok { fv.SetString(s) } else { mismatch = true } case reflect.Struct: // Only struct we support is time.Time if s, ok := vsrc.(time.Time); ok { fv.Set(reflect.ValueOf(s)) } else { mismatch = true } case reflect.Slice, reflect.Ptr: // TODO implement later if useful. // slice would map to a []byte for a binary blob errStr += fmt.Sprintf("CRUD Prop Loader [%s.%s]: Not-implemented-yet struct type %v", vname, name, ft.Name()) isSlice = false // prevent from adding to current slice if any. } if (mismatch) { errStr += fmt.Sprintf("CRUD Prop Loader [%s.%s]: datastore type %v incompatible with struct type %v", vname, name, tsrc.Name(), ft.Name()) } else if isSlice { // If it's a slice, add the new element to the slice vslice.Set(reflect.Append(vslice, fv)) } } } if errStr != "" { return errors.New(errStr) } return nil } func (e *CrudEntityLoadSaver) Save(c chan<- datastore.Property) error { // Save means we consume the crud-client struct specified in e.Value // and produce datastore Properties. // Important: we need to close the channel in all conditions on exit. defer close(c) vsrc := e.Value //--log.Printf("##DEBUG SAVER vsrc: %#v", vsrc) if vsrc.Kind() == reflect.Ptr { vsrc = vsrc.Elem() } //--log.Printf("##DEBUG SAVER vsrc: %#v", vsrc) if vsrc.Kind() == reflect.Interface { vsrc = vsrc.Elem() } //--log.Printf("##DEBUG SAVER vsrc: %#v", vsrc) tsrc := vsrc.Type() vname := tsrc.Name() if vsrc.Kind() != reflect.Struct { panic(fmt.Sprintf("CRUD Prop Saver [%s]: type %v found, struct was expected.", vname, vsrc.Kind())) } errStr := "" for i := 0; i < vsrc.NumField(); i++ { fs := tsrc.Field(i) // reflect.StructField (aka field descriptor) tag := strings.Split(fs.Tag.Get("datastore"), ",") // src type can have "datastore" field tags to rename their fields name := fs.Name if len(tag) > 0 && tag[0] != "" { name = tag[0] if name == "-" { // datastore tag says to skip this field name //--log.Printf("##DEBUG SAVE skip field name %v with tag %v", fs.Name, tag) continue } } // fv is the value of the source struct field. ft is its type. fv := vsrc.Field(i) ft := fv.Type() if !fv.IsValid() { errStr += fmt.Sprintf("CRUD Prop Saver [%s.%s]: Invalid field %v\n", vname, name, ft.Name()) continue } p := datastore.Property{ Name: name, NoIndex: len(tag) == 2 && tag[1] == "noindex", Multiple: false, } if fv.Kind() == reflect.Slice { p.Multiple = true for j := 0; j < fv.Len(); j++ { v := fv.Index(j) //--log.Printf("##DEBUG Slice[%v], kind %v, %v", j, v.Kind(), v) p.Value = nil switch v.Interface().(type) { case appengine.BlobKey: p.Value = v case time.Time: p.Value = v case []byte: p.NoIndex = true p.Value = v default: switch v.Kind() { case reflect.Bool: p.Value = v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: p.Value = v.Int() case reflect.Float32, reflect.Float64: p.Value = v.Float() case reflect.String: p.Value = v.String() } } if p.Value == nil { errStr += fmt.Sprintf("CRUD Prop Saver [%s.%s]: Unsupported slice type %v\n", vname, name, ft.Name()) break } else { //--log.Printf("##DEBUG SAVE slice %#v", p) c <- p } } } else { switch fv.Interface().(type) { case appengine.BlobKey: p.Value = fv case []byte: p.NoIndex = true p.Value = fv default: switch fv.Kind() { case reflect.Bool: p.Value = fv.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: p.Value = fv.Int() case reflect.Float32, reflect.Float64: p.Value = fv.Float() case reflect.String: p.Value = fv.String() } } if p.Value == nil { errStr += fmt.Sprintf("CRUD Prop Saver [%s.%s]: Unsupported type %v\n", vname, name, ft.Name()) } else { //--log.Printf("##DEBUG SAVE value %#v", p) c <- p } } } if errStr != "" { return errors.New(errStr) } return nil } //------------------------------ func (p *CrudHandler) ProcessRequest(w http.ResponseWriter, r *http.Request, c appengine.Context, a *AccessInfo, urlBase string, urlRest string) (httpCode int, err error) { ci := p.CrudInfo if r.Method == "GET" && urlBase == ci.BaseUrl + "/get" { return p.processJsonGetList(w, r, c, a) } else if r.Method == "POST" && urlBase == ci.BaseUrl + "/set" { return p.processJsonAdd(w, r, c, a, urlRest) } else if r.Method == "DELETE" && urlBase == ci.BaseUrl + "/del" { return p.processJsonDel(w, r, c, a, urlRest) } else if pr, ok := ci.Cruder.(CruderProcessRequester); ok { return pr.ProcessRequest(w, r, c, a, urlBase, urlRest) } return http.StatusNotFound, nil } // Returns the first struct field with a tag `crud:"key"`. // If the interface is nil, defaults to CrudInfo.DsStruct which has zero value. func (ci *CrudInfo) GetCrudKey(d *Datastorer) (name string, value interface{}) { if d != nil { // Use the given Datastorer to retrieve the key and its value v := reflect.ValueOf(d) //--log.Printf("##DEBUG 1: %v => %#v", v.Kind(), v) if v.Kind() == reflect.Ptr { // A pointer was given, get the referenced element v = v.Elem() } //--log.Printf("##DEBUG 2: %v => %#v", v.Kind(), v) if v.Kind() == reflect.Interface { v = v.Elem() } //--log.Printf("##DEBUG 3: %v => %#v", v.Kind(), v) t := v.Type() if v.Kind() != reflect.Struct { panic(fmt.Sprintf("getCrudKey: struct expected but %s has type %v : %v", t.Name(), v.Kind(), v.String())) } for i := 0; i < v.NumField(); i++ { fv := v.Field(i) ft := t.Field(i) if ft.Tag.Get("crud") == "key" { return ft.Name, fv.Interface() } } panic(fmt.Sprintf("No field tag crud:\"key\" in struct %s", t.Name())) } // Otherwise use the default DsSliceType to find the key. No value can be given. t := reflect.TypeOf(ci.DsStruct) if t.Kind() == reflect.Slice { // Get the underlying type of the slice. t = t.Elem() } if t.Kind() == reflect.Ptr { // Get the underlying type of the pointer. t = t.Elem() } if t.Kind() != reflect.Struct { panic(fmt.Sprintf("getCrudKey: struct expected but %s has type %v", t.Name(), t.Kind())) } for i := 0; i < t.NumField(); i++ { ft := t.Field(i) if ft.Tag.Get("crud") == "key" { return ft.Name, "" } } panic(fmt.Sprintf("No field tag crud:\"key\" in struct %s", t.Name())) return "", "" } func (p *CrudHandler) processJsonGetList(w http.ResponseWriter, r *http.Request, c appengine.Context, a *AccessInfo) (httpCode int, err error) { ci := p.CrudInfo //--TODO-- defer AddLogNow(c, u, kAccessKind, 0, LogActionView) // Check user ability. Must be in group View to list content. if !a.Is(GroupView) { return http.StatusUnauthorized, nil } v := r.URL.Query() // dataTable requires this argument to be passed through as an int echo := v.Get("sEcho") if _, err = strconv.Atoi(echo); err != nil { echo = "invalid" } // dataTable way of specifying pagination minRange, _ := strconv.Atoi(v.Get("iDisplayStart")) lenRange, _ := strconv.Atoi(v.Get("iDisplayLength")) //--log.Printf("## GET-LIST range=%v+%v", minRange, lenRange); // DEBUG key, _ := ci.GetCrudKey(nil) q := datastore.NewQuery(ci.Kind).Order(key) var n int if n, err = q.Count(c); err == nil { // Adjust query min/max based on range requested and actual count imin := Choice(minRange > 0, minRange, 0) ilen := Choice(imin + lenRange <= n, lenRange, n - imin) q.Offset(imin).Limit(ilen); var data struct { SEcho string `json:"sEcho"` TotalNum int `json:"iTotalRecords"` FilterNum int `json:"iTotalDisplayRecords"` AAData [][]string `json:"aaData"` } data.AAData = make([][]string, 0, ilen) t := reflect.TypeOf(ci.DsStruct) for it := q.Run(c); ; { v := CrudEntityLoadSaver { reflect.New(t).Elem() } _, err = it.Next(&v) // will call v.Load(<-data_channel) if err != nil { break } entry := v.Value.Interface().(Datastorer) data.AAData = append(data.AAData, entry.ToJsonTable()) } if err == datastore.Done || err == nil { err = nil data.SEcho = echo data.TotalNum = n data.FilterNum = n //--log.Printf("## GET-LIST reply %v - %v / %v -- %v", imin, imin+ilen, n, data); if b, err := json.MarshalIndent(data, "", " "); err == nil { w.Header().Add("Content-Range", fmt.Sprintf("items %d-%d/%d", imin, imin+ilen, n)) w.WriteHeader(http.StatusOK) _, err = w.Write(b) // Return 0 to avoid having the parent trying to set header when there's no error. return 0, err } } } log.Println("processJsonGetList err: ", err) return http.StatusInternalServerError, err } func (p *CrudHandler) processJsonAdd(w http.ResponseWriter, r *http.Request, c appengine.Context, a *AccessInfo, urlRest string) (httpCode int, err error) { ci := p.CrudInfo // Check user ability. Must be in group Create. if !a.Is(GroupCreate) { return http.StatusUnauthorized, nil } blob, err := ioutil.ReadAll(r.Body) if err != nil { return http.StatusInternalServerError, err } v, err := url.ParseQuery(string(blob)) if err == nil { var info Datastorer info, err = ci.Cruder.ValidateAdd(v) if err != nil { //--log.Printf("##DEBUG PUT-ERROR: %v", err.Error()) return http.StatusBadRequest, err } //--log.Printf("##DEBUG PUT-INFO: [%v %v] %#v", // reflect.ValueOf(info).Kind(), // reflect.TypeOf(info), // info) // FIXME: both lines might panic. Try and generate an Error _, vkey := ci.GetCrudKey(&info) skey := vkey.(string) //--log.Printf("## PUT-ITEM data=%v", info); key := datastore.NewKey(c, ci.Kind, skey, 0, nil) saver := &CrudEntityLoadSaver { reflect.ValueOf(info) } //--log.Printf("##DEBUG saver=%#v", saver); if _, err = datastore.Put(c, key, saver); err == nil { //--log.Printf("## PUT-ITEM datastore NO ERROR"); return http.StatusOK, nil } //--log.Printf("## PUT-ITEM datastore ERROR: %v", err.Error()); } return http.StatusBadRequest, err } func (p *CrudHandler) processJsonDel(w http.ResponseWriter, r *http.Request, c appengine.Context, a *AccessInfo, urlRest string) (httpCode int, err error) { ci := p.CrudInfo // Check user ability. Must be in group Create. if !a.Is(GroupCreate) { return http.StatusUnauthorized, nil } // urlRest should be /<key>. f := strings.Split(urlRest, "/") if len(f) == 2 { //--log.Printf("## DELETE-ITEM key=%s", f[1]); // DEBUG key := datastore.NewKey(c, ci.Kind, f[1], 0, nil) if err = datastore.Delete(c, key); err == datastore.ErrNoSuchEntity { return http.StatusNotFound, err } // Return 0 to avoid having the parent trying to set header when there's no error. return 0, err } log.Println("processJsonDel err: ", urlRest, err) return http.StatusNotFound, err }
110165172-description
TimeriSample/TimeriGo/src/serv/crud.go
Go
gpl3
24,168
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package serv /* A handler is a 'rooted' URL handler. For example a handler for "/user" will handle all requests to serve anything starting with "/user/..." or "/user?..." or "/user". The Handler can choose to be visible only for GET or POST and be associated with UI or not. */ import ( "appengine" "errors" "html/template" "net/http" "strings" ) //---------------- const ( // Handler is only visible for POST requests HandlerIsPost = 1 << iota // Handler is only visible for DELETE requests HandlerIsDelete // Handler is only visible for signed users HandlerIsSigned // Handler is only visible when listing UI tabs HandlerIsTab ) // Type describing a Handler. type HandlerDesc struct { // Mandatory URL root, must start with /, e.g. "/logs". URL string // Optional Handler* flag, possibly ORed. 0 for no flags. Flags int // Optional group required for accessing this Handler, e.g. "admin" Groups []string // Optional. Only needed for UI tabs. Title string } func (p *HandlerDesc) Is(flag int) bool { return (p.Flags & flag) != 0 } // Interface for implementing a handler for a given descriptor. type Handler interface { Handler() *HandlerDesc // Create the HTML representing the tab in the main page CreateTab (r *http.Request, c appengine.Context, a *AccessInfo) template.HTML // Process UI-less request ProcessRequest(w http.ResponseWriter, r *http.Request, c appengine.Context, a *AccessInfo, urlBase string, urlRest string) (httpCode int, err error) } //---------------- type Handlers []Handler var mRegisteredHandlers = make(Handlers, 0) func init() { mRegisteredHandlers = RegisterStatusHandlers(mRegisteredHandlers) mRegisteredHandlers = RegisterGCMCrud (mRegisteredHandlers) } // Find all handlers accessible by current user, regardless of the request path. // However this depends on the request method and whether it's for a UI tab or not. func FindHandlers(r *http.Request, isUiTab bool, isSigned bool, a *AccessInfo) (result Handlers) { flags := 0 if isUiTab { flags |= HandlerIsTab } if isSigned { flags |= HandlerIsSigned } if r.Method == "POST" { flags |= HandlerIsPost } else if r.Method == "DELETE" { flags |= HandlerIsDelete } result = make(Handlers, 0) for _, h := range mRegisteredHandlers { handler := h.Handler() if handler.Flags != flags { continue } if handler.Groups != nil { for _, g := range handler.Groups { if !a.Is(g) { continue } } } result = append(result, h) } return result } // Find first handler that can handle this specific request. // We don't know whether the handler will be for a tab or not, so this isn't a parameter. func FindRequestHandler(r *http.Request, isSigned bool, a *AccessInfo) (urlBase string, urlRest string, Handler Handler, err error) { u := r.URL.Path ulen := len(u) flags := 0 if isSigned { flags |= HandlerIsSigned } if r.Method == "POST" { flags |= HandlerIsPost } else if r.Method == "DELETE" { flags |= HandlerIsDelete } if ulen > 0 && u[0:1] == "/" { for _, h := range mRegisteredHandlers { handler := h.Handler() hflags := handler.Flags & ^HandlerIsTab // Ignore whether handler is for a tab or not if hflags != flags { continue } if handler.Groups != nil { for _, g := range handler.Groups { if !a.Is(g) { continue } } } urlBase = handler.URL blen := len(urlBase) if ulen >= blen && u[:blen] == urlBase { // get the reminder urlRest = u[blen:] // reminder must be either empty or start with / or & or ? if len(urlRest) == 0 || strings.ContainsAny(string(urlRest[0]), "/&?") { return urlBase, urlRest, h, nil } } } } return "", "", nil, errors.New("Invalid URL") } //----------------
110165172-description
TimeriSample/TimeriGo/src/serv/handler.go
Go
gpl3
5,309
<!DOCTYPE html> <!-- /* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ --> <html lang="en"> <head> <meta charset="utf-8"> <title>TimeriGo :: {{.TabName}}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Bootstrap styles --> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <style> body { padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */ } </style> <link href="/static/css/bootstrap-responsive.min.css" rel="stylesheet"> <style> /* Overrride bootsrap .brand right padding in the top navbar. */ .navbar .brand { padding-right: 0px !important; font-size: 100% !important; } /* Display footer always at bottom */ footer { position: absolute; bottom: 0px; width: 100%; padding-top: 10px; background-color: #f5f5f5; } footer > p { padding: 0px 10px; } /* Revert 'pull-right' on sign-in div when nav-collapse is in action. Otherwise it's obscured by the first nav element. */ @media (max-width: 980px) { .timeri-sign-in { float: none; } } </style> <!-- jQueryUI --> <link href="http://code.jquery.com/ui/1.10.2/themes/cupertino/jquery-ui.css" rel="stylesheet"> <!-- Data grid --> <link href="/static/css/datatable_table.css" rel="stylesheet"> <link href="/static/css/datatable_pager.css" rel="stylesheet"> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <span class="brand" href="#">TimeriGo ::</span> <div class="nav-collapse collapse"> <p class="navbar-text pull-right timeri-sign-in"> {{if .SignLink}} <a href="{{.SignLink}}">Sign In</a> {{else}} {{if .Email}}Welcome <span title="{{.UserTooltip}}">{{.Email}}</span>{{end}} &nbsp;|&nbsp; {{if .LogoutLink}}<a href="{{.LogoutLink}}">{{end}}Log out{{if .LogoutLink}}</a>{{end}} {{end}} </p> <ul class="nav"> {{range .Tabs}} <li class="{{.Active}}"><a href="{{.URL}}">{{.Title}}</a></li> {{end}} </ul> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container"> {{.TabContent}} </div> <!-- /container --> <footer class="footer"> <p class="credit"> {{.Timestamp}} <span id="timeriJSTimestamp"></span> <span class="pull-right"> {{.AppVersion}} </span> </p> <p class="error"> {{.ErrStr}} </p> </footer> <script type="text/javascript"> var timeri_start_time = Date.now(); </script> <!-- Bootsrap javascript --> <script src="http://code.jquery.com/jquery.js"></script> <script src="/static/js/bootstrap.min.js"></script> <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> <!-- Data grid --> <script src="/static/js/jquery.dataTables.min.js"></script> <script src="/static/js/datatables_bootstrap.js"></script> {{if .TabPathJS}} <script src="/static/js/{{.TabPathJS}}.js" type="text/javascript"></script> {{end}} <!-- Google analytics --> <script type="text/javascript"> if (document.location.hostname != "localhost") { var _gaq = _gaq || []; _gaq.push(["_setAccount", "UA-37396631-1"]); _gaq.push(["_trackPageview"]); (function() { var ga = document.createElement("script"); ga.type = "text/javascript"; ga.async = true; ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ga, s); })(); } </script> </body> </html>
110165172-description
TimeriSample/TimeriGo/src/serv/serv_bootstrap.html
HTML
gpl3
5,345
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package serv import ( "appengine" "appengine/datastore" // "appengine/user" // FIXME remove if unused "errors" "io/ioutil" "log" "net/http" "net/url" "time" ) //------------------------------ // GCM client defines the default lifespan of a registered id as 7 days. const kServerLifespanHours = 7 * 24 // Structure stored in AppEngine's datastore type GCMInfo struct { RegID string `crud:"key"` Created time.Time `datastore:",noindex"` Expires time.Time `datastore:",noindex"` } func (u GCMInfo) ToJsonTable() []string { // Converts a DataStore entity (the one matching DsStruct) into an array of strings // matching the fields expected in the CRUD html data table. return []string { u.RegID, u.Created.Format("2006-01-02 15:04:05 MST"), u.Expires.Format("2006-01-02 15:04:05 MST") } } //------------------------------ func RegisterGCMCrud(handlers Handlers) Handlers { ci := NewCrud("GCM", "/gcm", GCMInfo{}, &gcmCruder{}) return ci.RegisterHandlers(handlers) } type gcmCruder struct { crudInfo *CrudInfo } // gcmCruder implements the Cruder interface func (c *gcmCruder) RegisterHandlers(ci *CrudInfo, handlers Handlers) Handlers { c.crudInfo = ci desc := &HandlerDesc { Title: "GCM", URL: "/timer", Flags: HandlerIsTab | HandlerIsSigned, Groups: []string { GroupView, GroupAdmin } } handlers = append(handlers, &CrudHandler { desc, ci }) desc = &HandlerDesc { URL: "/gcm/register", Flags: HandlerIsPost } handlers = append(handlers, &CrudHandler { desc, ci }) desc = &HandlerDesc { URL: "/gcm/unregister", Flags: HandlerIsPost } handlers = append(handlers, &CrudHandler { desc, ci }) return handlers } func (c *gcmCruder) CanCreateTab(p *CrudHandler, r *http.Request, ac appengine.Context, a *AccessInfo) bool { // Return true if it's OK to create a UI tab page for this request. // -- return p.Is(HandlerIsSigned) && a.Is(GroupView) -- FIXME is signed needed? return a.Is(GroupView) } func (c *gcmCruder) ValidateAdd(values url.Values) (entity Datastorer, err error) { return nil, errors.New("Invalid request") } // gcmCruder implements the CruderProcessRequester interface func (p *gcmCruder) ProcessRequest(w http.ResponseWriter, r *http.Request, c appengine.Context, a *AccessInfo, urlBase string, urlRest string) (httpCode int, err error) { log.Printf("##DEBUG timer_gcm ProcessRequest %v %v", r.Method, urlBase) if r.Method == "POST" && urlBase == "/timer_gcm/register" { return p.processRegister(w, r, c, a) } else if r.Method == "POST" && urlBase == "/timer_gcm/unregister" { return p.processUnregister(w, r, c, a) } return http.StatusNotFound, nil } //------------------------------ func (p *gcmCruder) processRegister(w http.ResponseWriter, r *http.Request, c appengine.Context, a *AccessInfo) (httpCode int, err error) { blob, err := ioutil.ReadAll(r.Body) if err != nil { return http.StatusInternalServerError, err } v, err := url.ParseQuery(string(blob)) regID := v.Get("regId") log.Printf("##DEBUG register regid: %v", regID) if regID != "" { err = datastore.RunInTransaction(c, func(tc appengine.Context) error { kind := p.crudInfo.Kind tkey := datastore.NewKey(c, kind, regID, 0, nil) var info GCMInfo terr := datastore.Get(tc, tkey, &info) now := time.Now() if terr == datastore.ErrNoSuchEntity { info.Created = now } info.RegID = regID info.Expires = now.Add(time.Duration(kServerLifespanHours) * time.Hour) _, terr = datastore.Put(c, tkey, &info) if terr != nil { log.Printf("##DEBUG register Put.err: %v", terr.Error()) } return terr }, nil ) //-- &datastore.TransactionOptions { XG: true } ) if err == nil { return http.StatusOK, nil } } return http.StatusBadRequest, nil } func (p *gcmCruder) processUnregister(w http.ResponseWriter, r *http.Request, c appengine.Context, a *AccessInfo) (httpCode int, err error) { blob, err := ioutil.ReadAll(r.Body) if err != nil { return http.StatusInternalServerError, err } v, err := url.ParseQuery(string(blob)) regID := v.Get("regId") log.Printf("##DEBUG *un*register regid: %v", regID) if regID != "" { err = datastore.RunInTransaction(c, func(tc appengine.Context) error { kind := p.crudInfo.Kind tkey := datastore.NewKey(c, kind, regID, 0, nil) terr := datastore.Delete(tc, tkey) if terr != nil { log.Printf("##DEBUG *un*register Del.err: %v", terr.Error()) } return terr }, nil ) //-- &datastore.TransactionOptions { XG: true } ) if err == nil { return http.StatusOK, nil } } return http.StatusBadRequest, nil }
110165172-description
TimeriSample/TimeriGo/src/serv/gcm.go
Go
gpl3
6,443
package serv /* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import ( "appengine" "bytes" "html/template" "net/http" ) //------------------------------ type StatusHandler struct { *HandlerDesc } func RegisterStatusHandlers(handlers Handlers) Handlers { // Status for non-logged users desc := &HandlerDesc { Title: "Status", URL: "/", Flags: HandlerIsTab } handlers = append(handlers, &StatusHandler { desc }) // Status for signed-in users with "view" group access desc = &HandlerDesc { Title: "Status", URL: "/", Flags: HandlerIsTab | HandlerIsSigned, Groups: []string { GroupView } } handlers = append(handlers, &StatusHandler { desc }) return handlers } func (p *StatusHandler) Handler() *HandlerDesc { return p.HandlerDesc } //------------------------------ const tmplTabStatus = ` <div class="row-fluid"> <div class="span4">Select the "GCM" tab to get started.</div> </div> ` var mTmplTabStatus *template.Template func (p *StatusHandler) CreateTab(r *http.Request, c appengine.Context, a *AccessInfo) template.HTML { if !p.Is(HandlerIsSigned) || !a.Is(GroupView) { // Return the status for non-logged users. Basically there's nothing for them to see. return template.HTML(`<em>These are not the droids you are looking for.</em>`) } if mTmplTabStatus == nil { mTmplTabStatus = template.Must(template.New("Status_tmpl").Parse(tmplTabStatus)) } var buf bytes.Buffer err := mTmplTabStatus.Execute(&buf, struct { Title string } { p.Handler().Title } ) if err == nil { return template.HTML(buf.String()) } return template.HTML("internal error") } func (p *StatusHandler) ProcessRequest(w http.ResponseWriter, r *http.Request, c appengine.Context, s *AccessInfo, urlBase string, urlRest string) (httpCode int, err error) { return http.StatusInternalServerError, nil }
110165172-description
TimeriSample/TimeriGo/src/serv/status.go
Go
gpl3
2,967
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* grid control */ var timeriGCMTable; var timeriGCMTableSelection; $(document).ready(function() { timeriGCMTable = $("#timeriGCMTable").dataTable( { "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>", // http://www.datatables.net/usage/server-side "bServerSide": true, "bFilter ": false, "bSort ": false, "bSortClasses": false, "sAjaxSource": "/timer_gcm/get", "sPaginationType": "bootstrap", "aoColumns": [ { "bSortable": false }, { "bSortable": false }, { "bSortable": false }, ] }) // Row selection: http://www.datatables.net/examples/api/select_single_row.html $("#timeriGCMTable tbody").click(function(event) { $(timeriGCMTable.fnSettings().aoData).each(function () { $(this.nTr).removeClass("row_selected") }) var tr = event.target.parentNode $(tr).addClass("row_selected") timeriGCMOnRowSelected(timeriGCMTable.fnGetData(tr)) }) timeriGCMUnselectAll() } ) // ----------------------------------------------------------- // No Add Dialog // ----------------------------------------------------------- function timeriGCMRefresh() { timeriGCMUnselectAll() timeriGCMTable.fnDraw() } // ----------------------------------------------------------- function timeriGCMUnselectAll() { timeriGCMTableSelection = undefined; $(timeriGCMTable.fnSettings().aoData).each(function () { $(this.nTr).removeClass("row_selected") }) var b = $("#timeriGCMDeleteButton") b.attr("disabled", "disabled"); b.attr("title", "Select a row to delete it.") //--b = $("#timeriGCMAddButton") //--b.html("Add new user...") } function timeriGCMOnRowSelected(trGetData) { if (trGetData != undefined && trGetData.length == 2) { timeriGCMTableSelection = trGetData var b = $("#timeriGCMDeleteButton").removeAttr("disabled"); b.attr("title", "Delete entry for email [" + timeriGCMTableSelection[0] + "]") //--b = $("#timeriGCMAddButton") //--b.html("Add/Edit user...") } } function timeriGCMDelete() { if (timeriGCMTableSelection == undefined) { alert("Error. Nothing to delete.") return } if (!confirm("Do you want to delete [" + timeriGCMTableSelection[0] + "] ?")) { return } var q = $.ajax({ type: "DELETE", url: "/timer_gcm/del/" + encodeURI(timeriGCMTableSelection[0]), error: function(xhr, status, error) { var str = $.trim(error + ": " + xhr.responseText.replace(/[^A-Za-z0-9]+/gi, " ")); alert(str) }, success: function(data, status, xhr) { timeriGCMRefresh() }, }) }
110165172-description
TimeriSample/TimeriGo/src/static/js/timeriGCM.js
JavaScript
gpl3
3,489
/* grid control */ /* Source: http://www.datatables.net/blog/Twitter_Bootstrap_2 and at the bottom, all the JS to make datatable compatible with bootstrap's look: http://www.datatables.net/media/blog/bootstrap_2/DT_bootstrap.js */ $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline" } ); /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).addClass('pagination').append( '<ul>'+ '<li class="prev disabled"><a href="#">&larr; '+oLang.sPrevious+'</a></li>'+ '<li class="next disabled"><a href="#">'+oLang.sNext+' &rarr; </a></li>'+ '</ul>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, ien=an.length ; i<ien ; i++ ) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "DTTT btn-group", "buttons": { "normal": "btn", "disabled": "disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "DTTT_print_info modal" }, "select": { "row": "active" } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); } // -----------------------------------------------------------
110165172-description
TimeriSample/TimeriGo/src/static/js/datatables_bootstrap.js
JavaScript
gpl3
4,267
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * General page setup */ #dt_example { font: 80%/1.45em "Lucida Grande", Verdana, Arial, Helvetica, sans-serif; margin: 0; padding: 0; color: #333; background-color: #fff; } #dt_example #container { width: 800px; margin: 30px auto; padding: 0; } #dt_example #footer { margin: 50px auto 0 auto; padding: 0; } #dt_example #demo { margin: 30px auto 0 auto; } #dt_example .demo_jui { margin: 30px auto 0 auto; } #dt_example .big { font-size: 1.3em; font-weight: bold; line-height: 1.6em; color: #4E6CA3; } #dt_example .spacer { height: 20px; clear: both; } #dt_example .clear { clear: both; } #dt_example pre { padding: 15px; background-color: #F5F5F5; border: 1px solid #CCCCCC; } #dt_example h1 { margin-top: 2em; font-size: 1.3em; font-weight: normal; line-height: 1.6em; color: #4E6CA3; border-bottom: 1px solid #B0BED9; clear: both; } #dt_example h2 { font-size: 1.2em; font-weight: normal; line-height: 1.6em; color: #4E6CA3; clear: both; } #dt_example a { color: #0063DC; text-decoration: none; } #dt_example a:hover { text-decoration: underline; } #dt_example ul { color: #4E6CA3; } .css_right { float: right; } .css_left { float: left; } .demo_links { float: left; width: 50%; margin-bottom: 1em; } #demo_info { padding: 5px; border: 1px solid #B0BED9; height: 100px; width: 100%; overflow: auto; } #dt_example code { font-family: Menlo, Monaco, Consolas, "Courier New", monospace; padding: 2px 4px !important; white-space: nowrap; font-size: 0.9em; color: #D14; background-color: #F7F7F9; border: 1px solid #E1E1E8; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; }
110165172-description
TimeriSample/TimeriGo/src/static/css/datatable_pager.css
CSS
gpl3
1,765
/* * File: demo_table.css * CVS: $Id$ * Description: CSS descriptions for DataTables demo pages * Author: Allan Jardine * Created: Tue May 12 06:47:22 BST 2009 * Modified: $Date$ by $Author$ * Language: CSS * Project: DataTables * * Copyright 2009 Allan Jardine. All Rights Reserved. * * *************************************************************************** * DESCRIPTION * * The styles given here are suitable for the demos that are used with the standard DataTables * distribution (see www.datatables.net). You will most likely wish to modify these styles to * meet the layout requirements of your site. * * Common issues: * 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is * no conflict between the two pagination types. If you want to use full_numbers pagination * ensure that you either have "example_alt_pagination" as a body class name, or better yet, * modify that selector. * Note that the path used for Images is relative. All images are by default located in * ../images/ - relative to this CSS file. */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables features */ .dataTables_wrapper { position: relative; clear: both; zoom: 1; /* Feeling sorry for IE */ } .dataTables_processing { position: absolute; top: 50%; left: 50%; width: 250px; height: 30px; margin-left: -125px; margin-top: -15px; padding: 14px 0 2px 0; border: 1px solid #ddd; text-align: center; color: #999; font-size: 14px; background-color: white; } .dataTables_length { width: 40%; float: left; } .dataTables_filter { width: 50%; float: right; text-align: right; } .dataTables_info { width: 60%; float: left; } .dataTables_paginate { float: right; text-align: right; } /* Pagination nested */ .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next { height: 19px; float: left; cursor: pointer; *cursor: hand; color: #111 !important; } .paginate_disabled_previous:hover, .paginate_enabled_previous:hover, .paginate_disabled_next:hover, .paginate_enabled_next:hover { text-decoration: none !important; } .paginate_disabled_previous:active, .paginate_enabled_previous:active, .paginate_disabled_next:active, .paginate_enabled_next:active { outline: none; } .paginate_disabled_previous, .paginate_disabled_next { color: #666 !important; } .paginate_disabled_previous, .paginate_enabled_previous { padding-left: 23px; } .paginate_disabled_next, .paginate_enabled_next { padding-right: 23px; margin-left: 10px; } .paginate_disabled_previous { background: url('../images/back_disabled.png') no-repeat top left; } .paginate_enabled_previous { background: url('../images/back_enabled.png') no-repeat top left; } .paginate_enabled_previous:hover { background: url('../images/back_enabled_hover.png') no-repeat top left; } .paginate_disabled_next { background: url('../images/forward_disabled.png') no-repeat top right; } .paginate_enabled_next { background: url('../images/forward_enabled.png') no-repeat top right; } .paginate_enabled_next:hover { background: url('../images/forward_enabled_hover.png') no-repeat top right; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables display */ table.display { margin: 0 auto; clear: both; width: 100%; /* Note Firefox 3.5 and before have a bug with border-collapse * ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 ) * border-spacing: 0; is one possible option. Conditional-css.com is * useful for this kind of thing * * Further note IE 6/7 has problems when calculating widths with border width. * It subtracts one px relative to the other browsers from the first column, and * adds one to the end... * * If you want that effect I'd suggest setting a border-top/left on th/td's and * then filling in the gaps with other borders. */ } table.display thead th { padding: 3px 18px 3px 10px; border-bottom: 1px solid black; font-weight: bold; cursor: pointer; * cursor: hand; } table.display tfoot th { padding: 3px 18px 3px 10px; border-top: 1px solid black; font-weight: bold; } table.display tr.heading2 td { border-bottom: 1px solid #aaa; } table.display td { padding: 3px 10px; } table.display td.center { text-align: center; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables sorting */ .sorting_asc { background: url('../images/sort_asc.png') no-repeat center right; } .sorting_desc { background: url('../images/sort_desc.png') no-repeat center right; } .sorting { background: url('../images/sort_both.png') no-repeat center right; } .sorting_asc_disabled { background: url('../images/sort_asc_disabled.png') no-repeat center right; } .sorting_desc_disabled { background: url('../images/sort_desc_disabled.png') no-repeat center right; } table.display thead th:active, table.display thead td:active { outline: none; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables row classes */ table.display tr.odd.gradeA { background-color: #ddffdd; } table.display tr.even.gradeA { background-color: #eeffee; } table.display tr.odd.gradeC { background-color: #ddddff; } table.display tr.even.gradeC { background-color: #eeeeff; } table.display tr.odd.gradeX { background-color: #ffdddd; } table.display tr.even.gradeX { background-color: #ffeeee; } table.display tr.odd.gradeU { background-color: #ddd; } table.display tr.even.gradeU { background-color: #eee; } tr.odd { background-color: #E2E4FF; } tr.even { background-color: white; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Misc */ .dataTables_scroll { clear: both; } .dataTables_scrollBody { *margin-top: -1px; -webkit-overflow-scrolling: touch; } .top, .bottom { padding: 15px; background-color: #F5F5F5; border: 1px solid #CCCCCC; } .top .dataTables_info { float: none; } .clear { clear: both; } .dataTables_empty { text-align: center; } tfoot input { margin: 0.5em 0; width: 100%; color: #444; } tfoot input.search_init { color: #999; } td.group { background-color: #d1cfd0; border-bottom: 2px solid #A19B9E; border-top: 2px solid #A19B9E; } td.details { background-color: #d1cfd0; border: 2px solid #A19B9E; } .example_alt_pagination div.dataTables_info { width: 40%; } .paging_full_numbers { width: 400px; height: 22px; line-height: 22px; } .paging_full_numbers a:active { outline: none } .paging_full_numbers a:hover { text-decoration: none; } .paging_full_numbers a.paginate_button, .paging_full_numbers a.paginate_active { border: 1px solid #aaa; -webkit-border-radius: 5px; -moz-border-radius: 5px; padding: 2px 5px; margin: 0 3px; cursor: pointer; *cursor: hand; color: #333 !important; } .paging_full_numbers a.paginate_button { background-color: #ddd; } .paging_full_numbers a.paginate_button:hover { background-color: #ccc; text-decoration: none !important; } .paging_full_numbers a.paginate_active { background-color: #99B3FF; } table.display tr.even.row_selected td { background-color: #B0BED9; } table.display tr.odd.row_selected td { background-color: #9FAFD1; } /* RM 20130407 for bootstrap.css for odd/even row_selected */ .table-striped tbody > tr.row_selected:nth-child(odd) > td { background-color: #d7deec; } .table-striped tbody > tr.row_selected:nth-child(even) > td { background-color: #e2e7f1 ; } /* * Sorting classes for columns */ /* For the standard odd/even */ tr.odd td.sorting_1 { background-color: #D3D6FF; } tr.odd td.sorting_2 { background-color: #DADCFF; } tr.odd td.sorting_3 { background-color: #E0E2FF; } tr.even td.sorting_1 { background-color: #EAEBFF; } tr.even td.sorting_2 { background-color: #F2F3FF; } tr.even td.sorting_3 { background-color: #F9F9FF; } /* For the Conditional-CSS grading rows */ /* Colour calculations (based off the main row colours) Level 1: dd > c4 ee > d5 Level 2: dd > d1 ee > e2 */ tr.odd.gradeA td.sorting_1 { background-color: #c4ffc4; } tr.odd.gradeA td.sorting_2 { background-color: #d1ffd1; } tr.odd.gradeA td.sorting_3 { background-color: #d1ffd1; } tr.even.gradeA td.sorting_1 { background-color: #d5ffd5; } tr.even.gradeA td.sorting_2 { background-color: #e2ffe2; } tr.even.gradeA td.sorting_3 { background-color: #e2ffe2; } tr.odd.gradeC td.sorting_1 { background-color: #c4c4ff; } tr.odd.gradeC td.sorting_2 { background-color: #d1d1ff; } tr.odd.gradeC td.sorting_3 { background-color: #d1d1ff; } tr.even.gradeC td.sorting_1 { background-color: #d5d5ff; } tr.even.gradeC td.sorting_2 { background-color: #e2e2ff; } tr.even.gradeC td.sorting_3 { background-color: #e2e2ff; } tr.odd.gradeX td.sorting_1 { background-color: #ffc4c4; } tr.odd.gradeX td.sorting_2 { background-color: #ffd1d1; } tr.odd.gradeX td.sorting_3 { background-color: #ffd1d1; } tr.even.gradeX td.sorting_1 { background-color: #ffd5d5; } tr.even.gradeX td.sorting_2 { background-color: #ffe2e2; } tr.even.gradeX td.sorting_3 { background-color: #ffe2e2; } tr.odd.gradeU td.sorting_1 { background-color: #c4c4c4; } tr.odd.gradeU td.sorting_2 { background-color: #d1d1d1; } tr.odd.gradeU td.sorting_3 { background-color: #d1d1d1; } tr.even.gradeU td.sorting_1 { background-color: #d5d5d5; } tr.even.gradeU td.sorting_2 { background-color: #e2e2e2; } tr.even.gradeU td.sorting_3 { background-color: #e2e2e2; } /* * Row highlighting example */ .ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted { background-color: #ECFFB3; } .ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted { background-color: #E6FF99; } .ex_highlight_row #example tr.even:hover { background-color: #ECFFB3; } .ex_highlight_row #example tr.even:hover td.sorting_1 { background-color: #DDFF75; } .ex_highlight_row #example tr.even:hover td.sorting_2 { background-color: #E7FF9E; } .ex_highlight_row #example tr.even:hover td.sorting_3 { background-color: #E2FF89; } .ex_highlight_row #example tr.odd:hover { background-color: #E6FF99; } .ex_highlight_row #example tr.odd:hover td.sorting_1 { background-color: #D6FF5C; } .ex_highlight_row #example tr.odd:hover td.sorting_2 { background-color: #E0FF84; } .ex_highlight_row #example tr.odd:hover td.sorting_3 { background-color: #DBFF70; } /* * KeyTable */ table.KeyTable td { border: 3px solid transparent; } table.KeyTable td.focus { border: 3px solid #3366FF; } table.display tr.gradeA { background-color: #eeffee; } table.display tr.gradeC { background-color: #ddddff; } table.display tr.gradeX { background-color: #ffdddd; } table.display tr.gradeU { background-color: #ddd; } div.box { height: 100px; padding: 10px; overflow: auto; border: 1px solid #8080FF; background-color: #E5E5FF; }
110165172-description
TimeriSample/TimeriGo/src/static/css/datatable_table.css
CSS
gpl3
11,019
// +build !appengine /* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package datastore import ( "appengine" "errors" "fmt" "strings" ) var ErrNoSuchEntity = errors.New("datastore.ErrNoSuchEntity") //---- type datastoreMockResulter interface { appengine.MockResulter AppendProperty(p Property) } type DatastoreMockResult struct { PutProperties PropertyList } func (d *DatastoreMockResult) AsString() string { results := make([]string, 0) for _, p := range d.PutProperties { results = append(results, p.AsString()) } return strings.Join(results, "\n") } func (d *DatastoreMockResult) AppendProperty(p Property) { d.PutProperties = append(d.PutProperties, p) } //---- type Key struct { } func NewKey(c appengine.Context, kind, stringID string, intID int64, parent *Key) *Key { return nil } //----- func Get(c appengine.Context, key *Key, dst interface{}) error { return nil } func Put(c appengine.Context, key *Key, src interface{}) (*Key, error) { var d datastoreMockResulter d = c.MockResult.(datastoreMockResulter) if saver, ok := src.(PropertyLoadSaver); ok { ch := make(chan Property) go saver.Save(ch) for p := range ch { d.AppendProperty(p) } } return nil, nil } func Delete(c appengine.Context, key *Key) error { return nil } //---- type Query struct { } func NewQuery(kind string) *Query { return nil } func (q *Query) Count(c appengine.Context) (int, error) { return 0, nil } func (q *Query) GetAll(c appengine.Context, dst interface{}) ([]*Key, error) { return nil, nil } func (q *Query) Limit(limit int) *Query { return nil } func (q *Query) Offset(offset int) *Query { return nil } func (q *Query) Order(fieldName string) *Query { return nil } func (q *Query) Run(c appengine.Context) *Iterator { return nil } //------ type Iterator struct { } type Cursor struct { } func (t *Iterator) Cursor() (Cursor, error) { return Cursor{}, nil } // Done is returned when a query iteration has completed. var Done = errors.New("datastore: query has no more results") func (t *Iterator) Next(dst interface{}) (*Key, error) { return nil, nil } //------ type Property struct { Name string Value interface{} NoIndex bool Multiple bool } func (p *Property) AsString() string { return fmt.Sprintf("[%v] index:%v, multi:%v -- %v", p.Name, !p.NoIndex, p.Multiple, p.Value) } type PropertyLoadSaver interface { Load(<-chan Property) error Save(chan<- Property) error } type PropertyList []Property //------ type TransactionOptions struct { XG bool } func RunInTransaction(c appengine.Context, f func(tc appengine.Context) error, opts *TransactionOptions) error { return nil }
110165172-description
TimeriSample/TimeriGo/src/appengine/datastore/datastore_mock.go
Go
gpl3
3,469
// +build !appengine /* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package user import ( "appengine" ) type User struct { Email string } func Current(c appengine.Context) *User { return &User { "mock@example.com" } } func IsAdmin(c appengine.Context) bool { return false } func LoginURL(c appengine.Context, dest string) (string, error) { return "", nil } func LogoutURL(c appengine.Context, dest string) (string, error) { return "", nil }
110165172-description
TimeriSample/TimeriGo/src/appengine/user/user_mock.go
Go
gpl3
1,136
// +build !appengine /* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package appengine import ( "net/http" ) type BlobKey string type MockResulter interface { AsString() string } type Context struct { MockResult MockResulter } func NewContext(r *http.Request) Context { return Context {} } func VersionID(c Context) string { return "1" } func ServerSoftware() string { return "mock" }
110165172-description
TimeriSample/TimeriGo/src/appengine/appengine_mock.go
Go
gpl3
1,077
# # Copyright (C) 2013 rdrrlabs gmail com, # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # Usage: # source this from a script that defines a function wrap_py27_exec() # . ./_set_go_path.sh if [[ $(uname -o) == "Cygwin" ]]; then wrap_py27_exec else # Linux RR_PY27_DEACTIVATE="" if [[ $(python --version 2>&1 | cut -d " " -f 2) =~ "2.6" ]]; then echo "[PYTHON] 2.6 detected" ENV27=~/env-python27 if [[ ! -d $ENV27 ]]; then echo "[PYTHON] creating $ENV27" mkdir $ENV27 virtualenv --no-site-packages --python=python2.7 $ENV27 fi source ~/env-python27/bin/activate echo "[PYTHON] Activating " $(python --version) RR_PY27_DEACTIVATE="1" fi echo "[EXEC] Starting exec" wrap_py27_exec "$P" if [[ -n $RR_PY27_DEACTIVATE ]]; then echo "[PYTHON] Deactivating " $(python --version) deactivate fi fi
110165172-description
TimeriSample/TimeriGo/_wrap_py27.sh
Shell
gpl3
1,542
/* * Copyright 2012 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. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.android.gcm.GCMConstants.EXTRA_ERROR; import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Skeleton for application-specific {@link IntentService}s responsible for * handling communication from Google Cloud Messaging service. * <p> * The abstract methods in this class are called from its worker thread, and * hence should run in a limited amount of time. If they execute long * operations, they should spawn new threads, otherwise the worker thread will * be blocked. * <p> * Subclasses must provide a public no-arg constructor. */ public abstract class GCMBaseIntentService extends IntentService { public static final String TAG = "GCMBaseIntentService"; // wakelock private static final String WAKELOCK_KEY = "GCM_LIB"; private static PowerManager.WakeLock sWakeLock; // Java lock used to synchronize access to sWakelock private static final Object LOCK = GCMBaseIntentService.class; private final String[] mSenderIds; // instance counter private static int sCounter = 0; private static final Random sRandom = new Random(); private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis(3600); // 1 hour // token used to check intent origin private static final String TOKEN = Long.toBinaryString(sRandom.nextLong()); private static final String EXTRA_TOKEN = "token"; /** * Constructor that does not set a sender id, useful when the sender id * is context-specific. * <p> * When using this constructor, the subclass <strong>must</strong> * override {@link #getSenderIds(Context)}, otherwise methods such as * {@link #onHandleIntent(Intent)} will throw an * {@link IllegalStateException} on runtime. */ protected GCMBaseIntentService() { this(getName("DynamicSenderIds"), null); } /** * Constructor used when the sender id(s) is fixed. */ protected GCMBaseIntentService(String... senderIds) { this(getName(senderIds), senderIds); } private GCMBaseIntentService(String name, String[] senderIds) { super(name); // name is used as base name for threads, etc. mSenderIds = senderIds; } private static String getName(String senderId) { String name = "GCMIntentService-" + senderId + "-" + (++sCounter); Log.v(TAG, "Intent service name: " + name); return name; } private static String getName(String[] senderIds) { String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds); return getName(flatSenderIds); } /** * Gets the sender ids. * * <p>By default, it returns the sender ids passed in the constructor, but * it could be overridden to provide a dynamic sender id. * * @throws IllegalStateException if sender id was not set on constructor. */ protected String[] getSenderIds(Context context) { if (mSenderIds == null) { throw new IllegalStateException("sender id not set on constructor"); } return mSenderIds; } /** * Called when a cloud message has been received. * * @param context application's context. * @param intent intent containing the message payload as extras. */ protected abstract void onMessage(Context context, Intent intent); /** * Called when the GCM server tells pending messages have been deleted * because the device was idle. * * @param context application's context. * @param total total number of collapsed messages */ protected void onDeletedMessages(Context context, int total) { } /** * Called on a registration error that could be retried. * * <p>By default, it does nothing and returns {@literal true}, but could be * overridden to change that behavior and/or display the error. * * @param context application's context. * @param errorId error id returned by the GCM service. * * @return if {@literal true}, failed operation will be retried (using * exponential backoff). */ protected boolean onRecoverableError(Context context, String errorId) { return true; } /** * Called on registration or unregistration error. * * @param context application's context. * @param errorId error id returned by the GCM service. */ protected abstract void onError(Context context, String errorId); /** * Called after a device has been registered. * * @param context application's context. * @param registrationId the registration id returned by the GCM service. */ protected abstract void onRegistered(Context context, String registrationId); /** * Called after a device has been unregistered. * * @param registrationId the registration id that was previously registered. * @param context application's context. */ protected abstract void onUnregistered(Context context, String registrationId); @Override public final void onHandleIntent(Intent intent) { try { Context context = getApplicationContext(); String action = intent.getAction(); if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) { GCMRegistrar.setRetryBroadcastReceiver(context); handleRegistration(context, intent); } else if (action.equals(INTENT_FROM_GCM_MESSAGE)) { // checks for special messages String messageType = intent.getStringExtra(EXTRA_SPECIAL_MESSAGE); if (messageType != null) { if (messageType.equals(VALUE_DELETED_MESSAGES)) { String sTotal = intent.getStringExtra(EXTRA_TOTAL_DELETED); if (sTotal != null) { try { int total = Integer.parseInt(sTotal); Log.v(TAG, "Received deleted messages " + "notification: " + total); onDeletedMessages(context, total); } catch (NumberFormatException e) { Log.e(TAG, "GCM returned invalid number of " + "deleted messages: " + sTotal); } } } else { // application is not using the latest GCM library Log.e(TAG, "Received unknown special message: " + messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String token = intent.getStringExtra(EXTRA_TOKEN); if (!TOKEN.equals(token)) { // make sure intent was generated by this class, not by a // malicious app. Log.e(TAG, "Received invalid token: " + token); return; } // retry last call if (GCMRegistrar.isRegistered(context)) { GCMRegistrar.internalUnregister(context); } else { String[] senderIds = getSenderIds(context); GCMRegistrar.internalRegister(context, senderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If onMessage() needs to spawn a thread or do something else, // it should use its own lock. synchronized (LOCK) { // sanity check for null as this is a public method if (sWakeLock != null) { Log.v(TAG, "Releasing wakelock"); sWakeLock.release(); } else { // should never happen during normal workflow Log.e(TAG, "Wakelock reference is null"); } } } } /** * Called from the broadcast receiver. * <p> * Will process the received intent, call handleMessage(), registered(), * etc. in background threads, with a wake lock, while keeping the service * alive. */ static void runIntentInService(Context context, Intent intent, String className) { synchronized (LOCK) { if (sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } } Log.v(TAG, "Acquiring wakelock"); sWakeLock.acquire(); intent.setClassName(context, className); context.startService(intent); } private void handleRegistration(final Context context, Intent intent) { String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered); // registration succeeded if (registrationId != null) { GCMRegistrar.resetBackoff(context); GCMRegistrar.setRegistrationId(context, registrationId); onRegistered(context, registrationId); return; } // unregistration succeeded if (unregistered != null) { // Remember we are unregistered GCMRegistrar.resetBackoff(context); String oldRegistrationId = GCMRegistrar.clearRegistrationId(context); onUnregistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; Log.d(TAG, "Registration error: " + error); // Registration failed if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) { boolean retry = onRecoverableError(context, error); if (retry) { int backoffTimeMs = GCMRegistrar.getBackoff(context); int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); Log.d(TAG, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")"); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.putExtra(EXTRA_TOKEN, TOKEN); PendingIntent retryPendingIntent = PendingIntent .getBroadcast(context, 0, retryIntent, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if (backoffTimeMs < MAX_BACKOFF_MS) { GCMRegistrar.setBackoff(context, backoffTimeMs * 2); } } else { Log.d(TAG, "Not retrying failed operation"); } } else { // Unrecoverable error, notify app onError(context, error); } } }
110165172-description
TimeriSample/Timer2App/src/gcm/java/com/google/android/gcm/GCMBaseIntentService.java
Java
gpl3
13,565
/* * Copyright 2012 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. */ package com.google.android.gcm; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.os.Build; import android.util.Log; import java.sql.Timestamp; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utilities for device registration. * <p> * <strong>Note:</strong> this class uses a private {@link SharedPreferences} * object to keep track of the registration token. */ public final class GCMRegistrar { /** * Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)} * flag until it is considered expired. */ // NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8 public static final long DEFAULT_ON_SERVER_LIFESPAN_MS = 1000 * 3600 * 24 * 7; private static final String TAG = "GCMRegistrar"; private static final String BACKOFF_MS = "backoff_ms"; private static final String GSF_PACKAGE = "com.google.android.gsf"; private static final String PREFERENCES = "com.google.android.gcm"; private static final int DEFAULT_BACKOFF_MS = 3000; private static final String PROPERTY_REG_ID = "regId"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_ON_SERVER = "onServer"; private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME = "onServerExpirationTime"; private static final String PROPERTY_ON_SERVER_LIFESPAN = "onServerLifeSpan"; /** * {@link GCMBroadcastReceiver} instance used to handle the retry intent. * * <p> * This instance cannot be the same as the one defined in the manifest * because it needs a different permission. */ private static GCMBroadcastReceiver sRetryReceiver; private static String sRetryReceiverClassName; /** * Checks if the device has the proper dependencies installed. * <p> * This method should be called when the application starts to verify that * the device supports GCM. * * @param context application context. * @throws UnsupportedOperationException if the device does not support GCM. */ public static void checkDevice(Context context) { int version = Build.VERSION.SDK_INT; if (version < 8) { throw new UnsupportedOperationException("Device must be at least " + "API Level 8 (instead of " + version + ")"); } PackageManager packageManager = context.getPackageManager(); try { packageManager.getPackageInfo(GSF_PACKAGE, 0); } catch (NameNotFoundException e) { throw new UnsupportedOperationException( "Device does not have package " + GSF_PACKAGE); } } /** * Checks that the application manifest is properly configured. * <p> * A proper configuration means: * <ol> * <li>It creates a custom permission called * {@code PACKAGE_NAME.permission.C2D_MESSAGE}. * <li>It defines at least one {@link BroadcastReceiver} with category * {@code PACKAGE_NAME}. * <li>The {@link BroadcastReceiver}(s) uses the * {@value GCMConstants#PERMISSION_GCM_INTENTS} permission. * <li>The {@link BroadcastReceiver}(s) handles the 3 GCM intents * ({@value GCMConstants#INTENT_FROM_GCM_MESSAGE}, * {@value GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}, * and {@value GCMConstants#INTENT_FROM_GCM_LIBRARY_RETRY}). * </ol> * ...where {@code PACKAGE_NAME} is the application package. * <p> * This method should be used during development time to verify that the * manifest is properly set up, but it doesn't need to be called once the * application is deployed to the users' devices. * * @param context application context. * @throws IllegalStateException if any of the conditions above is not met. */ public static void checkManifest(Context context) { PackageManager packageManager = context.getPackageManager(); String packageName = context.getPackageName(); String permissionName = packageName + ".permission.C2D_MESSAGE"; // check permission try { packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Application does not define permission " + permissionName); } // check receivers PackageInfo receiversInfo; try { receiversInfo = packageManager.getPackageInfo( packageName, PackageManager.GET_RECEIVERS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Could not get receivers for package " + packageName); } ActivityInfo[] receivers = receiversInfo.receivers; if (receivers == null || receivers.length == 0) { throw new IllegalStateException("No receiver for package " + packageName); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "number of receivers for " + packageName + ": " + receivers.length); } Set<String> allowedReceivers = new HashSet<String>(); for (ActivityInfo receiver : receivers) { if (GCMConstants.PERMISSION_GCM_INTENTS.equals( receiver.permission)) { allowedReceivers.add(receiver.name); } } if (allowedReceivers.isEmpty()) { throw new IllegalStateException("No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS); } checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK); checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE); } private static void checkReceiver(Context context, Set<String> allowedReceivers, String action) { PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); Intent intent = new Intent(action); intent.setPackage(packageName); List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS); if (receivers.isEmpty()) { throw new IllegalStateException("No receivers for action " + action); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Found " + receivers.size() + " receivers for action " + action); } // make sure receivers match for (ResolveInfo receiver : receivers) { String name = receiver.activityInfo.name; if (!allowedReceivers.contains(name)) { throw new IllegalStateException("Receiver " + name + " is not set with permission " + GCMConstants.PERMISSION_GCM_INTENTS); } } } /** * Initiate messaging registration for the current application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with * either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or * {@link GCMConstants#EXTRA_ERROR}. * * @param context application context. * @param senderIds Google Project ID of the accounts authorized to send * messages to this application. * @throws IllegalStateException if device does not have all GCM * dependencies installed. */ public static void register(Context context, String... senderIds) { GCMRegistrar.resetBackoff(context); internalRegister(context, senderIds); } static void internalRegister(Context context, String... senderIds) { String flatSenderIds = getFlatSenderIds(senderIds); Log.v(TAG, "Registering app " + context.getPackageName() + " of senders " + flatSenderIds); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION); intent.setPackage(GSF_PACKAGE); intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0)); intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds); context.startService(intent); } static String getFlatSenderIds(String... senderIds) { if (senderIds == null || senderIds.length == 0) { throw new IllegalArgumentException("No senderIds"); } StringBuilder builder = new StringBuilder(senderIds[0]); for (int i = 1; i < senderIds.length; i++) { builder.append(',').append(senderIds[i]); } return builder.toString(); } /** * Unregister the application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an * {@link GCMConstants#EXTRA_UNREGISTERED} extra. */ public static void unregister(Context context) { GCMRegistrar.resetBackoff(context); internalUnregister(context); } /** * Clear internal resources. * * <p> * This method should be called by the main activity's {@code onDestroy()} * method. */ public static synchronized void onDestroy(Context context) { if (sRetryReceiver != null) { Log.v(TAG, "Unregistering receiver"); context.unregisterReceiver(sRetryReceiver); sRetryReceiver = null; } } static void internalUnregister(Context context) { Log.v(TAG, "Unregistering app " + context.getPackageName()); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION); intent.setPackage(GSF_PACKAGE); intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0)); context.startService(intent); } /** * Lazy initializes the {@link GCMBroadcastReceiver} instance. */ static synchronized void setRetryBroadcastReceiver(Context context) { if (sRetryReceiver == null) { if (sRetryReceiverClassName == null) { // should never happen Log.e(TAG, "internal error: retry receiver class not set yet"); sRetryReceiver = new GCMBroadcastReceiver(); } else { Class<?> clazz; try { clazz = Class.forName(sRetryReceiverClassName); sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance(); } catch (Exception e) { Log.e(TAG, "Could not create instance of " + sRetryReceiverClassName + ". Using " + GCMBroadcastReceiver.class.getName() + " directly."); sRetryReceiver = new GCMBroadcastReceiver(); } } String category = context.getPackageName(); IntentFilter filter = new IntentFilter( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); filter.addCategory(category); // must use a permission that is defined on manifest for sure String permission = category + ".permission.C2D_MESSAGE"; Log.v(TAG, "Registering receiver"); context.registerReceiver(sRetryReceiver, filter, permission, null); } } /** * Sets the name of the retry receiver class. */ static void setRetryReceiverClassName(String className) { Log.v(TAG, "Setting the name of retry receiver class to " + className); sRetryReceiverClassName = className; } /** * Gets the current registration id for application on GCM service. * <p> * If result is empty, the registration has failed. * * @return registration id, or empty string if the registration is not * complete. */ public static String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int newVersion = getAppVersion(context); if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) { Log.v(TAG, "App version changed from " + oldVersion + " to " + newVersion + "; resetting registration id"); clearRegistrationId(context); registrationId = ""; } return registrationId; } /** * Checks whether the application was successfully registered on GCM * service. */ public static boolean isRegistered(Context context) { return getRegistrationId(context).length() > 0; } /** * Clears the registration id in the persistence store. * * @param context application's context. * @return old registration id. */ static String clearRegistrationId(Context context) { return setRegistrationId(context, ""); } /** * Sets the registration id in the persistence store. * * @param context application's context. * @param regId registration id */ static String setRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, ""); int appVersion = getAppVersion(context); Log.v(TAG, "Saving regId on app version " + appVersion); Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); return oldRegistrationId; } /** * Sets whether the device was successfully registered in the server side. */ public static void setRegisteredOnServer(Context context, boolean flag) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putBoolean(PROPERTY_ON_SERVER, flag); // set the flag's expiration date long lifespan = getRegisterOnServerLifespan(context); long expirationTime = System.currentTimeMillis() + lifespan; Log.v(TAG, "Setting registeredOnServer status as " + flag + " until " + new Timestamp(expirationTime)); editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime); editor.commit(); } /** * Checks whether the device was successfully registered in the server side, * as set by {@link #setRegisteredOnServer(Context, boolean)}. * * <p>To avoid the scenario where the device sends the registration to the * server but the server loses it, this flag has an expiration date, which * is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed * by {@link #setRegisterOnServerLifespan(Context, long)}). */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); Log.v(TAG, "Is registered on server: " + isRegistered); if (isRegistered) { // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); if (System.currentTimeMillis() > expirationTime) { Log.v(TAG, "flag expired on: " + new Timestamp(expirationTime)); return false; } } return isRegistered; } /** * Gets how long (in milliseconds) the {@link #isRegistered(Context)} * property is valid. * * @return value set by {@link #setRegisteredOnServer(Context, boolean)} or * {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set. */ public static long getRegisterOnServerLifespan(Context context) { final SharedPreferences prefs = getGCMPreferences(context); long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN, DEFAULT_ON_SERVER_LIFESPAN_MS); return lifespan; } /** * Sets how long (in milliseconds) the {@link #isRegistered(Context)} * flag is valid. */ public static void setRegisterOnServerLifespan(Context context, long lifespan) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan); editor.commit(); } /** * Gets the application version. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Coult not get package name: " + e); } } /** * Resets the backoff counter. * <p> * This method should be called after a GCM call succeeds. * * @param context application's context. */ static void resetBackoff(Context context) { Log.d(TAG, "resetting backoff for " + context.getPackageName()); setBackoff(context, DEFAULT_BACKOFF_MS); } /** * Gets the current backoff counter. * * @param context application's context. * @return current backoff counter, in milliseconds. */ static int getBackoff(Context context) { final SharedPreferences prefs = getGCMPreferences(context); return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS); } /** * Sets the backoff counter. * <p> * This method should be called after a GCM call fails, passing an * exponential value. * * @param context application's context. * @param backoff new backoff counter, in milliseconds. */ static void setBackoff(Context context, int backoff) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putInt(BACKOFF_MS, backoff); editor.commit(); } private static SharedPreferences getGCMPreferences(Context context) { return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); } private GCMRegistrar() { throw new UnsupportedOperationException(); } }
110165172-description
TimeriSample/Timer2App/src/gcm/java/com/google/android/gcm/GCMRegistrar.java
Java
gpl3
20,124
/* * Copyright 2012 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. */ package com.google.android.gcm; /** * Constants used by the GCM library. */ public final class GCMConstants { /** * Intent sent to GCM to register the application. */ public static final String INTENT_TO_GCM_REGISTRATION = "com.google.android.c2dm.intent.REGISTER"; /** * Intent sent to GCM to unregister the application. */ public static final String INTENT_TO_GCM_UNREGISTRATION = "com.google.android.c2dm.intent.UNREGISTER"; /** * Intent sent by GCM indicating with the result of a registration request. */ public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK = "com.google.android.c2dm.intent.REGISTRATION"; /** * Intent used by the GCM library to indicate that the registration call * should be retried. */ public static final String INTENT_FROM_GCM_LIBRARY_RETRY = "com.google.android.gcm.intent.RETRY"; /** * Intent sent by GCM containing a message. */ public static final String INTENT_FROM_GCM_MESSAGE = "com.google.android.c2dm.intent.RECEIVE"; /** * Extra used on {@link #INTENT_TO_GCM_REGISTRATION} to indicate the sender * account (a Google email) that owns the application. */ public static final String EXTRA_SENDER = "sender"; /** * Extra used on {@link #INTENT_TO_GCM_REGISTRATION} to get the application * id. */ public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; /** * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * that the application has been unregistered. */ public static final String EXTRA_UNREGISTERED = "unregistered"; /** * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * an error when the registration fails. See constants starting with ERROR_ * for possible values. */ public static final String EXTRA_ERROR = "error"; /** * Extra used on {@link #INTENT_FROM_GCM_REGISTRATION_CALLBACK} to indicate * the registration id when the registration succeeds. */ public static final String EXTRA_REGISTRATION_ID = "registration_id"; /** * Type of message present in the {@link #INTENT_FROM_GCM_MESSAGE} intent. * This extra is only set for special messages sent from GCM, not for * messages originated from the application. */ public static final String EXTRA_SPECIAL_MESSAGE = "message_type"; /** * Special message indicating the server deleted the pending messages. */ public static final String VALUE_DELETED_MESSAGES = "deleted_messages"; /** * Number of messages deleted by the server because the device was idle. * Present only on messages of special type * {@link #VALUE_DELETED_MESSAGES} */ public static final String EXTRA_TOTAL_DELETED = "total_deleted"; /** * Permission necessary to receive GCM intents. */ public static final String PERMISSION_GCM_INTENTS = "com.google.android.c2dm.permission.SEND"; /** * @see GCMBroadcastReceiver */ public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME = ".GCMIntentService"; /** * The device can't read the response, or there was a 500/503 from the * server that can be retried later. The application should use exponential * back off and retry. */ public static final String ERROR_SERVICE_NOT_AVAILABLE = "SERVICE_NOT_AVAILABLE"; /** * There is no Google account on the phone. The application should ask the * user to open the account manager and add a Google account. */ public static final String ERROR_ACCOUNT_MISSING = "ACCOUNT_MISSING"; /** * Bad password. The application should ask the user to enter his/her * password, and let user retry manually later. Fix on the device side. */ public static final String ERROR_AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED"; /** * The request sent by the phone does not contain the expected parameters. * This phone doesn't currently support GCM. */ public static final String ERROR_INVALID_PARAMETERS = "INVALID_PARAMETERS"; /** * The sender account is not recognized. Fix on the device side. */ public static final String ERROR_INVALID_SENDER = "INVALID_SENDER"; /** * Incorrect phone registration with Google. This phone doesn't currently * support GCM. */ public static final String ERROR_PHONE_REGISTRATION_ERROR = "PHONE_REGISTRATION_ERROR"; private GCMConstants() { throw new UnsupportedOperationException(); } }
110165172-description
TimeriSample/Timer2App/src/gcm/java/com/google/android/gcm/GCMConstants.java
Java
gpl3
5,385
/* * Copyright 2012 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. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * {@link BroadcastReceiver} that receives GCM messages and delivers them to * an application-specific {@link GCMBaseIntentService} subclass. * <p> * By default, the {@link GCMBaseIntentService} class belongs to the application * main package and is named * {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class, * the {@link #getGCMIntentServiceClassName(Context)} must be overridden. */ public class GCMBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "GCMBroadcastReceiver"; private static boolean mReceiverSet = false; @Override public final void onReceive(Context context, Intent intent) { Log.v(TAG, "onReceive: " + intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; String myClass = getClass().getName(); if (!myClass.equals(GCMBroadcastReceiver.class.getName())) { GCMRegistrar.setRetryReceiverClassName(myClass); } } String className = getGCMIntentServiceClassName(context); Log.v(TAG, "GCM IntentService class: " + className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); } /** * Gets the class name of the intent service that will handle GCM messages. */ protected String getGCMIntentServiceClassName(Context context) { return getDefaultIntentServiceClassName(context); } /** * Gets the default class name of the intent service that will handle GCM * messages. */ static final String getDefaultIntentServiceClassName(Context context) { String className = context.getPackageName() + DEFAULT_INTENT_SERVICE_CLASS_NAME; return className; } }
110165172-description
TimeriSample/Timer2App/src/gcm/java/com/google/android/gcm/GCMBroadcastReceiver.java
Java
gpl3
2,863
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.view.MenuItem; import com.rdrrlabs.example.timer2app.R; /** * An activity representing a single Event detail screen. This activity is only * used on handset devices. On tablet-size devices, item details are presented * side-by-side with a list of items in a {@link EventListActivity}. * <p> * This activity is mostly just a 'shell' activity containing nothing more than * a {@link EventDetailFragment}. */ public class EventDetailActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event_detail); // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. Bundle arguments = new Bundle(); arguments.putString(EventDetailFragment.ARG_ITEM_ID, getIntent() .getStringExtra(EventDetailFragment.ARG_ITEM_ID)); EventDetailFragment fragment = new EventDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.event_detail_container, fragment) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpTo(this, new Intent(this, EventListActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/pub/ui/EventDetailActivity.java
Java
gpl3
3,638
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.rdrrlabs.example.timer2app.R; public class MainActivityImpl extends FragmentActivity { @Override protected void onCreate(Bundle state) { super.onCreate(state); setContentView(R.layout.activity_intro); } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/pub/ui/MainActivityImpl.java
Java
gpl3
1,080
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.view.MenuItem; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.core.GCMHelper; import com.rdrrlabs.example.timer2app.core.GlobalContext; /** * An activity representing a list of Events. This activity has different * presentations for handset and tablet-size devices. On handsets, the activity * presents a list of items, which when touched, lead to a * {@link EventDetailActivity} representing item details. On tablets, the * activity presents the list of items and item details side-by-side using two * vertical panes. * <p> * The activity makes heavy use of fragments. The list of items is a * {@link EventListFragment} and the item details (if present) is a * {@link EventDetailFragment}. * <p> * This activity also implements the required * {@link EventListFragment.Callbacks} interface to listen for item selections. */ public class EventListActivity extends FragmentActivity implements EventListFragment.Callbacks { /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private boolean mTwoPane; private GCMHelper mGCMMixing; public EventListActivity() { mGCMMixing = new GCMHelper(this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GlobalContext.getContext().onAppStart(this); setContentView(R.layout.activity_event_list); setupActionBar(); if (findViewById(R.id.event_detail_container) != null) { // The detail container view will be present only in the // large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the // activity should be in two-pane mode. mTwoPane = true; // In two-pane mode, list items should be given the // 'activated' state when touched. ((EventListFragment) getSupportFragmentManager().findFragmentById( R.id.event_list)).setActivateOnItemClick(true); } // TODO: If exposing deep links into your app, handle intents here. //--RM DEBUG--mGCMMixing.onCreate(); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (MainActivity.sStartClass != this.getClass()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // // TODO: If Settings has multiple levels, Up should navigate up // that hierarchy. NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } /** * Callback method from {@link EventListFragment.Callbacks} indicating that * the item with the given ID was selected. */ @Override public void onItemSelected(String id) { if (mTwoPane) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. Bundle arguments = new Bundle(); arguments.putString(EventDetailFragment.ARG_ITEM_ID, id); EventDetailFragment fragment = new EventDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.event_detail_container, fragment) .commit(); } else { // In single-pane mode, simply start the detail activity // for the selected item ID. Intent detailIntent = new Intent(this, EventDetailActivity.class); detailIntent.putExtra(EventDetailFragment.ARG_ITEM_ID, id); startActivity(detailIntent); } } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/pub/ui/EventListActivity.java
Java
gpl3
5,684
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.RingtonePreference; import android.text.TextUtils; import android.view.MenuItem; import android.support.v4.app.NavUtils; import java.util.List; import com.rdrrlabs.example.timer2app.R; /** * A {@link PreferenceActivity} that presents a set of application settings. On * handset devices, settings are presented as a single list. On tablets, * settings are split by category, with category headers shown to the left of * the list of settings. * <p> * See <a href="http://developer.android.com/design/patterns/settings.html"> * Android Design: Settings</a> for design guidelines and the <a * href="http://developer.android.com/guide/topics/ui/settings.html">Settings * API Guide</a> for more information on developing a Settings UI. */ public class SettingsActivity extends PreferenceActivity { /** * Determines whether to always show the simplified settings UI, where * settings are presented in a single list. When false, settings are shown * as a master/detail two-pane view on tablets. When true, a single pane is * shown on tablets. */ private static final boolean ALWAYS_SIMPLE_PREFS = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // // TODO: If Settings has multiple levels, Up should navigate up // that hierarchy. NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setupSimplePreferencesScreen(); } /** * Shows the simplified settings UI if the device configuration if the * device configuration dictates that a simplified, single-pane UI should be * shown. */ @SuppressWarnings("deprecation") private void setupSimplePreferencesScreen() { if (!isSimplePreferences(this)) { return; } // In the simplified UI, fragments are not used at all and we instead // use the older PreferenceActivity APIs. // Add 'general' preferences. addPreferencesFromResource(R.xml.pref_general); // Add 'notifications' preferences, and a corresponding header. PreferenceCategory fakeHeader = new PreferenceCategory(this); fakeHeader.setTitle(R.string.pref_header_notifications); getPreferenceScreen().addPreference(fakeHeader); addPreferencesFromResource(R.xml.pref_notification); // Add 'data and sync' preferences, and a corresponding header. fakeHeader = new PreferenceCategory(this); fakeHeader.setTitle(R.string.pref_header_data_sync); getPreferenceScreen().addPreference(fakeHeader); addPreferencesFromResource(R.xml.pref_data_sync); // Bind the summaries of EditText/List/Dialog/Ringtone preferences to // their values. When their values change, their summaries are updated // to reflect the new value, per the Android Design guidelines. bindPreferenceSummaryToValue(findPreference("example_text")); bindPreferenceSummaryToValue(findPreference("example_list")); bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")); bindPreferenceSummaryToValue(findPreference("sync_frequency")); } /** {@inheritDoc} */ @Override public boolean onIsMultiPane() { return isXLargeTablet(this) && !isSimplePreferences(this); } /** * Helper method to determine if the device has an extra-large screen. For * example, 10" tablets are extra-large. */ private static boolean isXLargeTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE; } /** * Determines whether the simplified settings UI should be shown. This is * true if this is forced via {@link #ALWAYS_SIMPLE_PREFS}, or the device * doesn't have newer APIs like {@link PreferenceFragment}, or the device * doesn't have an extra-large screen. In these cases, a single-pane * "simplified" settings UI should be shown. */ private static boolean isSimplePreferences(Context context) { return ALWAYS_SIMPLE_PREFS || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB || !isXLargeTablet(context); } /** {@inheritDoc} */ @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void onBuildHeaders(List<Header> target) { if (!isSimplePreferences(this)) { loadHeadersFromResource(R.xml.pref_headers, target); } } /** * A preference value change listener that updates the preference's summary * to reflect its new value. */ private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); // Set the summary to reflect the new value. preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null); } else if (preference instanceof RingtonePreference) { // For ringtone preferences, look up the correct display value // using RingtoneManager. if (TextUtils.isEmpty(stringValue)) { // Empty values correspond to 'silent' (no ringtone). preference.setSummary(R.string.pref_ringtone_silent); } else { Ringtone ringtone = RingtoneManager.getRingtone( preference.getContext(), Uri.parse(stringValue)); if (ringtone == null) { // Clear the summary if there was a lookup error. preference.setSummary(null); } else { // Set the summary to reflect the new ringtone display // name. String name = ringtone .getTitle(preference.getContext()); preference.setSummary(name); } } } else { // For all other preferences, set the summary to the value's // simple string representation. preference.setSummary(stringValue); } return true; } }; /** * Binds a preference's summary to its value. More specifically, when the * preference's value is changed, its summary (line of text below the * preference title) is updated to reflect the value. The summary is also * immediately updated upon calling this method. The exact display format is * dependent on the type of preference. * * @see #sBindPreferenceSummaryToValueListener */ private static void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); // Trigger the listener immediately with the preference's // current value. sBindPreferenceSummaryToValueListener.onPreferenceChange( preference, PreferenceManager.getDefaultSharedPreferences( preference.getContext()).getString( preference.getKey(), "")); } /** * This fragment shows general preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class GeneralPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_general); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("example_text")); bindPreferenceSummaryToValue(findPreference("example_list")); } } /** * This fragment shows notification preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class NotificationPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_notification); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone")); } } /** * This fragment shows data and sync preferences only. It is used when the * activity is showing a two-pane settings UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class DataSyncPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_data_sync); // Bind the summaries of EditText/List/Dialog/Ringtone preferences // to their values. When their values change, their summaries are // updated to reflect the new value, per the Android Design // guidelines. bindPreferenceSummaryToValue(findPreference("sync_frequency")); } } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/pub/ui/SettingsActivity.java
Java
gpl3
13,063
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.rdrrlabs.example.timer2app.R; public class IntroFragment extends Fragment { private TextView mTextSignInfo; private Button mBtnSignInOut; private Button mBtnEvents; private Button mBtnSettings; @Override public void onCreate(Bundle state) { super.onCreate(state); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle state) { View root = inflater.inflate(R.layout.fragment_intro, container, false); mTextSignInfo = (TextView) root.findViewById(R.id.textAccountName); mBtnSignInOut = (Button) root.findViewById(R.id.btnSignInOut); mBtnEvents = (Button) root.findViewById(R.id.btnEvents); mBtnSettings = (Button) root.findViewById(R.id.btnSettings); mBtnSignInOut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SignInDialog.showSignInDialog(getActivity()); } }); mBtnEvents.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onClickProfiles(); } }); mBtnSettings.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onClickSettings(); } }); return root; } @Override public void onResume() { super.onResume(); mTextSignInfo.setText(R.string.intro__not_logged); } protected void onClickProfiles() { startActivity(new Intent(getActivity(), EventListActivity.class)); } protected void onClickSettings() { startActivity(new Intent(getActivity(), SettingsActivity.class)); } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/pub/ui/IntroFragment.java
Java
gpl3
2,904
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import java.util.ArrayList; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.OnAccountsUpdateListener; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.rdrrlabs.example.liblabs.app.Bus; import com.rdrrlabs.example.liblabs.app.Bus.Register; import com.rdrrlabs.example.liblabs.app.IBusListener; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.core.BusConstants; import com.rdrrlabs.example.timer2app.core.GAEHelper; import com.rdrrlabs.example.timer2app.core.GAEHelper.State; import com.rdrrlabs.example.timer2app.core.GlobalContext; public class SignInDialog extends DialogFragment implements IBusListener { @SuppressWarnings("unused") private static final String TAG = SignInDialog.class.getSimpleName(); static void showSignInDialog(FragmentActivity activity) { // based on http://developer.android.com/reference/android/app/DialogFragment.html FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment prev = fm.findFragmentByTag("dialog"); if (prev != null) ft.remove(prev); ft.addToBackStack(null); SignInDialog df = new SignInDialog(); df.show(ft, "dialog"); } // ----------- private static final int RESULT_SYNC_SETTINGS = Activity.RESULT_FIRST_USER + 1; private static final int MODE_SELECT_ACCOUNT = 0; private static final int MODE_AUTH_TOKEN = 1; private Button mBtnNext; private TextView mTextExplanation; private ListView mListView; private ProgressBar mProgress; private AccountManager mAccMan; private int mMode = MODE_SELECT_ACCOUNT; private OnAccountsUpdateListener mAccListener; private final State mState = new State(); private final ArrayList<AccountWrapper> mAccountWrappers = new ArrayList<SignInDialog.AccountWrapper>(); private Register<SignInDialog> mBusReg; @Override public void onCreate(Bundle state) { super.onCreate(state); mAccMan = AccountManager.get(getActivity()); mBusReg = Bus.register(this, GlobalContext.getContext().getBus()); if (mAccListener == null) { mAccListener = new OnAccountsUpdateListener() { @Override public void onAccountsUpdated(Account[] accounts) { updateAccountList(); } }; } mAccMan.addOnAccountsUpdatedListener(mAccListener, null/*handler*/, false/*updateImmediately*/); } @Override public void onDestroy() { super.onDestroy(); if (mAccListener != null) mAccMan.removeOnAccountsUpdatedListener(mAccListener); mAccMan = null; mAccountWrappers.clear(); mBusReg.deregister(); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle state) { View root = inflater.inflate(R.layout.fragment_signin, container, false); getDialog().setTitle("Sign In"); mBtnNext = (Button) root.findViewById(R.id.btnNext); mTextExplanation = (TextView) root.findViewById(R.id.txtExplanation); mListView = (ListView) root.findViewById(R.id.listAccounts); mListView.setEmptyView(root.findViewById(android.R.id.empty)); mProgress = (ProgressBar) root.findViewById(R.id.progressBar1); displayList(true); Button btnCancel = (Button) root.findViewById(R.id.btnCancel); btnCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Dismiss the dialog. SignInDialog.this.dismiss(); } }); Button btnCreate = (Button) root.findViewById(android.R.id.empty); btnCreate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT); //-- doesn't seem to work. //-- i.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { "com.google" }); startActivityForResult(i, RESULT_SYNC_SETTINGS); } }); mBtnNext.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Object o = v.getTag(); if (o instanceof AccountWrapper) { authenticateAccount(((AccountWrapper) o).getAccount()); } else { mListView.clearChoices(); } } }); setupAccountList(root); mBtnNext.setEnabled(false); return root; } private void displayList(boolean displayList) { mListView.setVisibility(displayList ? View.VISIBLE : View.GONE); mProgress.setVisibility(displayList ? View.GONE : View.VISIBLE); mProgress.setIndeterminate(!displayList); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_SYNC_SETTINGS) { updateAccountList(); } } private void setupAccountList(View root) { mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Object o = parent.getItemAtPosition(position); if (o instanceof AccountWrapper) { mBtnNext.setEnabled(true); mBtnNext.setTag(o); } } }); updateAccountList(); } private void updateAccountList() { if (mMode != MODE_SELECT_ACCOUNT) return; if (mListView == null) return; // this should not happen. mAccountWrappers.clear(); for (Account account : mAccMan.getAccountsByType("com.google")) { mAccountWrappers.add(new AccountWrapper(account)); } if (mAccountWrappers.isEmpty()) { mTextExplanation.setText("No Google accounts available."); //FIXME res string } else { mTextExplanation.setText("Select a Google account:"); //FIXME res string } ArrayAdapter<AccountWrapper> adapter = new ArrayAdapter<AccountWrapper>( getActivity(), android.R.layout.simple_list_item_single_choice, android.R.id.text1, mAccountWrappers) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); return view; } }; mListView.setAdapter(adapter); mListView.clearChoices(); } /** Adapts an Account to be a list entry by providing its adequate string description. */ private static class AccountWrapper { private final Account mAccount; public AccountWrapper(Account account) { mAccount = account; } public Account getAccount() { return mAccount; } @Override public String toString() { return mAccount.name; } } //----- private void authenticateAccount(Account account) { mMode = MODE_AUTH_TOKEN; mBtnNext.setEnabled(false); displayList(false); mTextExplanation.setText("Authenticating. This may take a few minutes."); GAEHelper ah = GlobalContext.getContext().getGAEHelper(); mState.mAccountName = account.name; ah.getAuthToken(getActivity(), account, mState); } @Override public void onBusMessage(int what, Object object) { if (what == BusConstants.GAE_ACCOUNT_STATE_CHANGED && object == mState) { mTextExplanation.post(new Runnable() { @Override public void run() { String info = mState.mDetail; if (info == null) { switch(mState.mState) { case State.NO_ACCOUNT: // This shouldn't really happen here. info = "Please select an account to sign-in."; break; case State.INVALID_ACCOUNT: // This shouldn't really happen here. info = "Invalid account, please select another account to sign-in."; break; case State.AUTH_TOKEN_FAILED: case State.AUTH_COOKIE_FAILED: info = "Failed to authenticate. Try again or change account."; break; case State.SUCCESS: info = "Success"; break; default: info = ""; } } mTextExplanation.setText(info); if (mState.mState != State.PENDING) { mProgress.setIndeterminate(false); mProgress.setProgress(mProgress.getMax()); } if (mState.mState == State.SUCCESS) { GAEHelper ah = GlobalContext.getContext().getGAEHelper(); ah.useAccount(getActivity(), mState.mAccountName, mState.mGAECookie); // Auto-close mTextExplanation.postDelayed(new Runnable() { @Override public void run() { SignInDialog.this.dismiss(); } }, 250 /*ms*/); } } }); } } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/pub/ui/SignInDialog.java
Java
gpl3
11,611
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.dummy.DummyContent; /** * A fragment representing a single Event detail screen. This fragment is either * contained in a {@link EventListActivity} in two-pane mode (on tablets) or a * {@link EventDetailActivity} on handsets. */ public class EventDetailFragment extends Fragment { /** * The fragment argument representing the item ID that this fragment * represents. */ public static final String ARG_ITEM_ID = "item_id"; /** * The dummy content this fragment is presenting. */ private DummyContent.DummyItem mItem; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public EventDetailFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { // Load the dummy content specified by the fragment // arguments. In a real-world scenario, use a Loader // to load content from a content provider. mItem = DummyContent.ITEM_MAP.get(getArguments().getString( ARG_ITEM_ID)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_event_detail, container, false); // Show the dummy content as text in a TextView. if (mItem != null) { ((TextView) rootView.findViewById(R.id.event_detail)) .setText(mItem.content); } return rootView; } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/pub/ui/EventDetailFragment.java
Java
gpl3
2,773
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.text.SpannableString; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.rdrrlabs.example.liblabs.app.Bus; import com.rdrrlabs.example.liblabs.app.Bus.Register; import com.rdrrlabs.example.liblabs.app.IBusListener; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.core.BusConstants; import com.rdrrlabs.example.timer2app.core.GAEHelper; import com.rdrrlabs.example.timer2app.core.GlobalContext; import com.rdrrlabs.example.timer2app.core.GAEHelper.State; import com.rdrrlabs.example.timer2app.dummy.DummyContent; /** * A list fragment representing a list of Events. This fragment also supports * tablet devices by allowing list items to be given an 'activated' state upon * selection. This helps indicate which item is currently being viewed in a * {@link EventDetailFragment}. * <p> * Activities containing this fragment MUST implement the {@link Callbacks} * interface. */ public class EventListFragment extends ListFragment // FIXME use Timeriffic ListFragment2 implements IBusListener { /** * The serialization (saved instance state) Bundle key representing the * activated item position. Only used on tablets. */ private static final String STATE_ACTIVATED_POSITION = "activated_position"; /** * The fragment's current callback object, which is notified of list item * clicks. */ private Callbacks mCallbacks = sDummyCallbacks; /** * The current activated item position. Only used on tablets. */ private int mActivatedPosition = ListView.INVALID_POSITION; private Button mBtnSignIn; private TextView mTextSignName; private TextView mTextSignInfo; private TextView mLinkSignIn; private Register<EventListFragment> mBusReg; /** * A callback interface that all activities containing this fragment must * implement. This mechanism allows activities to be notified of item * selections. */ public interface Callbacks { /** * Callback for when an item has been selected. */ public void onItemSelected(String id); } /** * A dummy implementation of the {@link Callbacks} interface that does * nothing. Used only when this fragment is not attached to an activity. */ private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onItemSelected(String id) { } }; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public EventListFragment() { } @Override public void onCreate(Bundle state) { super.onCreate(state); mBusReg = Bus.register(this, GlobalContext.getContext().getBus()); // TODO: replace with a real list adapter. setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(getActivity(), android.R.layout.simple_list_item_1, //FIXME API 11 simple_list_item_activated_1 android.R.id.text1, DummyContent.ITEMS)); } @Override public void onDestroy() { super.onDestroy(); mBusReg.deregister(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { //-- Disabled: do not call super since it creates a view root hierarchy that //-- we do not need. //-- return super.onCreateView(inflater, container, state); View root = inflater.inflate(R.layout.fragment_event_master, null /*root*/, false /*attachToRoot*/); // On start, the list view should have the focus, if possible. final View listView = root.findViewById(android.R.id.list); listView.requestFocus(); mTextSignName = (TextView) root.findViewById(R.id.textAccountName); mTextSignInfo = (TextView) root.findViewById(R.id.textInfo); mBtnSignIn = (Button) root.findViewById(R.id.btnSignIn); if (mBtnSignIn != null) { mBtnSignIn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SignInDialog.showSignInDialog(getActivity()); } }); } mLinkSignIn = (TextView) root.findViewById(R.id.linkSignIn); if (mLinkSignIn != null) { // get current text CharSequence t = mLinkSignIn.getText(); // make it a spannable SpannableString s = new SpannableString(t); // create a clickable span ClickableSpan cs = new ClickableSpan() { @Override public void onClick(View widget) { listView.requestFocus(); // TODO change focus only on success SignInDialog.showSignInDialog(getActivity()); } }; // attach the span to the spannable s.setSpan(cs, 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); mLinkSignIn.setMovementMethod(LinkMovementMethod.getInstance()); mLinkSignIn.setText(s); } // Start the GAE check 250ms after startup mTextSignName.postDelayed(new Runnable() { @Override public void run() { GAEHelper ah = GlobalContext.getContext().getGAEHelper(); updateSignInfo(ah); ah.onActivityStartedCheck(getActivity()); } }, 250 /*ms*/); return root; } @Override public void onViewCreated(View view, Bundle state) { super.onViewCreated(view, state); // Restore the previously serialized activated item position. if (state != null && state.containsKey(STATE_ACTIVATED_POSITION)) { setActivatedPosition(state.getInt(STATE_ACTIVATED_POSITION)); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Activities containing this fragment must implement its callbacks. if (!(activity instanceof Callbacks)) { throw new IllegalStateException( "Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); // Reset the active callbacks interface to the dummy implementation. mCallbacks = sDummyCallbacks; } @Override public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mActivatedPosition != ListView.INVALID_POSITION) { // Serialize and persist the activated item position. outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); } } /** * Turns on activate-on-click mode. When this mode is on, list items will be * given the 'activated' state when touched. */ public void setActivateOnItemClick(boolean activateOnItemClick) { // When setting CHOICE_MODE_SINGLE, ListView will automatically // give items the 'activated' state when touched. getListView().setChoiceMode( activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE); } private void setActivatedPosition(int position) { if (position == ListView.INVALID_POSITION) { getListView().setItemChecked(mActivatedPosition, false); } else { getListView().setItemChecked(position, true); } mActivatedPosition = position; } // --------------- @Override public void onBusMessage(int what, Object object) { final GAEHelper ah = GlobalContext.getContext().getGAEHelper(); if (what == BusConstants.GAE_ACCOUNT_STATE_CHANGED && object == ah.getCurrentState()) { mTextSignName.post(new Runnable() { @Override public void run() { updateSignInfo(ah); } }); } } private void updateSignInfo(final GAEHelper ah) { State state = ah.getCurrentState(); String name = state.mAccountName; if (name != null) { mTextSignName.setText(name); } else { mTextSignName.setText(getString(R.string.intro__not_logged)); } String info = state.mDetail; if (info == null) { switch(state.mState) { case State.NO_ACCOUNT: info = "Please <select an account> to sign-in."; break; case State.INVALID_ACCOUNT: info = "Invalid account, please <select another account> to sign-in."; break; case State.AUTH_TOKEN_FAILED: case State.AUTH_COOKIE_FAILED: info = "Failed to authenticate. <Try again> or <change account>."; break; default: info = ""; } } mTextSignInfo.setText(info); } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/pub/ui/EventListFragment.java
Java
gpl3
10,758
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.pub.ui; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class MainActivity extends Activity { public static Class<?> sStartClass = null; @Override protected void onCreate(Bundle state) { super.onCreate(state); // Check prefs to decide on which to start with sStartClass = MainActivityImpl.class; sStartClass = EventListActivity.class; Intent i = new Intent(this, sStartClass); startActivity(i); finish(); } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/pub/ui/MainActivity.java
Java
gpl3
1,320
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.gcm; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.rdrrlabs.example.timer2app.R; import com.rdrrlabs.example.timer2app.pub.ui.EventListActivity; import com.google.android.gcm.GCMBaseIntentService; import com.google.android.gcm.GCMRegistrar; //----------------------------------------------- /** * GCM Intent Service -- this class MUST remain at the root of the package. */ public class GCMIntentServiceImpl extends GCMBaseIntentService { private static final String TAG = GCMIntentServiceImpl.class.getSimpleName(); public static final String SENDER_ID = "265050972334"; // FIXME store in CoreStrings public GCMIntentServiceImpl() { super(SENDER_ID); } @Override protected void onRegistered(Context context, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); GCMServerUtilities.displayMessage(context, "gcm_registered"); //--getString(R.string.gcm_registered)); GCMServerUtilities.register(context, registrationId); } @Override protected void onUnregistered(Context context, String registrationId) { Log.i(TAG, "Device unregistered"); GCMServerUtilities.displayMessage(context, "gcm_unregistered"); //--getString(R.string.gcm_unregistered)); if (GCMRegistrar.isRegisteredOnServer(context)) { GCMServerUtilities.unregister(context, registrationId); } else { // This callback results from the call to unregister made on // GCMServerUtilities when the registration to the server failed. Log.i(TAG, "Ignoring unregister callback"); } } @Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "Received message"); String message = "gcm_message"; //--getString(R.string.gcm_message); GCMServerUtilities.displayMessage(context, message); // notifies user generateNotification(context, message); } @Override protected void onDeletedMessages(Context context, int total) { Log.i(TAG, "Received deleted messages notification"); String message = "gcm_deleted"; //-- getString(R.string.gcm_deleted, total); GCMServerUtilities.displayMessage(context, message); // notifies user generateNotification(context, message); } @Override public void onError(Context context, String errorId) { Log.i(TAG, "Received error: " + errorId); GCMServerUtilities.displayMessage(context, "gcm_error: " + errorId); //--getString(R.string.gcm_error, errorId)); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message Log.i(TAG, "Received recoverable error: " + errorId); GCMServerUtilities.displayMessage(context, "gcm_recoverable_error: " + errorId); //--getString(R.string.gcm_recoverable_error, errorId)); return super.onRecoverableError(context, errorId); } /** * Issues a notification to inform the user that server has sent a message. */ @SuppressWarnings("deprecation") private static void generateNotification(Context context, String message) { int icon = R.drawable.ic_launcher; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, EventListActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/gcm/GCMIntentServiceImpl.java
Java
gpl3
5,166
/* * Copyright 2012 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. */ package com.rdrrlabs.example.timer2app.gcm; import com.google.android.gcm.GCMRegistrar; import com.rdrrlabs.example.timer2app.core.GAEHelper; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; /** * Helper class used to communicate with the demo server. */ public final class GCMServerUtilities { private static final String TAG = GCMServerUtilities.class.getSimpleName(); //--public static final String URL_AH_SERVER = "http://10.0.2.2:8080"; // FIXME detect for emulator (by Build Model=sdk) public static final String URL_SERVER_HTTP = GAEHelper.sGAEBaseURL; //-- "http://myserver.appspot.com" ; // FIXME detect for emulator (by Build Model=sdk) public static final String URL_SERVER_HTTPS = URL_SERVER_HTTP.replace("http", "https"); private static final String URL_TIMER_GCM = URL_SERVER_HTTP + "/timer_gcm"; // FIXME detect for emulator (by Build Model=sdk) private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final Random random = new Random(); /** * Register this account/device pair within the server. * * @return whether the registration succeeded or not. */ static boolean register(final Context context, final String regId) { Log.i(TAG, "registering device (regId = " + regId + ")"); String serverUrl = URL_TIMER_GCM + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { Log.d(TAG, "Attempt #" + i + " to register"); try { displayMessage(context, "registering " + i); //-- context.getString(R.string.server_registering, i, MAX_ATTEMPTS)); post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); String message = "server_registered"; //--context.getString(R.string.server_registered); displayMessage(context, message); return true; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). Log.e(TAG, "Failed to register on attempt " + i, e); if (i == MAX_ATTEMPTS) { break; } try { Log.d(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Log.d(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return false; } // increase backoff exponentially backoff *= 2; } } String message = "server_register_error"; //--context.getString(R.string.server_register_error, MAX_ATTEMPTS); displayMessage(context, message); return false; } /** * Unregister this account/device pair within the server. */ static void unregister(final Context context, final String regId) { Log.i(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = URL_TIMER_GCM + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); String message = "server_unregistered"; //--context.getString(R.string.server_unregistered); displayMessage(context, message); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. String message = "server_unregister_error"; //--context.getString(R.string.server_unregister_error, e.getMessage()); displayMessage(context, message); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(BACKOFF_MILLI_SECONDS); // RM added conn.setReadTimeout(BACKOFF_MILLI_SECONDS); // RM added conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } /** * Intent used to display a message in the screen. */ static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE"; /** * Intent's extra that contains the message to be displayed. */ static final String EXTRA_MESSAGE = "message"; /** * Notifies UI to display a message. * <p> * This method is defined in the common helper because it's used both by * the UI and the background service. * * @param context application's context. * @param message message to be displayed. */ static void displayMessage(Context context, String message) { Toast.makeText(context, "GCM: " + message, Toast.LENGTH_SHORT).show(); Intent intent = new Intent(DISPLAY_MESSAGE_ACTION); intent.putExtra(EXTRA_MESSAGE, message); context.sendBroadcast(intent); } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/gcm/GCMServerUtilities.java
Java
gpl3
8,688
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.dummy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Helper class for providing sample content for user interfaces created by * Android template wizards. * <p> * TODO: Replace all uses of this class before publishing your app. */ public class DummyContent { /** * An array of sample (dummy) items. */ public static List<DummyItem> ITEMS = new ArrayList<DummyItem>(); /** * A map of sample (dummy) items, by ID. */ public static Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>(); static { // Add fake items. for (int i = 0; i < 20; i++) { addItem(new DummyItem("" + i, "Event " + i)); } } private static void addItem(DummyItem item) { ITEMS.add(item); ITEM_MAP.put(item.id, item); } /** * A dummy item representing a piece of content. */ public static class DummyItem { public String id; public String content; public DummyItem(String id, String content) { this.id = id; this.content = content; } @Override public String toString() { return content; } } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/dummy/DummyContent.java
Java
gpl3
2,012
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; //----------------------------------------------- public abstract class BusConstants { public final static int GAE_ACCOUNT_STATE_CHANGED = 1; }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/core/BusConstants.java
Java
gpl3
908
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import com.rdrrlabs.example.annotations.NonNull; import com.rdrrlabs.example.liblabs.utils.Utils; import java.io.IOException; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookieStore; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.TimeUnit; //----------------------------------------------- /** * Holds our helper to connect our GAE instance. * It keeps the context of the current user account to use, the current * app engine cookie and can do authenticated POSTs. */ public class GAEHelper { private static final String TAG = GAEHelper.class.getSimpleName(); private static final boolean DEBUG = true; private static final boolean USE_DEV_SERVER = Utils.isEmulator(); /** Pref to store GAE account name. Type: String. */ private static final String PREFS_KEY_GAE_ACCOUNT = "gae_account"; /** Base GAE url without a final / */ public static final String sGAEBaseURL = USE_DEV_SERVER ? "http://10.0.2.2:8080" : "http://myserver.appspot.com"; // TODO change private static final String sGAEAuthCookie = USE_DEV_SERVER ? "dev_appserver_login" : "ACSID"; private static final GAEHelper sInstance = new GAEHelper(); private CookieManager mCookieMan; private final State mCurrentState = new State(); public static GAEHelper getInstance() { return sInstance; } private GAEHelper() { // Setup our own cookie manager mCookieMan = new CookieManager(); CookieHandler.setDefault(mCookieMan); } @NonNull public State getCurrentState() { return mCurrentState; } public CookieManager getCookieManager() { return mCookieMan; } /** * Initialization when main activity gets started. * If the account name isn't present, try to read it from prefs. * If there is no auth cookie, try to get one. * * @param activity The calling activity. Needed by the account manager to ask for * user permission to access App Engine, if not already granted. */ public void onActivityStartedCheck(Activity activity) { if (DEBUG) Log.d(TAG, String.format("onActivityStartedCheck: %s", mCurrentState)); if (mCurrentState.mAccountName == null) { // Read initial name from prefs GlobalContext gc = GlobalContext.getContext(); PrefsStorage ps = gc.getPrefsStorage(); mCurrentState.mAccountName = ps.getString(PREFS_KEY_GAE_ACCOUNT, null); mCurrentState.setState( mCurrentState.mAccountName == null ? State.NO_ACCOUNT : State.SUCCESS); } if (mCurrentState.mAccountName != null && mCurrentState.mGAECookie == null) { Account account = validateAccount(activity, mCurrentState); if (account != null) { getAuthToken(activity, account, mCurrentState); } } } /** * Validate that the account exists in the Account Manager. * If there is no account name, sets the state to no-account and returns null. * If found, it returns the {@link Account} and sets the state to success. * If not found, it returns null and sets the state to invalid-account. * <p/> * This should typically be followed by a call to {@link #getAuthToken}. * * @return The {@link Account} found matching the {@link State} account name, * or null if not found. */ public Account validateAccount(Activity activity, State state) { if (DEBUG) Log.d(TAG, String.format("validateAccount: %s", state)); state.setState(State.PENDING, "Validating account."); if (state.mAccountName == null || state.mAccountName.isEmpty()) { state.setState(State.NO_ACCOUNT); return null; } AccountManager am = AccountManager.get(activity); for (Account account : am.getAccountsByType("com.google")) { if (mCurrentState.mAccountName.equals(account.name)) { state.setState(State.SUCCESS); return account; } } state.setState(State.INVALID_ACCOUNT); return null; } public void getAuthToken(final Activity activity, Account account, final State state) { if (DEBUG) Log.d(TAG, String.format("getAuthToken: %s", state)); state.setState(State.PENDING, "Authenticating..."); AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() { // Runs from the main thread @Override public void run(AccountManagerFuture<Bundle> future) { try { Bundle result = future.getResult(120, TimeUnit.SECONDS); GetCookieTask t = new GetCookieTask(state); t.execute(result.getString(AccountManager.KEY_AUTHTOKEN)); } catch (OperationCanceledException e) { Log.e(TAG, "getAuthToken", e); state.setState(State.AUTH_TOKEN_FAILED, "Authentication cancelled."); } catch (AuthenticatorException e) { Log.e(TAG, "getAuthToken", e); state.setState(State.AUTH_TOKEN_FAILED, "Authentication failed."); } catch (IOException e) { Log.e(TAG, "getAuthToken", e); state.setState(State.AUTH_TOKEN_FAILED, "Network error."); } } }; AccountManager am = AccountManager.get(activity); am.getAuthToken( account, "ah", // authTokenType, null, // options, activity, // activity, callback , null); // handler } private class GetCookieTask extends AsyncTask<String, Void, Void> { private final State mState; public GetCookieTask(State state) { mState = state; } @Override protected Void doInBackground(String... params) { String authToken = params[0]; if (DEBUG) Log.d(TAG, String.format("getAuthCookie: %s", mState)); mState.setState(State.PENDING, "Authenticating with server..."); // Note: The _ah/login request must match the protocol we'll use later, // either http or https. Cookies are ACSID vs SACSID and aren't interchangeable. String urlStr = sGAEBaseURL + "/_ah/login?"; if (USE_DEV_SERVER) { urlStr += "email=test@example.com&action=Login&"; } urlStr += "continue=" + sGAEBaseURL + "/&auth=" + authToken; try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(120*1000); conn.setReadTimeout(5*1000); conn.setInstanceFollowRedirects(false); conn.connect(); int status = conn.getResponseCode(); // We expect a 302 redirect on success. if (status != 302) { if (DEBUG) Log.d(TAG, "GetCookieTask invalid HTTP status " + status); mState.setState(State.AUTH_COOKIE_FAILED); return null; } CookieStore st = mCookieMan.getCookieStore(); for (HttpCookie cookie : st.getCookies()) { if (sGAEAuthCookie.equals(cookie.getName())) { // Success, we found our cookie mState.mGAECookie = (HttpCookie) cookie.clone(); mState.setState(State.SUCCESS); return null; } } // If we reach here, we didn't get the right cookie. if (DEBUG) Log.d(TAG, "GetCookieTask -- cookie not found"); mState.setState(State.AUTH_COOKIE_FAILED, "Authentication not supported by server."); } catch (Throwable tr) { // Probably a network error if (DEBUG) Log.d(TAG, "GetCookieTask", tr); mState.setState(State.AUTH_COOKIE_FAILED, "Network error."); } return null; } } /** * A new account has been choosen, with its cookie to be used for this session. * Save the info in the app prefs. * * Notify bus listeners that the account name has changed, if it did. * * @param context An android context * @param accountName The account name. * @param cookie The new auth cookie. */ public void useAccount(Context context, String accountName, HttpCookie cookie) { if (DEBUG) { Log.d(TAG, "useAccount: " + accountName + ", cookie: " + cookie.toString()); } mCurrentState.mGAECookie = cookie; if ((accountName == null && mCurrentState.mAccountName != null) || !accountName.equals(mCurrentState.mAccountName)) { mCurrentState.mAccountName = accountName; GlobalContext gc = GlobalContext.getContext(); PrefsStorage ps = gc.getPrefsStorage(); ps.putString(PREFS_KEY_GAE_ACCOUNT, accountName); ps.beginWriteAsync(context); } mCurrentState.setState(State.SUCCESS); } private static void busSend(int code, State state) { GlobalContext.getContext().getBus().send(code, state); } public static class State { public static final int PENDING = 0; public static final int NO_ACCOUNT = 10; public static final int INVALID_ACCOUNT = 11; public static final int AUTH_TOKEN_FAILED = 12; public static final int AUTH_COOKIE_FAILED = 13; public static final int SUCCESS = 42; public int mState; public String mDetail; public String mAccountName; public HttpCookie mGAECookie; /** Change the state and send a bus notification if it has actually changed. */ public void setState(int state) { this.setState(state, null); } /** Change the state and send a bus notification if it has actually changed. */ public void setState(int state, String detail) { if (mState != state || (detail == null && mDetail != null) || (detail != null && !detail.equals(mDetail))) { mState = state; mDetail = detail; busSend(BusConstants.GAE_ACCOUNT_STATE_CHANGED, this); } } @Override public String toString() { return "<GAE.State [" + mState + "] name: " + mAccountName + ", cookie: " + mGAECookie + ", detail: " + mDetail + ">"; } } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/core/GAEHelper.java
Java
gpl3
12,405
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; import com.rdrrlabs.example.liblabs.app.Bus; import android.content.Context; //----------------------------------------------- /** A singleton using shared structures of the app. * <p/> * This singleton must NEVER store an object that directly or indirectly holds * an Android context such as an activity or a fragment. * */ public class GlobalContext { private static GlobalContext sContext = new GlobalContext(); // TODO change override during test private final Bus mBus = new Bus(); private final PrefsStorage mPrefsStorage = new PrefsStorage("prefs"); private final GAEHelper mGAEHelper = GAEHelper.getInstance(); private boolean mAppStartDone; private GlobalContext() { } public static GlobalContext getContext() { return sContext; } public PrefsStorage getPrefsStorage() { return mPrefsStorage; } public GAEHelper getGAEHelper() { return mGAEHelper; } public Bus getBus() { return mBus; } /** Initialize a few things once. */ public void onAppStart(Context androidContext) { if (!mAppStartDone) { mAppStartDone = true; // Reads the pref storage async, since eventually we'll need it. mPrefsStorage.beginReadAsync(androidContext); } } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/core/GlobalContext.java
Java
gpl3
2,077
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; import android.app.Activity; import android.util.Log; import com.rdrrlabs.example.timer2app.GCMIntentService; import com.google.android.gcm.GCMRegistrar; //----------------------------------------------- public class GCMHelper { private static final String TAG = GCMHelper.class.getSimpleName(); private final Activity mActivity; public GCMHelper(Activity activity) { mActivity = activity; } public void onCreate() { GCMRegistrar.checkDevice(mActivity); GCMRegistrar.checkManifest(mActivity); final String regId = GCMRegistrar.getRegistrationId(mActivity); if (regId.equals("")) { GCMRegistrar.register(mActivity, GCMIntentService.SENDER_ID); } else { Log.v(TAG, "Already registered"); } } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/core/GCMHelper.java
Java
gpl3
1,561
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app.core; import com.rdrrlabs.example.liblabs.prefs.BasePrefsStorage; //----------------------------------------------- public class PrefsStorage extends BasePrefsStorage { public PrefsStorage(String filename) { super(filename); } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/core/PrefsStorage.java
Java
gpl3
1,000
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer2app; import com.rdrrlabs.example.timer2app.gcm.GCMIntentServiceImpl; //----------------------------------------------- /** * GCM Intent Service -- this class MUST remain at the root of the package. */ public class GCMIntentService extends GCMIntentServiceImpl { public GCMIntentService() { super(); } }
110165172-description
TimeriSample/Timer2App/src/main/java/com/rdrrlabs/example/timer2app/GCMIntentService.java
Java
gpl3
1,071
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.app; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import android.util.Log; import com.rdrrlabs.example.annotations.Null; import com.rdrrlabs.example.liblabs.utils.Utils; //----------------------------------------------- /** * A simplistic message-based notifier. * <p/> * In its most basic implementation, the "bus" sends messages. * Listeners listen to the messages and are notified when a message is sent. * <p/> * Messages are objects (typically strings or integers). * * Messages are not queued like a Handler: posted messages are sent right away and deliver * to whoever is currently listening. There is no fancy thread handling like in a Handler * either: messages are posted and received on the sender's thread. If you want the facilities * of a Handler then use a Handler. * <p/> * Listeners can choose to listen to any kind of message, specific message * objects or just a given Class of message (e.g. Strings, or whatever custom type.) */ public class Bus { private static final String TAG = Bus.class.getSimpleName(); private static final boolean DEBUG = Utils.isEmulator(); public static final int NO_WHAT = -1; /** * Listeners. A map filter-type => listener list. * Access to the map must synchronized on the map itself. * Access to the lists must synchronized on the lists themselves. */ private final HashMap<Class<?>, List<BusAdapter>> mListeners = new HashMap<Class<?>, List<BusAdapter>>(); public Bus() { } // ----- public void send(int what) { this.send(what, null); } public void send(Object object) { this.send(NO_WHAT, null); } public void send(int what, Object object) { Class<?> filter = object == null ? Void.class : object.getClass(); if (DEBUG) { Log.d(TAG, String.format("Bus.send: what: %d, obj: %s", what, object)); } List<BusAdapter> list0 = null; // list of listeners with null. List<BusAdapter> list1 = null; // list of typed listeners, including Void.class synchronized (mListeners) { list0 = mListeners.get(null); list1 = mListeners.get(filter); } sendInternal(list0, what, object); if (list1 != list0) { sendInternal(list1, what, object); } } private void sendInternal(List<BusAdapter> list, int what, Object object) { if (list != null) { synchronized (list) { for (BusAdapter listener : list) { try { listener.onBusMessage(what, object); } catch(Throwable tr) { Log.d(TAG, listener.getClass().getSimpleName() + ".onBusMessage failed", tr); } } } } } // ----- public BusAdapter addListener(BusAdapter listener) { if (listener == null) return listener; Class<?> filter = listener.getClassFilter(); List<BusAdapter> list = null; synchronized (mListeners) { list = mListeners.get(filter); if (list == null) { list = new LinkedList<BusAdapter>(); mListeners.put(filter, list); } } synchronized (list) { if (!list.contains(listener)) { list.add(listener); } } return listener; } public BusAdapter removeListener(BusAdapter listener) { if (listener == null) return listener; Class<?> filter = listener.getClassFilter(); List<BusAdapter> list = null; synchronized (mListeners) { list = mListeners.get(filter); } if (list != null) { synchronized (list) { list.remove(listener); } } return listener; } // ----- /** * Registers a BusListener with no class filter. * * @param receiver A receiver object implement {@link IBusListener}. * @param bus The {@link Bus} instance on which to register. * @return A new {@link Register} object; caller must call {@link Register#deregister()} later. */ public static <B extends IBusListener> Register<B> register(B receiver, Bus bus) { return register(null, receiver, bus); } /** * Registers a BusListener with a specific class filter. * * @param classFilter The object class to filter. Can be null to receive everything (any kind * of object, including null) or the {@link Void} class to filter on message with null * objects. * @param receiver A receiver object implement {@link IBusListener}. * @param bus The {@link Bus} instance on which to register. * @return A new {@link Register} object; caller must call {@link Register#deregister()} later. */ public static <B extends IBusListener> Register<B> register(@Null Class<?> classFilter, B receiver, Bus bus) { Register<B> m = new Register<B>(classFilter, receiver, bus); bus.addListener(m); return m; } /** * Helper to add/remove a bus listener on an existing class. * Usage: * <pre> * public class MyActivity extends Activity implements BusListener { * private Bus.Register<MyActivity> mBusReg; * public void onCreate(...) { * mBusReg = Bus.Register.register(this, globals.getBus()); * } * public void onDestroy() { * mBusReg.deregister(); * } * public void onBusMessage(int what, Object object) { ... } * public void foo() { * mBusReg.getBus().send(42); * } * } * </pre> * * This class only keeps weak references on the listener (typically an activity) and the bus. */ public static class Register<T extends IBusListener> extends BusAdapter { private WeakReference<Bus> mBusRef; private WeakReference<T> mReceiverRef; private Register(@Null Class<?> classFilter, T receiver, Bus bus) { mReceiverRef = new WeakReference<T>(receiver); mBusRef = new WeakReference<Bus>(bus); } @Null public Bus getBus() { return mBusRef.get(); } public void deregister() { if (mBusRef == null) return; Bus bus = mBusRef.get(); if (bus != null) bus.removeListener(this); mBusRef.clear(); mBusRef = null; if (mReceiverRef != null) { synchronized (this) { mReceiverRef.clear(); mReceiverRef = null; } } } @Override public void onBusMessage(int what, Object object) { T receiver = null; synchronized (this) { if (mReceiverRef != null) receiver = mReceiverRef.get(); } if (receiver != null) receiver.onBusMessage(what, object); } } }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/app/Bus.java
Java
gpl3
7,866
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.app; import com.rdrrlabs.example.annotations.Null; //----------------------------------------------- public abstract class BusAdapter implements com.rdrrlabs.example.liblabs.app.IBusListener { private final Class<?> mClassFilter; /** Creates a bus listener that receives all type of data. */ public BusAdapter() { this(null); } /** * Creates a bus listener that receives only object data of that type. * * @param classFilter The object class to filter. Can be null to receive everything. */ public BusAdapter(@Null Class<?> classFilter) { mClassFilter = classFilter; } public Class<?> getClassFilter() { return mClassFilter; } @Override public abstract void onBusMessage(int what, Object object); }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/app/BusAdapter.java
Java
gpl3
1,544
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.app; import com.rdrrlabs.example.annotations.Null; //----------------------------------------------- /** * Listen to {@link Bus} notifications. */ public interface IBusListener { /** * Callback invoked when a message matching the {@link BusAdapter} class filter * is received. * <p/> * Users must be aware that there is no thread specification -- the callback is * invoked on the sender's thread, which may or may not be the UI thread. * * @param what The integer "what" portion of the message. {@link Bus#NO_WHAT} if not specified. * @param object A potentially null message object. */ public abstract void onBusMessage(int what, @Null Object object); }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/app/IBusListener.java
Java
gpl3
1,463
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.utils; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.os.Build; import android.util.Log; public class Utils { public static final String TAG = Utils.class.getSimpleName(); public static final boolean DEBUG = true; private static int sSdkInt = 0; /** Returns current API level. The API level value is then cached. */ @SuppressWarnings("deprecation") public static int getApiLevel() { if (sSdkInt > 0) return sSdkInt; // Build.SDK_INT is only in API 4 and we're still compatible with API 3 try { int n = Integer.parseInt(Build.VERSION.SDK); sSdkInt = n; return n; } catch (Exception e) { Log.d(TAG, "Failed to parse Build.VERSION.SDK=" + Build.VERSION.SDK, e); return 3; } } /** Returns true if current API Level is equal or greater than {@code minApiLevel}. */ public static boolean checkMinApiLevel(int minApiLevel) { return getApiLevel() >= minApiLevel; } /** * Indicates whether the current platform reasonably looks like an emulator. * This could break if the emulator reported different values or if a custom * ROM was providing these values (e.g. one based on an emulator image.) */ public static boolean isEmulator() { // On the emulator: // Build.BRAND = generic // Build.DEVICE = generic // Build.MODEL = sdk // Build.PRODUCT = sdk or google_sdk (for the addon) // Build.MANUFACTURER = unknown -- API 4+ // Build.HARDWARE = goldfish -- API 8+ String b = Build.BRAND; String d = Build.DEVICE; String p = Build.PRODUCT; String h = null; //--ApiHelper.get().Build_HARDWARE(); if ("generic".equals(b) && "generic".equals(d) && (h == null || "goldfish".equals(h)) && ("sdk".equals(p) || "google_sdk".equals(p))) { Log.w(TAG, "Emulator Detected. Stats disabled."); return true; } return false; } // My debug key signature is // 30820255308201bea00302010202044a88ef41300d06092a864886f70d0101050500306f310b30090603550406130255533110300e06035504081307556e6b6e6f776e3110300e06035504071307556e6b6e6f776e310d300b060355040a130452616c663110300e060355040b1307556e6b6e6f776e311b301906035504031312416e64726f69642052616c66204465627567301e170d3039303831373035343834395a170d3337303130323035343834395a306f310b30090603550406130255533110300e06035504081307556e6b6e6f776e3110300e06035504071307556e6b6e6f776e310d300b060355040a130452616c663110300e060355040b1307556e6b6e6f776e311b301906035504031312416e64726f69642052616c6620446562756730819f300d06092a864886f70d010101050003818d0030818902818100aafbaa519b7a0cb0accb5cc37b6138b99bde072a952b291fb90cdb067e1f7c1980aac7152aee0304da0eb400d10dd7fef09e9e13f07ea09a3e500c86ba9fb93b5792003817cfd1639a9bffd085aa479521593d5ea516836e2eec5312c9044bafed29cf1339d4960ed96968fcbafd7ddd921b140b0de62f0576afa912789462630203010001300d06092a864886f70d01010505000381810027e6f99c4ef8c02d4dde0d1ec92bad13ea9ce85609e5d5e042e9800aca1e8472563be4fe6463ed1e12a72ff2780599d79ce03130925e345a196316b7ccab9b8941979c41e56c233d1a0a17f342cc74474615e7fde1340aac02c850b6119a708774973487250cd9d32e8c23ec8ed99d0a7ff07046c3ba53d387aa07805f6a8389 // hash = 1746973045 0x6820b175 // (to update this, empty first field and look in the log for the printed signature to match.) private static final String DEBUG_KEY_START = "30820255308201bea00302010202044"; private static final String DEBUG_KEY_END = "e8c23ec8ed99d0a7ff07046c3ba53d387aa07805f6a8389"; /** * Returns true if the current app is signed with my specific debug key. */ public static boolean isUsingDebugKey(Context context) { try { PackageInfo pi = context.getPackageManager().getPackageInfo( context.getPackageName(), PackageManager.GET_SIGNATURES); Signature[] sigs = pi.signatures; if (sigs == null || sigs.length != 1) { return false; } Signature sig = pi.signatures[0]; String str = sig.toCharsString(); if (DEBUG_KEY_START.length() == 0) { int hash = sig.hashCode(); Log.d(TAG, String.format("Sig [%08x]: %s", hash, str)); } else if (str != null && str.startsWith(DEBUG_KEY_START) && str.endsWith(DEBUG_KEY_END)) { Log.d(TAG, "Using Debug Key"); return true; } } catch (Exception e) { Log.e(TAG, "UsingKey exception: " + e.toString()); } return false; } }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/utils/Utils.java
Java
gpl3
5,648
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.utils; import android.util.Log; //----------------------------------------------- public abstract class ThreadLoop extends Thread { public static final String TAG = ThreadLoop.class.getSimpleName(); protected boolean mContinue = true; public ThreadLoop(String name) { super(name); } public ThreadLoop(String name, int priorityBoost) { this(name); this.setPriority(Thread.currentThread().getPriority() + priorityBoost); } /** * Called by the main activity when it's time to stop. * <p/> * Requirement: this MUST be called from another thread, not from GLBaseThread. * The activity thread is supposed to called this. * <p/> * This lets the thread complete it's render loop and wait for it * to fully stop using a join. */ public void threadWaitForStop() { // Not synchronized. Setting one boolean is assumed to be atomic. mContinue = false; try { assert Thread.currentThread() != this; threadWakeUp(); join(); } catch (InterruptedException e) { Log.e(TAG, "Thread.join failed", e); } } /** * Starts the thread if it wasn't already started. * Does nothing if started. */ @Override public synchronized void start() { if (getState() == State.NEW) { super.start(); } } // ----------------- /** * Base implementation of the thread loop. * Derived classes can re-implement this, as long as they follow this * contract: * - the loop must continue whilst mContinue is true * - each iteration must invoke threadRunIteration() when not paused. * - [deprecated] the loop must pause when mIsPaused is true by first * waiting for the pause barrier and do a waitForALongTime() until * mIsPaused is released. */ @Override public void run() { try { threadStartRun(); while (mContinue) { threadRunIteration(); } } catch (Exception e) { Log.e(TAG, "Run-Loop Exception, stopping thread", e); } finally { threadEndRun(); } } protected void threadStartRun() {} /** * Performs one iteration of the thread run loop. * Implementations must implement this and not throw exceptions from it. */ protected abstract void threadRunIteration(); protected void threadEndRun() {} public void threadSetCompleted() { mContinue = false; } public void threadWakeUp() { this.interrupt(); } public void threadWaitFor(long time_ms) { try { synchronized(this) { if (time_ms > 0) wait(time_ms); // TODO use SystemClock.sleep } } catch (InterruptedException e) { // pass } } }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/utils/ThreadLoop.java
Java
gpl3
3,673
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.utils; /** * A generic pair of 2 objects. * <p/> * (Note: Amusingly there's a similar class in android.util.Pair) */ public class Pair<U, V> { private final U mFirst; private final V mSecond; public Pair(U first, V second) { mFirst = first; mSecond = second; } public U getFirst() { return mFirst; } public V getSecond() { return mSecond; } // Java Tip: due to type erasure, the static create() X and Y types have // really nothing to do with the U & V types of the non-static Pair class. // Using different letters for the generic types makes this more obvious. // More details at http://stackoverflow.com/questions/936377/static-method-in-a-generic-class public static <X, Y> Pair<X, Y> create(X first, Y second) { return new Pair<X, Y>(first, second); } @SuppressWarnings("unchecked") public static <X, Y> Pair<X, Y>[] newArray(int size) { return new Pair[size]; } @Override public String toString() { return "Pair<" + (mFirst == null ? "(null)" : mFirst.toString()) + ", " + (mSecond == null ? "(null)" : mSecond.toString()) + ">"; } }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/utils/Pair.java
Java
gpl3
1,982
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.prefs; import com.rdrrlabs.example.annotations.PublicForTesting; import com.rdrrlabs.example.liblabs.serial.SerialKey; import com.rdrrlabs.example.liblabs.serial.SerialReader; import com.rdrrlabs.example.liblabs.serial.SerialWriter; import android.annotation.SuppressLint; import android.content.Context; import android.util.Log; import android.util.SparseArray; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.util.Arrays; /** * Wrapper around {@link SerialWriter} and {@link SerialReader} to deal with app prefs. * <p/> * Supported types are the minimal required for our needs: boolean, string and int. * Callers need to ensure that only one instance exists for the same file. * <p/> * Caller initial cycle should be: * - begingReadAsync * - endReadAsync ... this waits for the read the finish. * - read, add or modify data. * - modifying data generates a delayed write (or delays an existing one) * - flushSync must be called by the owner at least once, typically when an activity/app * is paused or about to finish. It forces a write or wait for an existing one to finish. * <p/> * Values cannot be null. * Affecting a value to null is equivalent to removing it from the storage map. */ public class BasePrefsStorage { /* * All prefs key constants used. * IMPORTANT: once set, value must NOT be changed. */ /** Issue (feedback report) number count. Type: integer. Strictly incremental. */ public final static String ISSUES_NUM_COUNT = "iss_id_count"; /** User-specific issue ID. Used to identify this user in feedback reports. Type: String. */ public final static String ISSUE_ID = "issue_id"; /** System wall time of last daily ping sent. Type: long. */ public final static String DAILY_PING_LAST_TS = "daily_ping_last_ts"; /** System wall time of next daily ping to send. Type: long. */ public final static String DAILY_PING_NEXT_TS = "daily_ping_next_ts"; private static final boolean DEBUG = true; public static final String TAG = BasePrefsStorage.class.getSimpleName(); /** * Special flag to rethrow exceptions when loading/saving fails. * In normal usage, callers will not see exceptions but load/save will just * return false in case of error, to not interrupt normal workflow. However * during unit tests we want hard errors. */ public static boolean THROW_EXCEPTIONS_WHEN_TESTING = false; /** * File header. Formatted to be 8 bytes (hoping it will help alignment). * The C identifies this is for 24 *C*lock. * The 1 can serve has a format version number in case we want to have future versions. */ private static final byte[] HEADER = new byte[] { 'P', 'R', 'E', 'F', '-', 'C', '1', '\0'}; private final SerialKey mKeyer = new SerialKey(); private final SparseArray<Object> mData = new SparseArray<Object>(); private final String mFilename; private volatile boolean mDataChanged; private volatile Thread mLoadThread; private volatile Thread mSaveThread; private volatile boolean mLoadResult; private volatile boolean mSaveResult; /** * Opens a serial prefs for "filename.sprefs" in the app's dir. * Caller must still read the file before anything happens. * * @param filename The end leaf filename. Must not be null or empty. * Must not contain any path separator. * This is not an absolute path -- the actual path will depend on the application package. */ public BasePrefsStorage(String filename) { mFilename = filename; } /** * Returns the filename that was given to the constructor. * This is not an absolute path -- the actual path will depend on the application package. */ public String getFilename() { return mFilename; } /** * Returns true if internal data has changed and it's worth * calling {@link #beginWriteAsync(Context)}. */ public boolean hasDataChanged() { return mDataChanged; } /** * Returns the absolute file path where the preference file is located. * It depends on the given context. * <p/> * This method is mostly useful for unit tests. Normal usage should have no use for that. */ public File getAbsoluteFile(Context context) { final Context appContext = context.getApplicationContext(); return appContext.getFileStreamPath(mFilename); } /** * Starts reading an existing prefs file asynchronously. * Callers <em>must</em> call {@link #endReadAsync()}. * * @param context The {@link Context} to use. */ public void beginReadAsync(Context context) { final Context appContext = context.getApplicationContext(); Thread t = new Thread() { @Override public void run() { FileInputStream fis = null; try { fis = appContext.openFileInput(mFilename); mLoadResult = loadChannel(fis.getChannel()); } catch (FileNotFoundException e) { // This is an expected error. if (DEBUG) Log.d(TAG, "fileNotFound"); mLoadResult = true; } catch (Exception e) { if (DEBUG) Log.e(TAG, "endReadAsync failed", e); } finally { try { if (fis != null) fis.close(); } catch (IOException ignore) {} } } }; synchronized(this) { Thread curr = mLoadThread; if (curr != null) { if (DEBUG) Log.d(TAG, "Load already pending."); return; } else { mLoadThread = t; t.start(); } } } /** * Makes sure the asynchronous read has finished. * Callers must call this at least once before they access * the underlying storage. * @return The result from the last load operation: * True if the file was correctly read OR if the file doesn't exist. * False if the false exists and wasn't correctly read. */ public boolean endReadAsync() { Thread t = null; synchronized(this) { t = mLoadThread; if (t != null) mLoadThread = null; } if (t != null) { try { t.join(); } catch (InterruptedException e) { if (DEBUG) Log.w(TAG, e); } } return mLoadResult; } /** * Saves the prefs if they have changed. * * @param context The app context. * @return True if prefs could be written, false otherwise. */ public boolean writeSync(Context context) { if (!mDataChanged) { return true; } beginWriteAsync(context); return endWriteAsync(); } /** * Starts saving an existing prefs file asynchronously. * Nothing happens if there's no data changed and there's already a pending save operation. * * @param context The {@link Context} to use. */ public void beginWriteAsync(Context context) { if (!mDataChanged) { return; } final Context appContext = context.getApplicationContext(); Thread t = new Thread() { @Override public void run() { FileOutputStream fos = null; try { fos = appContext.openFileOutput(mFilename, Context.MODE_PRIVATE); synchronized(mData) { saveChannel(fos.getChannel()); mDataChanged = false; } try { // Notify the backup manager that data might have changed //--new BackupWrapper(appContext).dataChanged(); } catch(Exception ignore) {} mSaveResult = true; } catch (Throwable t) { mSaveResult = false; if (DEBUG) Log.e(TAG, "flushSync failed", t); if (THROW_EXCEPTIONS_WHEN_TESTING) throw new RuntimeException(t); } finally { synchronized(BasePrefsStorage.this) { mSaveThread = null; } try { if (fos != null) fos.close(); } catch (IOException ignore) {} } } }; synchronized(this) { Thread curr = mSaveThread; if (curr != null) { if (DEBUG) Log.d(TAG, "Save already pending."); return; } else { mSaveThread = t; t.start(); } } } /** * Makes sure the asynchronous save has finished. * * @return The result from the last save operation: * True if the file was correctly saved. */ public boolean endWriteAsync() { Thread t = null; synchronized(this) { t = mSaveThread; } if (t != null) { try { t.join(); } catch (InterruptedException e) { if (DEBUG) Log.w(TAG, e); } } return mSaveResult; } // --- put public void putInt(String key, int value) { synchronized(mData) { int intKey = mKeyer.encodeNewKey(key); Integer newVal = Integer.valueOf(value); Object curVal = mData.get(intKey); if (!newVal.equals(curVal)) { mData.put(intKey, newVal); mDataChanged = true; } } } public void putLong(String key, long value) { synchronized(mData) { int intKey = mKeyer.encodeNewKey(key); Long newVal = Long.valueOf(value); Object curVal = mData.get(intKey); if (!newVal.equals(curVal)) { mData.put(intKey, newVal); mDataChanged = true; } } } public void putBool(String key, boolean value) { synchronized(mData) { int intKey = mKeyer.encodeNewKey(key); Boolean newVal = Boolean.valueOf(value); Object curVal = mData.get(intKey); if (!newVal.equals(curVal)) { mData.put(intKey, newVal); mDataChanged = true; } } } public void putString(String key, String value) { synchronized(mData) { int intKey = mKeyer.encodeNewKey(key); Object curVal = mData.get(intKey); if ((value == null && curVal != null) || (value != null && !value.equals(curVal))) { mData.put(intKey, value); mDataChanged = true; } } } // --- has public boolean hasKey(String key) { synchronized(mData) { return mData.indexOfKey(mKeyer.encodeKey(key)) >= 0; } } public boolean hasInt(String key) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } return o instanceof Integer; } public boolean hasLong(String key) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } return o instanceof Long; } public boolean hasBool(String key) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } return o instanceof Boolean; } public boolean hasString(String key) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } return o instanceof String; } // --- get public int getInt(String key, int defValue) { if (endReadAsync()) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } if (o instanceof Integer) { return ((Integer) o).intValue(); } else if (o != null) { throw new TypeMismatchException(key, "int", o); } } return defValue; } public long getLong(String key, long defValue) { return getLong(key, defValue, true); // default is to convert int-to-long } public long getLong(String key, long defValue, boolean convertIntToLong) { if (endReadAsync()) { Object o = null; int intKey = mKeyer.encodeKey(key); synchronized(mData) { o = mData.get(intKey); } if (o instanceof Long) { return ((Long) o).longValue(); } else if (o instanceof Integer && convertIntToLong) { return ((Integer) o).intValue(); } else if (o != null) { throw new TypeMismatchException(key, "int or long", o); } } return defValue; } public boolean getBool(String key, boolean defValue) { if (endReadAsync()) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } if (o instanceof Boolean) { return ((Boolean) o).booleanValue(); } else if (o != null) { throw new TypeMismatchException(key, "boolean", o); } } return defValue; } public String getString(String key, String defValue) { if (endReadAsync()) { Object o = null; synchronized(mData) { o = mData.get(mKeyer.encodeKey(key)); } if (o instanceof String) { return (String) o; } else if (o != null) { throw new TypeMismatchException(key, "String", o); } } return defValue; } // ---- @SuppressLint("NewApi") // Lint incorrectly flags ByteBuffer.array() as API 9+, but it's really 1+. @PublicForTesting protected boolean loadChannel(FileChannel fileChannel) throws IOException { // Size should be a multiple of 4. Always. // assert (Integer.SIZE / 8) == 4; long n = fileChannel.size(); if (n < HEADER.length || (n & 0x03) != 0) { Log.d(TAG, "Invalid file size, should be multiple of 4."); return false; } assert (HEADER.length & 0x03) == 0; ByteBuffer header = ByteBuffer.allocate(HEADER.length); header.order(ByteOrder.LITTLE_ENDIAN); int r = fileChannel.read(header); if (r != HEADER.length || !Arrays.equals(HEADER, header.array())) { Log.d(TAG, "Invalid file format, wrong header."); return false; } n -= r; header = null; if (n > Integer.MAX_VALUE) { Log.d(TAG, "Invalid file size, file is too large."); return false; } // read all data ByteBuffer bytes = ByteBuffer.allocateDirect((int) n); bytes.order(ByteOrder.LITTLE_ENDIAN); r = fileChannel.read(bytes); if (r != n) { Log.d(TAG, "Failed to read all data."); return false; } // convert to an int buffer int[] data = new int[bytes.capacity() / 4]; bytes.position(0); // rewind and read bytes.asIntBuffer().get(data); SerialReader sr = new SerialReader(data); synchronized(mData) { mData.clear(); for (SerialReader.Entry entry : sr) { mData.append(entry.getKey(), entry.getValue()); } mDataChanged = false; } return true; } @PublicForTesting protected void saveChannel(FileChannel fileChannel) throws IOException { BufferedWriter bw = null; try { ByteBuffer header = ByteBuffer.wrap(HEADER); header.order(ByteOrder.LITTLE_ENDIAN); if (fileChannel.write(header) != HEADER.length) { throw new IOException("Failed to write header."); } SerialWriter sw = new SerialWriter(); for (int n = mData.size(), i = 0; i < n; i++) { int key = mData.keyAt(i); Object value = mData.valueAt(i); // no need to store null values. if (value == null) continue; if (value instanceof Integer) { sw.addInt(key, ((Integer) value).intValue()); } else if (value instanceof Long) { sw.addLong(key, ((Long) value).longValue()); } else if (value instanceof Boolean) { sw.addBool(key, ((Boolean) value).booleanValue()); } else if (value instanceof String) { sw.addString(key, (String) value); } else { throw new UnsupportedOperationException( this.getClass().getSimpleName() + " does not support type " + value.getClass().getSimpleName()); } } int[] data = sw.encodeAsArray(); ByteBuffer bytes = ByteBuffer.allocateDirect(data.length * 4); bytes.order(ByteOrder.LITTLE_ENDIAN); bytes.asIntBuffer().put(data); fileChannel.write(bytes); } finally { if (bw != null) { try { bw.close(); } catch (IOException ignore) {} } } } public static class TypeMismatchException extends RuntimeException { private static final long serialVersionUID = -6386235026748640081L; public TypeMismatchException(String key, String expected, Object actual) { super(String.format("Key '%1$s' excepted type %2$s, got %3$s", key, expected, actual.getClass().getSimpleName())); } } }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/prefs/BasePrefsStorage.java
Java
gpl3
19,256
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.prefs; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.util.Log; public class BasePrefsValues { protected final SharedPreferences mPrefs; public BasePrefsValues(Context context) { mPrefs = PreferenceManager.getDefaultSharedPreferences(context); } public BasePrefsValues(SharedPreferences prefs) { mPrefs = prefs; } public SharedPreferences getPrefs() { return mPrefs; } public Object editLock() { return BasePrefsValues.class; } /** Returns a shared pref editor. Must call endEdit() later. */ public Editor startEdit() { return mPrefs.edit(); } /** Commits an open editor. */ public boolean endEdit(Editor e, String tag) { boolean b = e.commit(); if (!b) Log.w(tag, "Prefs.edit.commit failed"); return b; } public boolean isIntroDismissed() { return mPrefs.getBoolean("dismiss_intro", false); } public void setIntroDismissed(boolean dismiss) { synchronized (editLock()) { mPrefs.edit().putBoolean("dismiss_intro", dismiss).commit(); } } public int getLastIntroVersion() { return mPrefs.getInt("last_intro_vers", 0); } public void setLastIntroVersion(int lastIntroVers) { synchronized (editLock()) { mPrefs.edit().putInt("last_intro_vers", lastIntroVers).commit(); } } public String getLastExceptions() { return mPrefs.getString("last_exceptions", null); } public void setLastExceptions(String s) { synchronized (editLock()) { mPrefs.edit().putString("last_exceptions", s).commit(); } } public String getLastActions() { return mPrefs.getString("last_actions", null); } public void setLastActions(String s) { synchronized (editLock()) { mPrefs.edit().putString("last_actions", s).commit(); } } }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/prefs/BasePrefsValues.java
Java
gpl3
2,825
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.serial; import java.util.zip.CRC32; import com.rdrrlabs.example.liblabs.serial.SerialKey.DuplicateKey; /** * Encoder/decoder for typed data. * Extracted from NerdkillAndroid. * <p/> * * A {@link SerialWriter} serialized typed key/values to an int array. * Each key is identified by a name -- however <em>only</em> the hashcode * of the key string is used as an id, not the exact string itself. <br/> * An exception {@link DuplicateKey} is thrown when trying to add a key * that has the same string hashcode than an already present key. <br/> * The assumption is made that string hashcodes are stable for a given * interpreting machine (e.g. JVM or Dalvik). * <p/> * * <p/> * Supported types: <br/> * - integer <br/> * - long <br/> * - bool <br/> * - float <br/> * - double <br/> * - string <br/> * - {@link SerialWriter} * <p/> * * The type {@link SerialWriter} can be used to embedded a struct within * a struct. * <p/> * * Users of the serialized data can either directly process the int[] array * using {@link #encodeAsArray()} or can transform it to a semi-compact hexa * string using {@link #encodeAsString()}. Both can later be decoded using * {@link SerialReader}. * <p/> * * A typical strategy is for a serializable struct to contain a * <code>saveInto(SerialWriter)</code> method. Whatever code that does * the saving can thus first create a {@link SerialWriter} and pass it * to the struct so that it can save itself into the given writer. * <br/> * Another strategy is for the struct to have a method that creates the * {@link SerialWriter}, adds all the fields and then return the writer. * <br/> * Both approaches are valid. The former is useful if the outer and inner * methods are working in collaboration, the later is useful if both sides * should be agnostic to each other. * <p/> * * Format of the encoded int array: * The serialized data starts with a header describing the data size, * followed by one entry per field added in the order of the addXyz() calls. * Finally there's a CRC and an EOF marker. * * <pre> * - header: * - 1 int: number of ints to follow (including this and CRC + EOF marker) * - entries: * - 1 int: type, ascii for I L B F D S or Z * - 1 int: key * - int, bool, float: 1 int, value * - long, double: 2 int value (MSB + LSB) * - string: 1 int = number of chars following, then int = c1 | c2 (0 padding as needed) * - serializer: (self, starting with number of ints to follow) * - 1 int: CRC (of all previous ints including header, excluding this and EOF) * - 1 int: EOF * </pre> */ public class SerialWriter { public static class CantAddData extends RuntimeException { private static final long serialVersionUID = 8074293730213951679L; public CantAddData(String message) { super(message); } } private final SerialKey mKeyer = new SerialKey(); private int[] mData; private int mSize; private boolean mCantAdd; static final int TYPE_INT = 1; static final int TYPE_LONG = 2; static final int TYPE_BOOL = 3; static final int TYPE_FLOAT = 4; static final int TYPE_DOUBLE = 5; static final int TYPE_STRING = 6; static final int TYPE_SERIAL = 7; static final int EOF = 0x0E0F; public SerialWriter() { } public int[] encodeAsArray() { close(); // Resize the array to be of its exact size if (mData.length > mSize) { int[] newArray = new int[mSize]; System.arraycopy(mData, 0, newArray, 0, mSize); mData = newArray; } return mData; } public String encodeAsString() { int[] a = encodeAsArray(); int n = a.length; char[] cs = new char[n * 9]; int j = 0; for (int i = 0; i < n; i++) { int v = a[i]; // Write nibbles in MSB-LSB order, skipping leading zeros boolean skipZero = true; for (int k = 0; k < 8; k++) { int b = (v >> 28) & 0x0F; v = v << 4; if (skipZero) { if (b == 0) { if (k < 7) { continue; } } else { skipZero = false; } } char c = b < 0x0A ? (char)('0' + b) : (char)('A' - 0x0A + b); cs[j++] = c; } cs[j++] = ' '; } return new String(cs, 0, j); } //-- /** * @throws DuplicateKey if the key had already been registered. */ public void addInt(String name, int intValue) { addInt(mKeyer.encodeUniqueKey(name), intValue); } /** * @throws DuplicateKey if the key had already been registered. */ public void addLong(String name, long longValue) { addLong(mKeyer.encodeUniqueKey(name), longValue); } /** * @throws DuplicateKey if the key had already been registered. */ public void addBool(String name, boolean boolValue) { addBool(mKeyer.encodeUniqueKey(name), boolValue); } /** * @throws DuplicateKey if the key had already been registered. */ public void addFloat(String name, float floatValue) { addFloat(mKeyer.encodeUniqueKey(name), floatValue); } /** * @throws DuplicateKey if the key had already been registered. */ public void addDouble(String name, double doubleValue) { addDouble(mKeyer.encodeUniqueKey(name), doubleValue); } /** Add a string. Doesn't add a null value. * @throws DuplicateKey if the key had already been registered. */ public void addString(String name, String strValue) { addString(mKeyer.encodeUniqueKey(name), strValue); } /** Add a Serial. Doesn't add a null value. */ public void addSerial(String name, SerialWriter serialValue) { addSerial(mKeyer.encodeUniqueKey(name), serialValue); } //-- public void addInt(int key, int intValue) { _addInt(key, TYPE_INT, intValue); } public void addLong(int key, long longValue) { _addLong(key, TYPE_LONG, longValue); } public void addBool(int key, boolean boolValue) { _addInt(key, TYPE_BOOL, boolValue ? 1 : 0); } public void addFloat(int key, float floatValue) { _addInt(key, TYPE_FLOAT, Float.floatToIntBits(floatValue)); } public void addDouble(int key, double doubleValue) { _addLong(key, TYPE_DOUBLE, Double.doubleToLongBits(doubleValue)); } /** Add a string. Doesn't add a null value. */ public void addString(int key, String strValue) { if (strValue == null) return; int n = strValue.length(); int m = (n + 1) / 2; int pos = alloc(2 + m + 1); mData[pos++] = TYPE_STRING; mData[pos++] = key; mData[pos++] = n; for (int i = 0; i < n;) { char c1 = strValue.charAt(i++); char c2 = i >= n ? 0 : strValue.charAt(i++); int j = (c1 << 16) | (c2 & 0x0FFFF); mData[pos++] = j; } mSize = pos; } /** Add a Serial. Doesn't add a null value. */ public void addSerial(int key, SerialWriter serialValue) { if (serialValue == null) return; int[] a = serialValue.encodeAsArray(); int n = a.length; int pos = alloc(2 + n); mData[pos++] = TYPE_SERIAL; mData[pos++] = key; System.arraycopy(a, 0, mData, pos, n); pos += n; mSize = pos; } //--- private int alloc(int numInts) { if (mCantAdd) { throw new CantAddData("Serial data has been closed by a call to encode(). Can't add anymore."); } if (mData == null) { // Reserve the header int mData = new int[numInts + 1]; mSize = 1; return mSize; } int s = mSize; int n = s + numInts; if (mData.length < n) { // need to realloc int[] newArray = new int[s+n]; System.arraycopy(mData, 0, newArray, 0, s); mData = newArray; } return mSize; } private void _addInt(int key, int type, int value) { int pos = alloc(2+1); mData[pos++] = type; mData[pos++] = key; mData[pos++] = value; mSize = pos; } private void _addLong(int key, int type, long value) { int pos = alloc(2+2); mData[pos++] = type; mData[pos++] = key; // MSB first mData[pos++] = (int) (value >> 32); // LSB next mData[pos++] = (int) (value & 0xFFFFFFFF); mSize = pos; } /** Closing the array adds the CRC and the EOF. Can't add anymore once this is done. */ private void close() { // can't close the array twice if (mCantAdd) return; int pos = alloc(2); // write the header, the first int is the full size in ints mData[0] = pos + 2; // write the CRC and EOF footer mData[pos ] = computeCrc(mData, 0, pos); mData[pos+1] = EOF; mSize += 2; mCantAdd = true; } /* This is static so that we can reuse it as-is in the reader class. */ static int computeCrc(int[] data, int offset, int length) { CRC32 crc = new CRC32(); for (; length > 0; length--) { int v = data[offset++]; crc.update(v & 0x0FF); v = v >> 8; crc.update(v & 0x0FF); v = v >> 8; crc.update(v & 0x0FF); v = v >> 8; crc.update(v & 0x0FF); } return (int) crc.getValue(); } }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/serial/SerialWriter.java
Java
gpl3
10,588
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.serial; import java.util.Iterator; import android.util.SparseArray; /** * Encoder/decoder for typed data. * Extracted from NerdkillAndroid. * * See {@link SerialWriter} for implementations details. */ public class SerialReader implements Iterable<SerialReader.Entry> { public static final String TAG = SerialReader.class.getSimpleName(); public class Entry { private final int mKey; private final Object mValue; public Entry(int key, Object value) { mKey = key; mValue = value; } public int getKey() { return mKey; } public Object getValue() { return mValue; } } public static class DecodeError extends RuntimeException { private static final long serialVersionUID = -8603565615795418588L; public DecodeError(String message) { super(message); } } static final int TYPE_INT = SerialWriter.TYPE_INT; static final int TYPE_LONG = SerialWriter.TYPE_LONG; static final int TYPE_BOOL = SerialWriter.TYPE_BOOL; static final int TYPE_FLOAT = SerialWriter.TYPE_FLOAT; static final int TYPE_DOUBLE = SerialWriter.TYPE_DOUBLE; static final int TYPE_STRING = SerialWriter.TYPE_STRING; static final int TYPE_SERIAL = SerialWriter.TYPE_SERIAL; static final int EOF = SerialWriter.EOF; private final SparseArray<Object> mData = new SparseArray<Object>(); private final SerialKey mKeyer = new SerialKey(); public SerialReader(String data) { decodeString(data); } public SerialReader(int[] data, int offset, int length) { decodeArray(data, offset, length); } public SerialReader(int[] data) { this(data, 0, data.length); } /** * A shortcut around {@link SerialReader#SerialReader(int[])} useful for unit tests. */ public SerialReader(SerialWriter sw) { this(sw.encodeAsArray()); } public int size() { return mData.size(); } public boolean hasName(String name) { int id = mKeyer.encodeKey(name); return mData.indexOfKey(id) >= 0; } public int getInt(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return 0; if (d instanceof Integer) return ((Integer) d).intValue(); throw new ClassCastException("Int expected, got " + d.getClass().getSimpleName()); } public long getLong(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return 0; if (d instanceof Long) return ((Long) d).longValue(); throw new ClassCastException("Long expected, got " + d.getClass().getSimpleName()); } public boolean getBool(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return false; if (d instanceof Boolean) return ((Boolean) d).booleanValue(); throw new ClassCastException("Bool expected, got " + d.getClass().getSimpleName()); } public float getFloat(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return 0; if (d instanceof Float) return ((Float) d).floatValue(); throw new ClassCastException("Float expected, got " + d.getClass().getSimpleName()); } public double getDouble(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return 0; if (d instanceof Double) return ((Double) d).doubleValue(); throw new ClassCastException("Double expected, got " + d.getClass().getSimpleName()); } public String getString(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return null; if (d instanceof String) return (String) d; throw new ClassCastException("String expected, got " + d.getClass().getSimpleName()); } public SerialReader getSerial(String name) { int id = mKeyer.encodeKey(name); Object d = mData.get(id); if (d == null) return null; if (d instanceof SerialReader) return (SerialReader) d; throw new ClassCastException("SerialReader expected, got " + d.getClass().getSimpleName()); } @Override public Iterator<Entry> iterator() { return new Iterator<Entry>() { final int n = mData.size(); int index = 0; @Override public boolean hasNext() { return index < n; } @Override public Entry next() { Entry e = new Entry(mData.keyAt(index), mData.valueAt(index)); index++; return e; } @Override public void remove() { throw new UnsupportedOperationException( "Remove is not supported by " + SerialReader.class.getSimpleName()); } }; } //--- private static class IntArray { public int[] a = new int[16]; public int n = 0; public void add(long i) { if (n == a.length) { int[] newArray = new int[2 * a.length]; System.arraycopy(a, 0, newArray, 0, n); a = newArray; } int j = (int) (i & 0x0FFFFFFFFL); a[n++] = j; } } private void decodeString(String data) { IntArray a = new IntArray(); if (data == null || data.length() == 0) { throw new DecodeError("No data to decode."); } // Read a bunch of hexa numbers separated by non-hex chars char[] cs = data.toCharArray(); int cn = cs.length; int size = 0; long i = -1; for (int k = 0; k < cn; k++) { char c = cs[k]; if (c >= '0' && c <= '9') { if (i == -1) i = 0; i = (i << 4) + c - '0'; } else if (c >= 'a' && c <= 'f') { if (i == -1) i = 0; i = (i << 4) + c - 'a' + 0x0A; } else if (c >= 'A' && c <= 'F') { if (i == -1) i = 0; i = (i << 4) + c - 'A' + 0x0A; } else if (i >= 0) { a.add(i); i = -1; // The first int indicates how many ints we needed to read. // There's no need to try to read any more than that, we wouldn't // use it anyway. if (a.n == 1) { size = a.a[0]; } else if (a.n >= size) { break; } } } if (i >= 0) a.add(i); decodeArray(a.a, 0, a.n); } private void decodeArray(int[] data, int offset, int length) { // get the size in ints int size = data.length > offset ? data[offset] : 0; int end = size + offset; // An empty message has at least 3 ints. if (size < 3 || end > data.length || offset + length > data.length) { throw new DecodeError("Message too short. Not enough data found."); } if (data[end - 1] != EOF) { throw new DecodeError("Missing EOF."); } // Compute the CRC without the 2-int footer int crc = SerialWriter.computeCrc(data, offset, size - 2); if (data[end - 2] != crc) { throw new DecodeError("Invalid CRC."); } // Nothing to do if this is an empty message. if (size == 3) return; // disregard the ending CRC and EOF now end -= 2; // skip the size int offset++; while (offset < end) { // The smallest type needs 3 ints: type, id, 1 int if (offset + 3 > end) { throw new DecodeError("Not enough data to decode short primitive."); } int type = data[offset++]; int id = data[offset++]; int i1, i2; switch(type) { case TYPE_INT: i1 = data[offset++]; mData.put(id, Integer.valueOf(i1)); break; case TYPE_BOOL: i1 = data[offset++]; boolean b = i1 != 0; mData.put(id, Boolean.valueOf(b)); break; case TYPE_FLOAT: i1 = data[offset++]; float f = Float.intBitsToFloat(i1); mData.put(id, Float.valueOf(f)); break; case TYPE_LONG: case TYPE_DOUBLE: if (offset + 2 > end) throw new DecodeError("Not enough data to decode long primitive."); i1 = data[offset++]; i2 = data[offset++]; long L = ((long)i1) << 32; long L2 = i2; L |= L2 & 0x0FFFFFFFFL; if (type == TYPE_LONG) { mData.put(id, new Long(L)); } else { double d = Double.longBitsToDouble(L); mData.put(id, Double.valueOf(d)); } break; case TYPE_STRING: int char_size = data[offset++]; int m = (char_size + 1) / 2; if (offset + m > end) throw new DecodeError("Not enough data to decode string type."); char[] cs = new char[char_size]; for (int i = 0; i < char_size; ) { i1 = data[offset++]; char c = (char) ((i1 >> 16) & 0x0FFFF); cs[i++] = c; if (i < char_size) { c = (char) (i1 & 0x0FFFF); cs[i++] = c; } } String s = new String(cs); mData.put(id, s); break; case TYPE_SERIAL: // The next int must be the header of the serial data, which conveniently // starts with its own size. int sub_size = data[offset]; if (offset + sub_size > end) { throw new DecodeError("Not enough data to decode sub-serial type."); } else if (data[offset + sub_size - 1] != EOF) { throw new DecodeError("Missing EOF in sub-serial type."); } SerialReader sr = new SerialReader(data, offset, sub_size); mData.put(id, sr); offset += sub_size; break; } } } }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/serial/SerialReader.java
Java
gpl3
11,476
/* * Copyright (C) 2013 rdrrlabs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.liblabs.serial; import android.util.SparseArray; /** * Encode keys used by {@link SerialWriter}. * <p/> * Keys are transformed in a unique integer. * In case of collision, {@link DuplicateKey} is thrown. */ public class SerialKey { public static class DuplicateKey extends RuntimeException { private static final long serialVersionUID = -1735763023714511003L; public DuplicateKey(String message) { super(message); } } private SparseArray<String> mUsedKeys = null; /** * Encode a key name into an integer. * <p/> * There's a risk of collision when adding keys: different names can map to * the same encoded integer. If this is the case and the key is different * then a {@link DuplicateKey} is thrown. It is ok to register twice the * same key name, which will result in the same value being returned. * * @param name The name of the key. Must not be empty nor null. * @return The integer associated with that key name. * @throws DuplicateKey if the key collides with a different one. */ public int encodeNewKey(String name) { if (mUsedKeys == null) mUsedKeys = new SparseArray<String>(); int key = encodeKey(name); int index = mUsedKeys.indexOfKey(key); if (index >= 0) { String previous = mUsedKeys.valueAt(index); if (!name.equals(previous)) { throw new DuplicateKey( String.format("Key name collision: '%1$s' has the same hash than previously used '%2$s'", name, previous)); } } else { mUsedKeys.put(key, name); } return key; } /** * Encode a key name into an integer and makes sure the key name is unique * and has never be registered before. * * @param name The name of the key. Must not be empty nor null. * @return The integer associated with that key name. * @throws DuplicateKey if the key had already been registered. */ public int encodeUniqueKey(String name) { if (mUsedKeys == null) mUsedKeys = new SparseArray<String>(); int key = encodeKey(name); int index = mUsedKeys.indexOfKey(key); if (index >= 0) { String previous = mUsedKeys.valueAt(index); throw new DuplicateKey( String.format("Key name collision: '%1$s' has the same hash than previously used '%2$s'", name, previous)); } mUsedKeys.put(key, name); return key; } /** * Encode a key name into an integer. * <p/> * Unlike {@link #encodeNewKey(String)}, this does not check whether the key has already * been used. * * @param name The name of the key. Must not be empty nor null. * @return The integer associated with that key name. */ public int encodeKey(String name) { int key = name.hashCode(); return key; } }
110165172-description
TimeriSample/LibLabs/src/main/java/com/rdrrlabs/example/liblabs/serial/SerialKey.java
Java
gpl3
3,740
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import com.rdrrlabs.example.timer1app.core.app.Core; import com.rdrrlabs.example.timer1app.core.error.ExceptionHandler; public class UpdateService extends Service { public static final String TAG = UpdateService.class.getSimpleName(); private static final boolean DEBUG = false; @Override public IBinder onBind(Intent intent) { // pass return null; } //---- @Override public void onStart(Intent intent, int startId) { if (DEBUG) Log.d(TAG, "Start service"); ExceptionHandler handler = new ExceptionHandler(this); try { super.onStart(intent, startId); Core core = TimerifficApp.getInstance(this).getCore(); core.getUpdateService().onStart(this, intent, startId); } finally { handler.detach(); if (DEBUG) Log.d(TAG, "Stopping service"); stopSelf(); } } @Override public void onDestroy() { Core core = TimerifficApp.getInstance(this).getCore(); core.getUpdateService().onDestroy(this); super.onDestroy(); } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/app/UpdateService.java
Java
gpl3
2,005
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import java.io.IOException; import java.lang.reflect.Method; import android.app.backup.BackupAgentHelper; import android.app.backup.BackupDataInput; import android.app.backup.BackupDataOutput; import android.app.backup.FileBackupHelper; import android.app.backup.SharedPreferencesBackupHelper; import android.content.Context; import android.os.ParcelFileDescriptor; import android.preference.PreferenceManager; import android.util.Log; import com.rdrrlabs.example.timer1app.core.app.BackupWrapper; import com.rdrrlabs.example.timer1app.core.prefs.PrefsStorage; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesDB; /** * Backup agent to backup/restore both preferences and main database. * Used only with Froyo (Android API level 8) and above. * <p/> * This class is never referenced directly except by a class name reference * in the &lt;application&gt; tag of the manifest. * <p/> * Implementation detail: since {@link TimerifficBackupAgent} depends * on the BackupAgent class, it is not available on platform < API 8. * This means any direct access to this class must be avoided. E.g. to * get the lock, callers must use the {@link BackupWrapper} instead. * <p/> * TODO exclude from Proguard */ public class TimerifficBackupAgent extends BackupAgentHelper { /* * References for understanding this: * * - BackupAgent: * http://d.android.com/reference/android/app/backup/BackupAgent.html * * - FileHelperExampleAgent.java in the BackupRestore sample for * the Froyo/2.2 Samples. */ public static final String TAG = TimerifficBackupAgent.class.getSimpleName(); private static final String KEY_DEFAULT_SHARED_PREFS = "default_shared_prefs"; private static final String KEY_PROFILES_DB = "profiles_db"; private static final String KEY_PREFS_STORAGE = "prefs_storage_"; @Override public void onCreate() { super.onCreate(); // --- shared prefs backup --- // The sharedPreferencesBackupHelper wants the name of the shared pref, // however the "default" name is not given by any public API. Try // to retrieve it via reflection. This may fail if the method changes // in future Android APIs. String sharedPrefsName = null; try { Method m = PreferenceManager.class.getMethod( "getDefaultSharedPreferencesName", new Class<?>[] { Context.class } ); Object v = m.invoke(null /*receiver*/, (Context) this); if (v instanceof String) { sharedPrefsName = (String) v; } } catch (Exception e) { // ignore } if (sharedPrefsName == null) { // In case the API call fails, we implement it naively ourselves // like it used to be done in Android 1.6 (API Level 4) sharedPrefsName = this.getPackageName() + "_preferences"; } if (sharedPrefsName != null) { SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, sharedPrefsName); addHelper(KEY_DEFAULT_SHARED_PREFS, helper); Log.d(TAG, "Register backup 1 for " + sharedPrefsName); } // --- pref storage backup --- // Use the backup helper for the new app's pref storage. PrefsStorage ps = TimerifficApp.getInstance(this).getPrefsStorage(); if (ps != null) { String name = ps.getFilename(); FileBackupHelper helper = new FileBackupHelper(this, name); addHelper(KEY_PREFS_STORAGE + name, helper); Log.d(TAG, "Register backup 2 for " + name); } // --- profiles db backup --- // Use the backup helper for the profile database. // The FileBackupHelper defaults to a file under getFilesDir() // so we need to trim the full database path. String filesPath = getFilesDir().getAbsolutePath(); String dbPath = ProfilesDB.getDatabaseFile(this).getAbsolutePath(); if (filesPath != null && dbPath != null) { dbPath = relativePath(filesPath, dbPath); FileBackupHelper helper = new FileBackupHelper(this, dbPath); addHelper(KEY_PROFILES_DB, helper); Log.d(TAG, "Register backup 3 for " + dbPath); } } @Override public void onBackup( ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException { // Hold the lock while the helper performs the backup operation synchronized (BackupWrapper.getBackupLock()) { super.onBackup(oldState, data, newState); Log.d(TAG, "onBackup"); } } @Override public void onRestore( BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { // Hold the lock while the helper restores the file from // the data provided here. synchronized (BackupWrapper.getBackupLock()) { super.onRestore(data, appVersionCode, newState); Log.d(TAG, "onRestore"); } } /** * Computes a relative path from source to dest. * e.g. if source is A/B and dest is A/C/D, the relative path is ../C/D * <p/> * Source and dest are expected to be absolute unix-like, e.g. /a/b/c */ private String relativePath(String source, String dest) { // Implementation: we're working with unix-like stuff that is absolute // so /a/b/c => { "", "a", "b", "c" } // // In our use-case we can't have source==dest, so we don't handle it. String[] s = source.split("/"); String[] d = dest.split("/"); // Find common root part and ignore it. int common = 0; while (common < s.length && common < d.length && s[common].equals(d[common])) { common++; } // Now we need as many ".." as dirs left in source to go back to the // common root. String result = ""; for (int i = common; i < s.length; i++) { if (result.length() > 0) result += "/"; result += ".."; } // Finally add whatever is not a common root from the dest for (int i = common; i < d.length; i++) { if (result.length() > 0) result += "/"; result += d[i]; } return result; } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/app/TimerifficBackupAgent.java
Java
gpl3
7,331
/* * Project: Timeriffic * Copyright (C) 2011 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; public class TimerifficAppBase extends TimerifficApp { public TimerifficAppBase() { super(); } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/app/TimerifficAppBase.java
Java
gpl3
892
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; public class PhoneStateService extends Service { private MyPhoneStateListener mPSListener; @Override public IBinder onBind(Intent intent) { // pass return null; } @Override public void onCreate() { Context context = getApplicationContext(); TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (mPSListener == null) { mPSListener = new MyPhoneStateListener(); } telephony.listen(mPSListener, PhoneStateListener.LISTEN_CALL_STATE); super.onCreate(); } @Override public void onDestroy() { if (mPSListener != null) { Context context = getApplicationContext(); TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); telephony.listen(mPSListener, PhoneStateListener.LISTEN_NONE); mPSListener = null; } super.onDestroy(); } private class MyPhoneStateListener extends PhoneStateListener { @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); } } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/app/PhoneStateService.java
Java
gpl3
2,267
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import com.rdrrlabs.example.timer1app.core.app.Core; import com.rdrrlabs.example.timer1app.core.error.ExceptionHandler; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; public class UpdateReceiver extends BroadcastReceiver { public final static String TAG = UpdateReceiver.class.getSimpleName(); private final static boolean DEBUG = false; /** Name of intent to broadcast to activate this receiver when doing * alarm-based apply-state. */ public final static String ACTION_APPLY_STATE = "com.rdrrlabs.intent.action.APPLY_STATE"; /** Name of intent to broadcast to activate this receiver when triggering * a check from the UI. */ public final static String ACTION_UI_CHECK = "com.rdrrlabs.intent.action.UI_CHECK"; /** Name of an extra int: how we should display a toast for next event. */ public final static String EXTRA_TOAST_NEXT_EVENT = "toast-next"; public final static int TOAST_NONE = 0; public final static int TOAST_IF_CHANGED = 1; public final static int TOAST_ALWAYS = 2; /** * Starts the {@link UpdateService}. * Code should be at its minimum. No logging or DB access here. */ @Override public void onReceive(Context context, Intent intent) { ExceptionHandler handler = new ExceptionHandler(context); WakeLock wl = null; try { try { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TimerifficReceiver"); wl.acquire(); } catch (Exception e) { // Hmm wake lock failed... not sure why. Continue anyway. Log.w(TAG, "WakeLock.acquire failed"); } if (DEBUG) Log.d(TAG, "UpdateService requested"); Core core = TimerifficApp.getInstance(context).getCore(); core.getUpdateService().startFromReceiver(context, intent, wl); wl = null; } finally { if (wl != null) { try { wl.release(); } catch (Exception e) { // ignore } } handler.detach(); } } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/app/UpdateReceiver.java
Java
gpl3
3,191
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.app; import android.app.Application; import android.content.Context; import com.rdrrlabs.example.timer1app.core.app.AppId; import com.rdrrlabs.example.timer1app.core.app.Core; import com.rdrrlabs.example.timer1app.core.prefs.PrefsStorage; public class TimerifficApp extends Application { @SuppressWarnings("unused") private static final String TAG = TimerifficApp.class.getSimpleName(); private boolean mFirstStart = true; private Runnable mDataListener; private final Core mCore; private final PrefsStorage mPrefsStorage = new PrefsStorage("prefs"); /** Base constructor with a default core. */ public TimerifficApp() { mCore = new Core(); } /** Derived constructor, to override the core. */ public TimerifficApp(Core core) { mCore = core; } @Override public void onCreate() { super.onCreate(); mPrefsStorage.beginReadAsync(getApplicationContext()); } /** * Returns the {@link TimerifficApp} instance using the * {@link Context#getApplicationContext()}. * * Returns null if context doesn't correctly, which is not supposed * to happen in normal behavior. */ public static TimerifficApp getInstance(Context context) { Context app = context.getApplicationContext(); if (app instanceof TimerifficApp) { return (TimerifficApp) app; } return null; } //--------------------- public boolean isFirstStart() { return mFirstStart; } public void setFirstStart(boolean firstStart) { mFirstStart = firstStart; } //--------------------- public void setDataListener(Runnable listener) { mDataListener = listener; } public void invokeDataListener() { if (mDataListener != null) mDataListener.run(); } public PrefsStorage getPrefsStorage() { return mPrefsStorage; } public String getIssueId() { return AppId.getIssueId(this, mPrefsStorage); } public Core getCore() { return mCore; } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/app/TimerifficApp.java
Java
gpl3
2,859
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.error; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.Thread.UncaughtExceptionHandler; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.util.Log; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; import com.rdrrlabs.example.timer1app.ui.ErrorReporterUI; public class ExceptionHandler { /** Exception Notification ID. 'ExcH' as an int. */ private static final int EXCEPTION_NOTIF_ID = 'E' << 24 + 'x' << 16 + 'c' << 8 + 'H'; public static final String TAG = ExceptionHandler.class.getSimpleName(); public static final String SEP_START = "{[ "; public static final String SEP_END = "} /*end*/ \n"; private Context mAppContext; private Handler mHandler; private static DateFormat sDateFormat; static { sDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z"); } // ----- public static int getNumExceptionsInLog(Context context) { try { PrefsValues pv = new PrefsValues(context); String curr = pv.getLastExceptions(); if (curr == null) { return 0; } int count = -1; int pos = -1; do { count++; pos = curr.indexOf(SEP_END, pos + 1); } while (pos >= 0); return count; } catch (Exception e) { Log.d(TAG, "getNumExceptionsInLog failed", e); } return 0; } // ----- public ExceptionHandler(Context context) { // Context is never supposed to be null if (context == null) return; // We only set our handler if there's no current handler or it is // not our -- we don't override our own handler. UncaughtExceptionHandler h = Thread.currentThread().getUncaughtExceptionHandler(); if (h == null || !(h instanceof Handler)) { mAppContext = context.getApplicationContext(); mHandler = new Handler(h); Thread.currentThread().setUncaughtExceptionHandler(mHandler); } } public void detach() { if (mAppContext != null) { Thread.currentThread().setUncaughtExceptionHandler(mHandler.getOldHanlder()); mHandler = null; mAppContext = null; } } private class Handler implements Thread.UncaughtExceptionHandler { private final UncaughtExceptionHandler mOldHanlder; public Handler(UncaughtExceptionHandler oldHanlder) { mOldHanlder = oldHanlder; } public UncaughtExceptionHandler getOldHanlder() { return mOldHanlder; } public void uncaughtException(Thread t, Throwable e) { try { PrefsValues pv = new PrefsValues(mAppContext); addToLog(pv, e); createNotification(); } catch (Throwable t2) { // ignore, or we'll get into an infinite loop } try { // chain the calls to any previous handler that is not one of ours UncaughtExceptionHandler h = mOldHanlder; while (h != null && h instanceof Handler) { h = ((Handler) h).getOldHanlder(); } if (h != null) { mOldHanlder.uncaughtException(t, e); } else { // If we couldn't find any old handler, log the error // to the console if this is an emulator if ("sdk".equals(Build.MODEL)) { Log.e(TAG, "Exception caught in Timeriffic", e); } } } catch (Throwable t3) { // ignore } } }; public synchronized static void addToLog(PrefsValues pv, Throwable e) { // get a trace of the exception StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.flush(); // store the exception String currEx = pv.getLastExceptions(); if (currEx == null) currEx = ""; // trim the string if it gets too big. if (currEx.length() > 4096) { int pos = currEx.indexOf(SEP_END); int p = pos + SEP_END.length(); if (pos > 0) { if (p < currEx.length()) { currEx = currEx.substring(p); } else { currEx = ""; } } } String d = sDateFormat.format(new Date(System.currentTimeMillis())); currEx += SEP_START + d + " ]\n"; currEx += sw.toString() + "\n"; currEx += SEP_END; pv.setLastExceptions(currEx); } private void createNotification() { NotificationManager ns = (NotificationManager) mAppContext.getSystemService(Context.NOTIFICATION_SERVICE); if (ns == null) return; Notification notif = new Notification( R.drawable.app_icon, // icon "Timeriffic Crashed!", // tickerText System.currentTimeMillis() // when ); notif.flags |= Notification.FLAG_AUTO_CANCEL; notif.defaults = Notification.DEFAULT_ALL; Intent i = new Intent(mAppContext, ErrorReporterUI.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(mAppContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); notif.setLatestEventInfo(mAppContext, "Oh no! Timeriffic Crashed!", // contentTitle "Please click here to report this error.", // contentText pi // contentIntent ); ns.notify(EXCEPTION_NOTIF_ID, notif); } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/core/error/ExceptionHandler.java
Java
gpl3
6,971
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesUiImpl.ColIndexes; /** * The holder for a timed action row. */ public class TimedActionHolder extends BaseHolder { private static boolean DEBUG = false; public static final String TAG = TimedActionHolder.class.getSimpleName(); public TimedActionHolder(ProfilesUiImpl activity, View view) { super(activity, view); } @Override public void setUiData() { ColIndexes colIndexes = mActivity.getColIndexes(); Cursor cursor = mActivity.getCursor(); super.setUiData(cursor.getString(colIndexes.mDescColIndex), getDotColor(cursor.getInt(colIndexes.mEnableColIndex))); } private Drawable getDotColor(int actionMark) { switch (actionMark) { case Columns.ACTION_MARK_PREV: return mActivity.getGreenDot(); case Columns.ACTION_MARK_NEXT: return mActivity.getPurpleDot(); default: return mActivity.getGrayDot(); } } @Override public void onCreateContextMenu(ContextMenu menu) { menu.setHeaderTitle(R.string.timedactioncontextmenu_title); menu.add(0, R.string.menu_insert_action, 0, R.string.menu_insert_action); menu.add(0, R.string.menu_delete, 0, R.string.menu_delete); menu.add(0, R.string.menu_edit, 0, R.string.menu_edit); } @Override public void onItemSelected() { // trigger edit if (DEBUG) Log.d(TAG, "action - edit"); editAction(mActivity.getCursor()); } @Override public void onContextMenuSelected(MenuItem item) { switch (item.getItemId()) { case R.string.menu_insert_action: if (DEBUG) Log.d(TAG, "action - insert_action"); insertNewAction(mActivity.getCursor()); break; case R.string.menu_delete: if (DEBUG) Log.d(TAG, "action - delete"); deleteTimedAction(mActivity.getCursor()); break; case R.string.menu_edit: if (DEBUG) Log.d(TAG, "action - edit"); editAction(mActivity.getCursor()); break; default: break; } } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/core/profiles1/TimedActionHolder.java
Java
gpl3
3,289
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import java.util.Calendar; import java.util.GregorianCalendar; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.TimedActionUtils; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesUiImpl.ColIndexes; import com.rdrrlabs.example.timer1app.ui.EditActionUI; import com.rdrrlabs.example.timer1app.ui.EditProfileUI; /** * A base holder class that keeps tracks of the current cursor * and the common widgets of the two derived holders. */ public abstract class BaseHolder { public static final String TAG = BaseHolder.class.getSimpleName(); /** * The text view that holds the title or description as well * as the "check box". */ private final TextView mDescription; protected final ProfilesUiImpl mActivity; public BaseHolder(ProfilesUiImpl activity, View view) { mActivity = activity; mDescription = view != null ? (TextView) view.findViewById(R.id.description) : null; } protected void setUiData(String description, Drawable state) { if (description != null) mDescription.setText(description); if (state != null) mDescription.setCompoundDrawablesWithIntrinsicBounds( state /*left*/, null /*top*/, null /*right*/, null /*bottom*/); } public abstract void setUiData(); public abstract void onItemSelected(); public abstract void onCreateContextMenu(ContextMenu menu); public abstract void onContextMenuSelected(MenuItem item); // --- profile actions --- private void startEditActivity(Class<?> activity, String extra_id, long extra_value) { Intent intent = new Intent(mActivity.getActivity(), activity); intent.putExtra(extra_id, extra_value); mActivity.getActivity().startActivityForResult(intent, ProfilesUiImpl.DATA_CHANGED); } protected void deleteProfile(Cursor cursor) { ColIndexes colIndexes = mActivity.getColIndexes(); final long row_id = cursor.getLong(colIndexes.mIdColIndex); String title = cursor.getString(colIndexes.mDescColIndex); mActivity.showTempDialog(row_id, title, ProfilesUiImpl.DIALOG_DELETE_PROFILE); } protected void insertNewProfile(Cursor beforeCursor) { long prof_index = 0; if (beforeCursor != null) { ColIndexes colIndexes = mActivity.getColIndexes(); prof_index = beforeCursor.getLong(colIndexes.mProfIdColIndex) >> Columns.PROFILE_SHIFT; } ProfilesDB profDb = mActivity.getProfilesDb(); prof_index = profDb.insertProfile(prof_index, mActivity.getActivity().getString(R.string.insertprofile_new_profile_title), true /*isEnabled*/); startEditActivity(EditProfileUI.class, EditProfileUI.EXTRA_PROFILE_ID, prof_index << Columns.PROFILE_SHIFT); } protected void editProfile(Cursor cursor) { ColIndexes colIndexes = mActivity.getColIndexes(); long prof_id = cursor.getLong(colIndexes.mProfIdColIndex); startEditActivity(EditProfileUI.class, EditProfileUI.EXTRA_PROFILE_ID, prof_id); } // --- timed actions ---- protected void deleteTimedAction(Cursor cursor) { ColIndexes colIndexes = mActivity.getColIndexes(); final long row_id = cursor.getLong(colIndexes.mIdColIndex); String description = cursor.getString(colIndexes.mDescColIndex); mActivity.showTempDialog(row_id, description, ProfilesUiImpl.DIALOG_DELETE_ACTION); } protected void insertNewAction(Cursor beforeCursor) { long prof_index = 0; long action_index = 0; if (beforeCursor != null) { ColIndexes colIndexes = mActivity.getColIndexes(); prof_index = beforeCursor.getLong(colIndexes.mProfIdColIndex); action_index = prof_index & Columns.ACTION_MASK; prof_index = prof_index >> Columns.PROFILE_SHIFT; } Calendar c = new GregorianCalendar(); c.setTimeInMillis(System.currentTimeMillis()); int hourMin = c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE); int day = TimedActionUtils.calendarDayToActionDay(c); ProfilesDB profDb = mActivity.getProfilesDb(); action_index = profDb.insertTimedAction( prof_index, action_index, hourMin, // hourMin day, // days "", // actions 0 // nextMs ); long action_id = (prof_index << Columns.PROFILE_SHIFT) + action_index; startEditActivity(EditActionUI.class, EditActionUI.EXTRA_ACTION_ID, action_id); } protected void editAction(Cursor cursor) { try { ColIndexes colIndexes = mActivity.getColIndexes(); long action_id = cursor.getLong(colIndexes.mProfIdColIndex); startEditActivity(EditActionUI.class, EditActionUI.EXTRA_ACTION_ID, action_id); } catch (Throwable t) { Log.e(TAG, "editAction", t); } } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/core/profiles1/BaseHolder.java
Java
gpl3
6,141
/* * Project: Timeriffic * Copyright (C) 2011 rdrr labs gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewTreeObserver; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.view.ViewTreeObserver.OnPreDrawListener; import android.widget.AdapterView; import android.widget.ListView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.app.TimerifficApp; import com.rdrrlabs.example.timer1app.app.UpdateReceiver; import com.rdrrlabs.example.timer1app.core.app.BackupWrapper; import com.rdrrlabs.example.timer1app.core.prefs.PrefsValues; import com.rdrrlabs.example.timer1app.core.settings.SettingFactory; import com.rdrrlabs.example.timer1app.core.utils.AgentWrapper; import com.rdrrlabs.example.timer1app.ui.EditProfileUI; import com.rdrrlabs.example.timer1app.ui.ErrorReporterUI; import com.rdrrlabs.example.timer1app.ui.GlobalStatus; import com.rdrrlabs.example.timer1app.ui.GlobalToggle; import com.rdrrlabs.example.timer1app.ui.IActivityDelegate; import com.rdrrlabs.example.timer1app.ui.IntroUI; import com.rdrrlabs.example.timer1app.ui.PrefsUI; public class ProfilesUiImpl implements IActivityDelegate<ProfilesUiImpl> { private static final boolean DEBUG = true; public static final String TAG = ProfilesUiImpl.class.getSimpleName(); public static final int DATA_CHANGED = 42; static final int SETTINGS_UPDATED = 43; static final int CHECK_SERVICES = 44; static final int DIALOG_RESET_CHOICES = 0; public static final int DIALOG_DELETE_ACTION = 1; public static final int DIALOG_DELETE_PROFILE = 2; static final int DIALOG_CHECK_SERVICES = 3; private final Activity mActivity; private ListView mProfilesList; private ProfileCursorAdapter mAdapter; private LayoutInflater mLayoutInflater; private ProfilesDB mProfilesDb; private AgentWrapper mAgentWrapper; private PrefsValues mPrefsValues; private Drawable mGrayDot; private Drawable mGreenDot; private Drawable mPurpleDot; private Drawable mCheckOn; private Drawable mCheckOff; private GlobalToggle mGlobalToggle; private GlobalStatus mGlobalStatus; private long mTempDialogRowId; private String mTempDialogTitle; private Cursor mCursor; public static class ColIndexes { public int mIdColIndex; public int mTypeColIndex; public int mDescColIndex; public int mEnableColIndex; public int mProfIdColIndex; }; private ColIndexes mColIndexes = new ColIndexes(); private BackupWrapper mBackupWrapper; public ProfilesUiImpl(Activity profileActivity) { mActivity = profileActivity; } /** * Called when the activity is created. * <p/> * Initializes row indexes and buttons. * Profile list & db is initialized in {@link #onResume()}. */ public void onCreate(Bundle savedInstanceState) { Log.d(TAG, String.format("Started %s", getClass().getSimpleName())); mActivity.setContentView(R.layout.profiles_screen); mLayoutInflater = mActivity.getLayoutInflater(); mPrefsValues = new PrefsValues(mActivity); mGrayDot = mActivity.getResources().getDrawable(R.drawable.dot_gray); mGreenDot = mActivity.getResources().getDrawable(R.drawable.dot_green); mPurpleDot = mActivity.getResources().getDrawable(R.drawable.dot_purple); mCheckOn = mActivity.getResources().getDrawable(R.drawable.btn_check_on); mCheckOff = mActivity.getResources().getDrawable(R.drawable.btn_check_off); initButtons(); showIntroAtStartup(); mAgentWrapper = new AgentWrapper(); mAgentWrapper.start(mActivity); mAgentWrapper.event(AgentWrapper.Event.OpenProfileUI); } private void showIntroAtStartup() { final TimerifficApp tapp = TimerifficApp.getInstance(mActivity); if (tapp.isFirstStart() && mGlobalToggle != null) { final Runnable action = new Runnable() { public void run() { showIntro(false, true); tapp.setFirstStart(false); } }; final ViewTreeObserver obs = mGlobalToggle.getViewTreeObserver(); obs.addOnPreDrawListener(new OnPreDrawListener() { public boolean onPreDraw() { mGlobalToggle.postDelayed(action, 200 /*delayMillis*/); ViewTreeObserver obs2 = mGlobalToggle.getViewTreeObserver(); obs2.removeOnPreDrawListener(this); return true; } }); } } private void showIntro(boolean force, boolean checkServices) { // force is set when this comes from Menu > About boolean showIntro = force; // if not forcing, does the user wants to see the intro? // true by default, unless disabled in the prefs if (!showIntro) { showIntro = !mPrefsValues.isIntroDismissed(); } // user doesn't want to see it... but we force it anyway if this is // a version upgrade int currentVersion = -1; try { currentVersion = mActivity.getPackageManager().getPackageInfo( mActivity.getPackageName(), 0).versionCode; // the version number is in format n.m.kk where n.m is the // actual version number, incremented for features and kk is // a sub-minor index of minor fixes. We clear these last digits // out and don't force to see the intro for these minor fixes. currentVersion = (currentVersion / 100) * 100; } catch (NameNotFoundException e) { // ignore. should not happen. } if (!showIntro && currentVersion > 0) { showIntro = currentVersion > mPrefsValues.getLastIntroVersion(); } if (showIntro) { // mark it as seen if (currentVersion > 0) { mPrefsValues.setLastIntroVersion(currentVersion); } Intent i = new Intent(mActivity, IntroUI.class); if (force) i.putExtra(IntroUI.EXTRA_NO_CONTROLS, true); mActivity.startActivityForResult(i, CHECK_SERVICES); return; } if (checkServices) { onCheckServices(); } } public Activity getActivity() { return mActivity; } public Cursor getCursor() { return mCursor; }; public ColIndexes getColIndexes() { return mColIndexes; } public ProfilesDB getProfilesDb() { return mProfilesDb; } public Drawable getGrayDot() { return mGrayDot; } public Drawable getGreenDot() { return mGreenDot; } public Drawable getPurpleDot() { return mPurpleDot; } public Drawable getCheckOff() { return mCheckOff; } public Drawable getCheckOn() { return mCheckOn; } /** * Initializes the profile list widget with a cursor adapter. * Creates a db connection. */ private void initProfileList() { Log.d(TAG, "init profile list"); if (mProfilesList == null) { mProfilesList = (ListView) mActivity.findViewById(R.id.profilesList); mProfilesList.setEmptyView(mActivity.findViewById(R.id.empty)); mProfilesList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View clickedView, int position, long id) { if (DEBUG) Log.d(TAG, String.format("onItemClick: pos %d, id %d", position, id)); BaseHolder h = null; h = getHolder(null, clickedView); if (h != null) h.onItemSelected(); } }); mProfilesList.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View listview, ContextMenuInfo menuInfo) { if (DEBUG) Log.d(TAG, "onCreateContextMenu"); BaseHolder h = null; h = getHolder(menuInfo, null); if (h != null) h.onCreateContextMenu(menu); } }); } if (mProfilesDb == null) { mProfilesDb = new ProfilesDB(); mProfilesDb.onCreate(mActivity); String next = mPrefsValues.getStatusNextTS(); if (next == null) { // schedule a profile check to initialize the last/next status requestSettingsCheck(UpdateReceiver.TOAST_NONE); } } if (mAdapter == null) { if (mCursor != null) { mCursor.close(); mCursor = null; } mCursor = mProfilesDb.query( -1, //id new String[] { Columns._ID, Columns.TYPE, Columns.DESCRIPTION, Columns.IS_ENABLED, Columns.PROFILE_ID, // enable these only if they are actually used here //Columns.HOUR_MIN, //Columns.DAYS, //Columns.ACTIONS, //Columns.NEXT_MS } , //projection null, //selection null, //selectionArgs null //sortOrder ); mColIndexes.mIdColIndex = mCursor.getColumnIndexOrThrow(Columns._ID); mColIndexes.mTypeColIndex = mCursor.getColumnIndexOrThrow(Columns.TYPE); mColIndexes.mDescColIndex = mCursor.getColumnIndexOrThrow(Columns.DESCRIPTION); mColIndexes.mEnableColIndex = mCursor.getColumnIndexOrThrow(Columns.IS_ENABLED); mColIndexes.mProfIdColIndex = mCursor.getColumnIndexOrThrow(Columns.PROFILE_ID); mAdapter = new ProfileCursorAdapter(this, mColIndexes, mLayoutInflater); mProfilesList.setAdapter(mAdapter); Log.d(TAG, String.format("adapter count: %d", mProfilesList.getCount())); } } /** * Called when activity is resumed, or just after creation. * <p/> * Initializes the profile list & db. */ public void onResume() { initOnResume(); } private void initOnResume() { initProfileList(); setDataListener(); } /** * Called when the activity is getting paused. It might get destroyed * at any point. * <p/> * Reclaim all views (so that they tag's cursor can be cleared). * Destroys the db connection. */ public void onPause() { removeDataListener(); } public void onStop() { mAgentWrapper.stop(mActivity); } private void setDataListener() { TimerifficApp app = TimerifficApp.getInstance(mActivity); if (app != null) { app.setDataListener(new Runnable() { public void run() { onDataChanged(true /*backup*/); } }); // No backup on the first init onDataChanged(false /*backup*/); } } private void removeDataListener() { TimerifficApp app = TimerifficApp.getInstance(mActivity); if (app != null) { app.setDataListener(null); } } public void onRestoreInstanceState(Bundle savedInstanceState) { mTempDialogRowId = savedInstanceState.getLong("dlg_rowid"); mTempDialogTitle = savedInstanceState.getString("dlg_title"); } public void onSaveInstanceState(Bundle outState) { outState.putLong("dlg_rowid", mTempDialogRowId); outState.putString("dlg_title", mTempDialogTitle); } public void onDestroy() { if (mAdapter != null) { mAdapter.changeCursor(null); mAdapter = null; } if (mCursor != null) { mCursor.close(); mCursor = null; } if (mProfilesDb != null) { mProfilesDb.onDestroy(); mProfilesDb = null; } if (mProfilesList != null) { ArrayList<View> views = new ArrayList<View>(); mProfilesList.reclaimViews(views); mProfilesList.setAdapter(null); mProfilesList = null; } } public void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case DATA_CHANGED: onDataChanged(true /*backup*/); requestSettingsCheck(UpdateReceiver.TOAST_IF_CHANGED); break; case SETTINGS_UPDATED: updateGlobalState(); requestSettingsCheck(UpdateReceiver.TOAST_IF_CHANGED); break; case CHECK_SERVICES: onCheckServices(); } } private void onDataChanged(boolean backup) { if (mCursor != null) mCursor.requery(); mAdapter = null; initProfileList(); updateGlobalState(); if (backup) { if (mBackupWrapper == null) mBackupWrapper = new BackupWrapper(mActivity); mBackupWrapper.dataChanged(); } } public Dialog onCreateDialog(int id) { // In case of configuration change (e.g. screen rotation), // the activity is restored but onResume hasn't been called yet // so we do it now. initOnResume(); switch(id) { case DIALOG_RESET_CHOICES: return createDialogResetChoices(); case DIALOG_DELETE_PROFILE: return createDeleteProfileDialog(); case DIALOG_DELETE_ACTION: return createDialogDeleteTimedAction(); case DIALOG_CHECK_SERVICES: return createDialogCheckServices(); default: return null; } } private void onCheckServices() { String msg = getCheckServicesMessage(); if (DEBUG) Log.d(TAG, "Check Services: " + msg == null ? "null" : msg); if (msg.length() > 0 && mPrefsValues.getCheckService()) { mActivity.showDialog(DIALOG_CHECK_SERVICES); } } private String getCheckServicesMessage() { SettingFactory factory = SettingFactory.getInstance(); StringBuilder sb = new StringBuilder(); if (!factory.getSetting(Columns.ACTION_RING_VOLUME).isSupported(mActivity)) { sb.append("\n- ").append(mActivity.getString(R.string.checkservices_miss_audio_service)); } if (!factory.getSetting(Columns.ACTION_WIFI).isSupported(mActivity)) { sb.append("\n- ").append(mActivity.getString(R.string.checkservices_miss_wifi_service)); } if (!factory.getSetting(Columns.ACTION_AIRPLANE).isSupported(mActivity)) { sb.append("\n- ").append(mActivity.getString(R.string.checkservices_miss_airplane)); } if (!factory.getSetting(Columns.ACTION_BRIGHTNESS).isSupported(mActivity)) { sb.append("\n- ").append(mActivity.getString(R.string.checkservices_miss_brightness)); } // Bluetooth and APNDroid are not essential settings. We can't just bug the // user at start if they are missing (which is also highly probably, especially for // APNDroid). So here is not the right place to check for them. // // if (!factory.getSetting(Columns.ACTION_BLUETOOTH).isSupported(this)) { // sb.append("\n- ").append(getString(R.string.checkservices_miss_bluetooh)); // } // if (!factory.getSetting(Columns.ACTION_APN_DROID).isSupported(this)) { // sb.append("\n- ").append(getString(R.string.checkservices_miss_apndroid)); // } if (sb.length() > 0) { sb.insert(0, mActivity.getString(R.string.checkservices_warning)); } return sb.toString(); } private Dialog createDialogCheckServices() { Builder b = new AlertDialog.Builder(mActivity); b.setTitle(R.string.checkservices_dlg_title); b.setMessage(getCheckServicesMessage()); b.setPositiveButton(R.string.checkservices_ok_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mActivity.removeDialog(DIALOG_CHECK_SERVICES); } }); b.setNegativeButton(R.string.checkservices_skip_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mPrefsValues.setCheckService(false); mActivity.removeDialog(DIALOG_CHECK_SERVICES); } }); b.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { mActivity.removeDialog(DIALOG_CHECK_SERVICES); } }); return b.create(); } public boolean onContextItemSelected(MenuItem item) { ContextMenuInfo info = item.getMenuInfo(); BaseHolder h = getHolder(info, null); if (h != null) { h.onContextMenuSelected(item); return true; } return false; } private BaseHolder getHolder(ContextMenuInfo menuInfo, View selectedView) { if (selectedView == null && menuInfo instanceof AdapterContextMenuInfo) { selectedView = ((AdapterContextMenuInfo) menuInfo).targetView; } Object tag = selectedView.getTag(); if (tag instanceof BaseHolder) { return (BaseHolder) tag; } Log.d(TAG, "Holder missing"); return null; } /** * Initializes the list-independent buttons: global toggle, check now. */ private void initButtons() { mGlobalToggle = (GlobalToggle) mActivity.findViewById(R.id.global_toggle); mGlobalStatus = (GlobalStatus) mActivity.findViewById(R.id.global_status); updateGlobalState(); mGlobalToggle.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mPrefsValues.setServiceEnabled(!mPrefsValues.isServiceEnabled()); updateGlobalState(); requestSettingsCheck(UpdateReceiver.TOAST_ALWAYS); } }); mGlobalStatus.setWindowVisibilityChangedCallback(new Runnable() { public void run() { updateGlobalState(); } }); } private void updateGlobalState() { boolean isEnabled = mPrefsValues.isServiceEnabled(); mGlobalToggle.setActive(isEnabled); mGlobalStatus.setTextLastTs(mPrefsValues.getStatusLastTS()); if (isEnabled) { mGlobalStatus.setTextNextTs(mPrefsValues.getStatusNextTS()); mGlobalStatus.setTextNextDesc(mPrefsValues.getStatusNextAction()); } else { mGlobalStatus.setTextNextTs(mActivity.getString(R.string.globalstatus_disabled)); mGlobalStatus.setTextNextDesc(mActivity.getString(R.string.help_to_enable)); } mGlobalStatus.invalidate(); } public void onCreateOptionsMenu(Menu menu) { menu.add(0, R.string.menu_append_profile, 0, R.string.menu_append_profile).setIcon(R.drawable.ic_menu_add); menu.add(0, R.string.menu_settings, 0, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences); menu.add(0, R.string.menu_about, 0, R.string.menu_about).setIcon(R.drawable.ic_menu_help); menu.add(0, R.string.menu_report_error, 0, R.string.menu_report_error).setIcon(R.drawable.ic_menu_report); menu.add(0, R.string.menu_check_now, 0, R.string.menu_check_now).setIcon(R.drawable.ic_menu_rotate); menu.add(0, R.string.menu_reset, 0, R.string.menu_reset).setIcon(R.drawable.ic_menu_revert); // TODO save to sd } public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.string.menu_settings: mAgentWrapper.event(AgentWrapper.Event.MenuSettings); showPrefs(); break; case R.string.menu_check_now: requestSettingsCheck(UpdateReceiver.TOAST_ALWAYS); break; case R.string.menu_about: mAgentWrapper.event(AgentWrapper.Event.MenuAbout); showIntro(true /*force*/, false /* checkService */); break; case R.string.menu_reset: mAgentWrapper.event(AgentWrapper.Event.MenuReset); showResetChoices(); break; // TODO save to sd case R.string.menu_append_profile: appendNewProfile(); break; case R.string.menu_report_error: showErrorReport(); break; default: return false; } return true; // handled } private void showPrefs() { mActivity.startActivityForResult(new Intent(mActivity, PrefsUI.class), SETTINGS_UPDATED); } private void showErrorReport() { mActivity.startActivity(new Intent(mActivity, ErrorReporterUI.class)); } /** * Requests a setting check. * * @param displayToast Must be one of {@link UpdateReceiver#TOAST_ALWAYS}, * {@link UpdateReceiver#TOAST_IF_CHANGED} or {@link UpdateReceiver#TOAST_NONE} */ private void requestSettingsCheck(int displayToast) { if (DEBUG) Log.d(TAG, "Request settings check"); Intent i = new Intent(UpdateReceiver.ACTION_UI_CHECK); i.putExtra(UpdateReceiver.EXTRA_TOAST_NEXT_EVENT, displayToast); mActivity.sendBroadcast(i); } protected void showResetChoices() { mActivity.showDialog(DIALOG_RESET_CHOICES); } // TODO save to sd private Dialog createDialogResetChoices() { Builder d = new AlertDialog.Builder(mActivity); d.setCancelable(true); d.setTitle(R.string.resetprofiles_msg_confirm_delete); d.setIcon(R.drawable.app_icon); d.setItems(mProfilesDb.getResetLabels(), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mProfilesDb.resetProfiles(which); mActivity.removeDialog(DIALOG_RESET_CHOICES); onDataChanged(true /*backup*/); requestSettingsCheck(UpdateReceiver.TOAST_IF_CHANGED); } }); d.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { mActivity.removeDialog(DIALOG_RESET_CHOICES); } }); d.setNegativeButton(R.string.resetprofiles_button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mActivity.removeDialog(DIALOG_RESET_CHOICES); } }); return d.create(); } //-------------- public void showTempDialog(long row_id, String title, int dlg_id) { mTempDialogRowId = row_id; mTempDialogTitle = title; mActivity.showDialog(dlg_id); } //-------------- private Dialog createDeleteProfileDialog() { final long row_id = mTempDialogRowId; final String title = mTempDialogTitle; Builder d = new AlertDialog.Builder(mActivity); d.setCancelable(true); d.setTitle(R.string.deleteprofile_title); d.setIcon(R.drawable.app_icon); d.setMessage(String.format( mActivity.getString(R.string.deleteprofile_msgbody), title)); d.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { mActivity.removeDialog(DIALOG_DELETE_PROFILE); } }); d.setNegativeButton(R.string.deleteprofile_button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mActivity.removeDialog(DIALOG_DELETE_PROFILE); } }); d.setPositiveButton(R.string.deleteprofile_button_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { int count = mProfilesDb.deleteProfile(row_id); if (count > 0) { mAdapter.notifyDataSetChanged(); onDataChanged(true /*backup*/); } mActivity.removeDialog(DIALOG_DELETE_PROFILE); } }); return d.create(); } private Dialog createDialogDeleteTimedAction() { final long row_id = mTempDialogRowId; final String description = mTempDialogTitle; Builder d = new AlertDialog.Builder(mActivity); d.setCancelable(true); d.setTitle(R.string.deleteaction_title); d.setIcon(R.drawable.app_icon); d.setMessage(mActivity.getString(R.string.deleteaction_msgbody, description)); d.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { mActivity.removeDialog(DIALOG_DELETE_ACTION); } }); d.setNegativeButton(R.string.deleteaction_button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mActivity.removeDialog(DIALOG_DELETE_ACTION); } }); d.setPositiveButton(R.string.deleteaction_button_delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { int count = mProfilesDb.deleteAction(row_id); if (count > 0) { mAdapter.notifyDataSetChanged(); onDataChanged(true /*backup*/); } mActivity.removeDialog(DIALOG_DELETE_ACTION); } }); return d.create(); } public void appendNewProfile() { long prof_index = mProfilesDb.insertProfile(0, mActivity.getString(R.string.insertprofile_new_profile_title), true /*isEnabled*/); Intent intent = new Intent(mActivity, EditProfileUI.class); intent.putExtra(EditProfileUI.EXTRA_PROFILE_ID, prof_index << Columns.PROFILE_SHIFT); mActivity.startActivityForResult(intent, DATA_CHANGED); } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/core/profiles1/ProfilesUiImpl.java
Java
gpl3
28,210
/* * Project: Timeriffic * Copyright (C) 2009 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.profiles1.ProfilesUiImpl.ColIndexes; /** * A custom {@link CursorAdapter} that can provide the two views we * need: the profile header and the timed action entry. * <p/> * For each new view, the tag is set to either {@link ProfileHeaderHolder} * or {@link TimedActionHolder}, a subclass of {@link BaseHolder}. * <p/> * When a view is reused, it's tag is reused with a new cursor by using * {@link BaseHolder#setUiData}. This also updates the view * with the data from the cursor.. */ public class ProfileCursorAdapter extends CursorAdapter { /** View type is a profile header. */ private final static int TYPE_PROFILE = 0; /** View type is a timed action item. */ private final static int TYPE_TIMED_ACTION = 1; private final LayoutInflater mLayoutInflater; private final ColIndexes mColIndexes; private final ProfilesUiImpl mActivity; /** * Creates a new {@link ProfileCursorAdapter} for that cursor * and context. */ public ProfileCursorAdapter(ProfilesUiImpl activity, ColIndexes colIndexes, LayoutInflater layoutInflater) { super(activity.getActivity(), activity.getCursor()); mActivity = activity; mColIndexes = colIndexes; mLayoutInflater = layoutInflater; } /** * All items are always enabled in this view. */ @Override public boolean areAllItemsEnabled() { return true; } /** * All items are always enabled in this view. */ @Override public boolean isEnabled(int position) { return true; } /** * This adapter can serve 2 view types. */ @Override public int getViewTypeCount() { return 2; } /** * View types served are either {@link #TYPE_PROFILE} or * {@link #TYPE_TIMED_ACTION}. This is based on the value of * {@link Columns#TYPE} in the cursor. */ @Override public int getItemViewType(int position) { Cursor c = (Cursor) getItem(position); int type = c.getInt(mColIndexes.mTypeColIndex); if (type == Columns.TYPE_IS_PROFILE) return TYPE_PROFILE; if (type == Columns.TYPE_IS_TIMED_ACTION) return TYPE_TIMED_ACTION; return IGNORE_ITEM_VIEW_TYPE; } // --- /** * Depending on the value of {@link Columns#TYPE} in the cursor, * this inflates either a profile_header or a timed_action resource. * <p/> * It then associates the tag with a new {@link ProfileHeaderHolder} * or {@link TimedActionHolder} and initializes the holder using * {@link BaseHolder#setUiData}. * */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View v = null; BaseHolder h = null; int type = cursor.getInt(mColIndexes.mTypeColIndex); if (type == Columns.TYPE_IS_PROFILE) { v = mLayoutInflater.inflate(R.layout.profile_header, null); h = new ProfileHeaderHolder(mActivity, v); } else if (type == Columns.TYPE_IS_TIMED_ACTION) { v = mLayoutInflater.inflate(R.layout.timed_action, null); h = new TimedActionHolder(mActivity, v); } if (v != null) { v.setTag(h); h.setUiData(); } return v; } /** * To recycle a view, we just re-associate its tag using * {@link BaseHolder#setUiData}. */ @Override public void bindView(View view, Context context, Cursor cursor) { int type = cursor.getInt(mColIndexes.mTypeColIndex); if (type == Columns.TYPE_IS_PROFILE || type == Columns.TYPE_IS_TIMED_ACTION) { BaseHolder h = (BaseHolder) view.getTag(); h.setUiData(); } } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/core/profiles1/ProfileCursorAdapter.java
Java
gpl3
4,878
/* * Project: Timeriffic * Copyright (C) 2008 ralfoide gmail com, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rdrrlabs.example.timer1app.core.profiles1; import java.io.File; import java.security.InvalidParameterException; import java.util.ArrayList; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteStatement; import android.util.Log; import android.widget.Toast; import com.rdrrlabs.example.timer1app.base.R; import com.rdrrlabs.example.timer1app.core.actions.TimedActionUtils; //----------------------------------------------- /* * Debug Tip; to view content of database, use: * $ cd /cygdrive/c/.../android-sdk_..._windows/tools * $ ./adb shell 'echo ".dump" | sqlite3 data/data/com.rdrrlabs.example.timer1app/databases/profiles.db' */ /** * Helper to access the profiles database. * <p/> * The interface is similar to a {@link ContentProvider}, which should make it * easy to use only later. * <p/> * To be depreciated */ public class ProfilesDB { private static final boolean DEBUG = false; public static final String TAG = ProfilesDB.class.getSimpleName(); private static final String PROFILES_TABLE = "profiles"; private static final String DB_NAME = "profiles.db"; private static final int DB_VERSION = 1 * 100 + 1; // major*100 + minor private SQLiteDatabase mDb; private DatabaseHelper mDbHelper; private Context mContext; // ---------------------------------- /** Call this after creating this object. */ public boolean onCreate(Context context) { mContext = context; mDbHelper = new DatabaseHelper(context, DB_NAME, DB_VERSION); for (int i = 0; i < 10; i++) { try { mDb = mDbHelper.getWritableDatabase(); break; } catch (SQLiteException e) { Log.e(TAG, "DBHelper.getWritableDatabase", e); try { Thread.sleep(100 /*ms*/); } catch (InterruptedException e1) { // ignore } } } boolean created = mDb != null; return created; } /** Call this when the database is no longer needed. */ public void onDestroy() { mContext = null; if (mDbHelper != null) { for (int i = 0; i < 10; i++) { try { mDbHelper.close(); break; } catch (SQLiteException e) { Log.e(TAG, "DBHelper.close", e); try { Thread.sleep(100 /*ms*/); } catch (InterruptedException e1) { // ignore } } } mDbHelper = null; } } public static File getDatabaseFile(Context context) { return context.getDatabasePath(DB_NAME); } // ---------------------------------- /** * @see SQLiteDatabase#beginTransaction() */ public void beginTransaction() { mDb.beginTransaction(); } /** * @see SQLiteDatabase#setTransactionSuccessful() */ public void setTransactionSuccessful() { mDb.setTransactionSuccessful(); } /** * @see SQLiteDatabase#endTransaction() */ public void endTransaction() { mDb.endTransaction(); } // ---------------------------------- public long getProfileIdForRowId(long row_id) { SQLiteStatement sql = null; try { sql = mDb.compileStatement( String.format("SELECT %s FROM %s WHERE %s=%d;", Columns.PROFILE_ID, PROFILES_TABLE, Columns._ID, row_id)); return sql.simpleQueryForLong(); } catch (SQLiteDoneException e) { // no profiles return 0; } finally { if (sql != null) sql.close(); } } /** * Returns the max profile index (not id!). * * If maxProfileIndex == 0, returns the absolute max profile index, * i.e. the very last one. * If maxProfileIndex > 0, returns the max profile index that is smaller * than the given index (so basically the profile just before the one * given). * Returns 0 if there is no such index. */ public long getMaxProfileIndex(long maxProfileIndex) { SQLiteStatement sql = null; try { String testMaxProfId = ""; if (maxProfileIndex > 0) { testMaxProfId = String.format("AND %s<%d", Columns.PROFILE_ID, maxProfileIndex << Columns.PROFILE_SHIFT); } // e.g. SELECT MAX(prof_id) FROM profiles WHERE type=1 [ AND prof_id < 65536 ] sql = mDb.compileStatement( String.format("SELECT MAX(%s) FROM %s WHERE %s=%d %s;", Columns.PROFILE_ID, PROFILES_TABLE, Columns.TYPE, Columns.TYPE_IS_PROFILE, testMaxProfId)); return sql.simpleQueryForLong() >> Columns.PROFILE_SHIFT; } catch (SQLiteDoneException e) { // no profiles return 0; } finally { if (sql != null) sql.close(); } } /** * Returns the min action index (not id!) that is greater than the * requested minActionIndex. * <p/> * So for a given index (including 0), returns the next one used. * If there's no such index (i.e. not one used after the given index) * returns -1. */ public long getMinActionIndex(long profileIndex, long minActionIndex) { SQLiteStatement sql = null; try { long pid = (profileIndex << Columns.PROFILE_SHIFT) + minActionIndex; long maxPid = (profileIndex + 1) << Columns.PROFILE_SHIFT; // e.g. SELECT MIN(prof_id) FROM profiles WHERE type=2 AND prof_id > 32768+256 AND prof_id < 65536 sql = mDb.compileStatement( String.format("SELECT MIN(%s) FROM %s WHERE %s=%d AND %s>%d AND %s<%d;", Columns.PROFILE_ID, PROFILES_TABLE, Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, pid, Columns.PROFILE_ID, maxPid)); long result = sql.simpleQueryForLong(); if (result > pid && result < maxPid) return result & Columns.ACTION_MASK; } catch (SQLiteDoneException e) { // no actions } finally { if (sql != null) sql.close(); } return -1; } /** * Returns the max action index (not id!) for this profile. * Returns -1 if there are not actions. */ public long getMaxActionIndex(long profileIndex) { SQLiteStatement sql = null; try { long pid = (profileIndex << Columns.PROFILE_SHIFT); long maxPid = (profileIndex + 1) << Columns.PROFILE_SHIFT; // e.g. SELECT MAX(prof_id) FROM profiles WHERE type=2 AND prof_id > 32768 AND prof_id < 65536 sql = mDb.compileStatement( String.format("SELECT MAX(%s) FROM %s WHERE %s=%d AND %s>%d AND %s<%d;", Columns.PROFILE_ID, PROFILES_TABLE, Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, pid, Columns.PROFILE_ID, maxPid)); long result = sql.simpleQueryForLong(); if (result > pid && result < maxPid) return result & Columns.ACTION_MASK; } catch (SQLiteDoneException e) { // no actions } finally { if (sql != null) sql.close(); } return -1; } // ---------------------------------- /** * Inserts a new profile before the given profile index. * If beforeProfileIndex is <= 0, insert at the end. * * @return the profile index (not the row id) */ public long insertProfile(long beforeProfileIndex, String title, boolean isEnabled) { beginTransaction(); try { long index = getMaxProfileIndex(beforeProfileIndex); if (beforeProfileIndex <= 0) { long max = Long.MAX_VALUE >> Columns.PROFILE_SHIFT; if (index >= max - 1) { // TODO repack throw new UnsupportedOperationException("Profile index at maximum."); } else if (index < max - Columns.PROFILE_GAP) { index += Columns.PROFILE_GAP; } else { index += (max - index) / 2; } } else { if (index == beforeProfileIndex - 1) { // TODO repack throw new UnsupportedOperationException("No space left to insert profile before profile."); } else { index = (index + beforeProfileIndex) / 2; // get middle offset } } long id = index << Columns.PROFILE_SHIFT; ContentValues values = new ContentValues(2); values.put(Columns.PROFILE_ID, id); values.put(Columns.TYPE, Columns.TYPE_IS_PROFILE); values.put(Columns.DESCRIPTION, title); values.put(Columns.IS_ENABLED, isEnabled); id = mDb.insert(PROFILES_TABLE, Columns.TYPE, values); if (DEBUG) Log.d(TAG, String.format("Insert profile: %d => row %d", index, id)); if (id < 0) throw new SQLException("insert profile row failed"); setTransactionSuccessful(); return index; } finally { endTransaction(); } } /** * Inserts a new action for the given profile index. * If afterActionIndex is == 0, inserts at the beginning of these actions. * * NOTE: currently ignore afterActionIndex and always add at the end. * * @return the action index (not the row id) */ public long insertTimedAction(long profileIndex, long afterActionIndex, int hourMin, int days, String actions, long nextMs) { beginTransaction(); try { long pid = profileIndex << Columns.PROFILE_SHIFT; long maxIndex = getMaxActionIndex(profileIndex); if (maxIndex >= Columns.ACTION_MASK) { // Last index is used. Try to repack the action list. maxIndex = repackTimeActions(profileIndex); if (maxIndex == Columns.ACTION_MASK) { // definitely full... too bad. Toast.makeText(mContext, "No space left to insert action. Please delete some first.", Toast.LENGTH_LONG).show(); return -1; } } if (maxIndex < 0) { maxIndex = 0; } long index = maxIndex + 1; pid += index; String description = TimedActionUtils.computeDescription( mContext, hourMin, days, actions); ContentValues values = new ContentValues(2); values.put(Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION); values.put(Columns.PROFILE_ID, pid); values.put(Columns.DESCRIPTION, description); values.put(Columns.IS_ENABLED, 0); values.put(Columns.HOUR_MIN, hourMin); values.put(Columns.DAYS, days); values.put(Columns.ACTIONS, actions); values.put(Columns.NEXT_MS, nextMs); long id = mDb.insert(PROFILES_TABLE, Columns.TYPE, values); if (DEBUG) Log.d(TAG, String.format("Insert profile %d, action: %d => row %d", profileIndex, index, id)); if (id < 0) throw new SQLException("insert action row failed"); setTransactionSuccessful(); return index; } finally { endTransaction(); } } /** * Called by insertTimedAction within an existing transaction. * * Returns the new highest action index (not id) used. * Returns 0 if there were no actions. */ private long repackTimeActions(long profileIndex) { long pid = (profileIndex << Columns.PROFILE_SHIFT); long maxPid = (profileIndex + 1) << Columns.PROFILE_SHIFT; // Generates query with WHERE type=2 AND prof_id > 32768 AND prof_id < 65536 String where = String.format("%s=%d AND (%s>%d) AND (%s<%d)", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, pid, Columns.PROFILE_ID, maxPid); Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table new String[] { Columns.PROFILE_ID } , // columns where, // selection null, // selectionArgs null, // groupBy null, // having Columns.PROFILE_ID // orderBy ); int numActions = c.getCount(); if (DEBUG) Log.d(TAG, String.format("Repacking %d action", numActions)); if (numActions == 0 || numActions == Columns.ACTION_MASK) { // we know the table is empty or full, no need to repack. return numActions; } int colProfId = c.getColumnIndexOrThrow(Columns.PROFILE_ID); if (c.moveToFirst()) { int i = 1; do { long profId = c.getLong(colProfId); long newId = pid + (i++); if (profId != newId) { // generates update with WHERE type=2 AND prof_id=id where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, profId); ContentValues values = new ContentValues(1); values.put(Columns.PROFILE_ID, newId); mDb.update( PROFILES_TABLE, // table values, // values where, // whereClause null // whereArgs ); } } while (c.moveToNext()); } // new highest index is numActions return numActions; } finally { if (c != null) c.close(); } } // ---------------------------------- /** id is used if >= 0 */ public Cursor query(long id, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(PROFILES_TABLE); if (id >= 0) { qb.appendWhere(String.format("%s=%d", Columns._ID, id)); } if (sortOrder == null || sortOrder.length() == 0) sortOrder = Columns.DEFAULT_SORT_ORDER; Cursor c = qb.query(mDb, projection, selection, selectionArgs, null, // groupBy null, // having, sortOrder); return c; } // ---------------------------------- /** * @param name Profile name to update, if not null. * @param isEnabled Profile is enable flag to update. * @return Number of rows affected. 1 on success, 0 on failure. */ public int updateProfile(long prof_id, String name, boolean isEnabled) { String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_PROFILE, Columns.PROFILE_ID, prof_id); ContentValues cv = new ContentValues(); if (name != null) cv.put(Columns.DESCRIPTION, name); cv.put(Columns.IS_ENABLED, isEnabled); beginTransaction(); try { int count = mDb.update(PROFILES_TABLE, cv, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } /** * @param isEnabled Timed action is enable flag to update. * @return Number of rows affected. 1 on success, 0 on failure. */ public int updateTimedAction(long action_id, boolean isEnabled) { String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, action_id); ContentValues cv = new ContentValues(); cv.put(Columns.IS_ENABLED, isEnabled); beginTransaction(); try { int count = mDb.update(PROFILES_TABLE, cv, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } /** * @return Number of rows affected. 1 on success, 0 on failure. */ public int updateTimedAction(long action_id, int hourMin, int days, String actions, String description) { String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.PROFILE_ID, action_id); ContentValues cv = new ContentValues(); cv.put(Columns.HOUR_MIN, hourMin); cv.put(Columns.DAYS, days); cv.put(Columns.ACTIONS, actions); if (description != null) cv.put(Columns.DESCRIPTION, description); beginTransaction(); try { int count = mDb.update(PROFILES_TABLE, cv, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } // ---------------------------------- /** * @param row_id The SQL row id, NOT the prof_id * @return The number of deleted rows, >= 1 on success, 0 on failure. */ public int deleteProfile(long row_id) { beginTransaction(); try { long pid = getProfileIdForRowId(row_id); if (pid == 0) throw new InvalidParameterException("No profile id for this row id."); pid = pid & (~Columns.ACTION_MASK); // DELETE FROM profiles WHERE prof_id >= 65536 AND prof_id < 65536+65535 String where = String.format("%s>=%d AND %s<%d", Columns.PROFILE_ID, pid, Columns.PROFILE_ID, pid + Columns.ACTION_MASK); int count = mDb.delete(PROFILES_TABLE, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } /** * @param row_id The SQL row id, NOT the prof_id * @return The number of deleted rows, 1 on success, 0 on failure. */ public int deleteAction(long row_id) { beginTransaction(); try { // DELETE FROM profiles WHERE TYPE=2 AND _id=65537 String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns._ID, row_id); int count = mDb.delete(PROFILES_TABLE, where, null); setTransactionSuccessful(); return count; } finally { endTransaction(); } } // ---------------------------------- /** Convenience helper to open/create/update the database */ private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context, String db_name, int version) { super(context, db_name, null /* cursor factory */, version); } @Override public void onCreate(SQLiteDatabase db) { SQLiteDatabase old_mDb = mDb; mDb = db; onResetTables(); initDefaultProfiles(); mDb = old_mDb; } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, String.format("Upgrading database from version %1$d to %2$d.", oldVersion, newVersion)); db.execSQL("DROP TABLE IF EXISTS " + PROFILES_TABLE); onCreate(db); } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); // pass } } /** * Called by {@link DatabaseHelper} to reset the tables. */ private void onResetTables() { // hand over that chocolate and nobody gets hurt! mDb.execSQL(String.format("DROP TABLE IF EXISTS %s;", PROFILES_TABLE)); mDb.execSQL(String.format("CREATE TABLE %s " + "(%s INTEGER PRIMARY KEY AUTOINCREMENT, " + "%s INTEGER, " + "%s TEXT, " + "%s INTEGER, " + "%s INTEGER, " + "%s INTEGER, " + "%s INTEGER, " + "%s TEXT, " + "%s INTEGER);" , PROFILES_TABLE, Columns._ID, Columns.TYPE, Columns.DESCRIPTION, Columns.IS_ENABLED, Columns.PROFILE_ID, Columns.HOUR_MIN, Columns.DAYS, Columns.ACTIONS, Columns.NEXT_MS)); } /** * Called by {@link DatabaseHelper} when the database has just been * created to initialize it with initial data. It's safe to use * {@link ProfilesDB#insertProfile} or {@link ProfilesDB#insertTimedAction} * at that point. */ private void initDefaultProfiles() { long pindex = insertProfile(0, "Weekdaze", true /*isEnabled*/); long action = insertTimedAction(pindex, 0, 7*60+0, //hourMin Columns.MONDAY + Columns.TUESDAY + Columns.WEDNESDAY + Columns.THURSDAY, "RR,VV", //actions 0 //nextMs ); insertTimedAction(pindex, action, 20*60+0, //hourMin Columns.MONDAY + Columns.TUESDAY + Columns.WEDNESDAY + Columns.THURSDAY, "RM,VV", //actions 0 //nextMs ); pindex = insertProfile(0, "Party Time", true /*isEnabled*/); action = insertTimedAction(pindex, 0, 9*60+0, //hourMin Columns.FRIDAY + Columns.SATURDAY, "RR", //actions 0 //nextMs ); insertTimedAction(pindex, action, 22*60+0, //hourMin Columns.FRIDAY + Columns.SATURDAY, "RM,VV", //actions 0 //nextMs ); pindex = insertProfile(0, "Sleeping-In", true /*isEnabled*/); action = insertTimedAction(pindex, 0, 10*60+30, //hourMin Columns.SUNDAY, "RR", //actions 0 //nextMs ); insertTimedAction(pindex, action, 21*60+0, //hourMin Columns.SUNDAY, "RM,VV", //actions 0 //nextMs ); } /** * Some simple profiles for me */ private void initRalfProfiles() { long pindex = insertProfile(0, "Ralf Week", true /*isEnabled*/); long action = insertTimedAction(pindex, 0, 9*60+0, //hourMin Columns.MONDAY + Columns.TUESDAY + Columns.WEDNESDAY + Columns.THURSDAY + Columns.FRIDAY + Columns.SATURDAY + Columns.SUNDAY, "RR,VV,M75,Ba", //actions 0 //nextMs ); insertTimedAction(pindex, action, 21*60+0, //hourMin Columns.MONDAY + Columns.TUESDAY + Columns.WEDNESDAY + Columns.THURSDAY + Columns.FRIDAY + Columns.SATURDAY + Columns.SUNDAY, "RM,VN,M0,B0,U0", //actions 0 //nextMs ); } // -------------- /** * Labels of the reset profiles choices. * Default is index 0. */ public String[] getResetLabels() { return new String[] { "Default Profiles", "Ralf Profiles", "Empty Profile", }; } /** * Reset profiles according to choices. * * @param labelIndex An index from the {@link #getResetLabels()} array. */ public void resetProfiles(int labelIndex) { if (DEBUG) Log.d(TAG, "Reset profiles: " + Integer.toString(labelIndex)); switch(labelIndex) { case 0: // default profiles beginTransaction(); try { // empty tables onResetTables(); initDefaultProfiles(); setTransactionSuccessful(); } finally { endTransaction(); } break; case 1: // ralf profiles beginTransaction(); try { // empty tables onResetTables(); initRalfProfiles(); setTransactionSuccessful(); } finally { endTransaction(); } break; case 2: // empty profile beginTransaction(); try { // empty tables onResetTables(); setTransactionSuccessful(); } finally { endTransaction(); } break; } } // -------------- public void removeAllActionExecFlags() { // generates WHERE type=2 (aka action) AND enable=1 String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.IS_ENABLED, 1); ContentValues values = new ContentValues(1); values.put(Columns.IS_ENABLED, false); beginTransaction(); try { mDb.update( PROFILES_TABLE, // table values, // values where, // whereClause null // whereArgs ); setTransactionSuccessful(); } finally { endTransaction(); } } /** * Returns the list of all profiles, dumped in a structure that is * mostly for debugging. It is not designed to be read back for restoring * although we could change it to be later. */ public String[] getProfilesDump() { Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table null, // *ALL* columns null, // selection null, // selectionArgs null, // groupBy null, // having null // orderBy ); int colType = c.getColumnIndexOrThrow(Columns.TYPE); int colDesc = c.getColumnIndexOrThrow(Columns.DESCRIPTION); int colIsEnabled = c.getColumnIndexOrThrow(Columns.IS_ENABLED); int colProfId = c.getColumnIndexOrThrow(Columns.PROFILE_ID); int colHourMin = c.getColumnIndexOrThrow(Columns.HOUR_MIN); int colDays = c.getColumnIndexOrThrow(Columns.DAYS); int colActions = c.getColumnIndexOrThrow(Columns.ACTIONS); int colNextMs = c.getColumnIndexOrThrow(Columns.NEXT_MS); String[] summaries = new String[c.getCount()]; StringBuilder sb = new StringBuilder(); if (c.moveToFirst()) { int i = 0; do { String desc = c.getString(colDesc); String actions = c.getString(colActions); int enable = c.getInt(colIsEnabled); int type = c.getInt (colType); long profId = c.getLong(colProfId); int hourMin = c.getInt (colHourMin); int days = c.getInt (colDays); long nextMs = c.getLong(colNextMs); sb.setLength(0); if (type == Columns.TYPE_IS_TIMED_ACTION) { sb.append("- "); } // Format: { profile/action prof-index:action-index enable/active } sb.append(String.format("{ %1$s 0x%2$04x:%3$04x %4$s } ", type == Columns.TYPE_IS_PROFILE ? "P" : type == Columns.TYPE_IS_TIMED_ACTION ? "A" : Integer.toString(type), profId >> Columns.PROFILE_SHIFT, profId & Columns.ACTION_MASK, type == Columns.TYPE_IS_PROFILE ? (enable == 0 ? "D" : /*1*/ "E") : // profile: enable/disabled (enable == 0 ? "I" : // action: inactive/prev/next (enable == 1 ? "P" : /*2*/ "N")) )); // Description profile:user name, action: display summary sb.append(desc); if (type == Columns.TYPE_IS_TIMED_ACTION) { // Format: [ d:days-bitfield, hm:hour*60+min, a:actions/-, n:next MS ] sb.append(String.format(" [ d:%1$01x, hm:%2$04d, a:'%3$s', n:%d ]", days, hourMin, actions == null ? "-" : actions, nextMs )); } sb.append("\n"); summaries[i++] = sb.toString(); } while (c.moveToNext()); } return summaries; } finally { if (c != null) c.close(); } } /** * Returns the list of all enabled profiles. * This is a list of profiles indexes. * Can return an empty list, but not null. */ public long[] getEnabledProfiles() { // generates WHERE type=1 (aka profile) AND enable=1 String where = String.format("%s=%d AND %s=%d", Columns.TYPE, Columns.TYPE_IS_PROFILE, Columns.IS_ENABLED, 1); Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table new String[] { Columns.PROFILE_ID }, // columns where, // selection null, // selectionArgs null, // groupBy null, // having null // orderBy ); int profIdColIndex = c.getColumnIndexOrThrow(Columns.PROFILE_ID); long[] indexes = new long[c.getCount()]; if (c.moveToFirst()) { int i = 0; do { indexes[i++] = c.getLong(profIdColIndex) >> Columns.PROFILE_SHIFT; } while (c.moveToNext()); } return indexes; } finally { if (c != null) c.close(); } } /** * Returns the list of timed actions that should be activated "now", * as defined by the given day and hour/minute and limited to the * given list of profiles. * <p/> * Returns a list of action prof_id (ids, not indexes) or null. * prof_indexes is a list of profile indexes (not ids) that are currently * enabled. * <p/> * Synopsis: * - If there are no profiles activated, abort. That is we support prof_ids * being an empty list. * - Selects actions which action_day & given_day != 0 (bitfield match) * - Selects all actions for that day, independently of the hourMin. * The hourMin check is done after on the result. * - Can return an empty list, but not null. */ public ActionInfo[] getDayActivableActions(int hourMin, int day, long[] prof_indexes) { if (prof_indexes.length < 1) return null; StringBuilder profList = new StringBuilder(); for (long prof_index : prof_indexes) { if (profList.length() > 0) profList.append(","); profList.append(Long.toString(prof_index)); } // generates WHERE type=2 (aka action) // AND hourMin <= targetHourMin // AND days & MASK != 0 // AND prof_id >> SHIFT IN (profList) String where = String.format("%s=%d AND (%s <= %d) AND (%s & %d) != 0 AND (%s >> %d) IN (%s)", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.HOUR_MIN, hourMin, Columns.DAYS, day, Columns.PROFILE_ID, Columns.PROFILE_SHIFT, profList); // ORDER BY hourMin DESC String orderBy = String.format("%s DESC", Columns.HOUR_MIN); if (DEBUG) Log.d(TAG, "Get actions: WHERE " + where + " ORDER BY " + orderBy); Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table new String[] { Columns._ID, Columns.HOUR_MIN, Columns.ACTIONS }, // columns where, // selection null, // selectionArgs null, // groupBy null, // having orderBy ); int rowIdColIndex = c.getColumnIndexOrThrow(Columns._ID); int hourMinColIndex = c.getColumnIndexOrThrow(Columns.HOUR_MIN); int actionsColInfo = c.getColumnIndexOrThrow(Columns.ACTIONS); // Above we got the list of all actions for the requested day // that happen before the requested hourMin, in descending time // order, e.g. the most recent action is first in the list. // // We want to return the first action found. There might be more // than one action with the same time, so return them all. ArrayList<ActionInfo> infos = new ArrayList<ActionInfo>(); if (c.moveToFirst()) { int firstHourMin = c.getInt(hourMinColIndex); do { infos.add(new ActionInfo( c.getLong(rowIdColIndex), firstHourMin, // all actions have the same time c.getString(actionsColInfo))); if (DEBUG) Log.d(TAG, String.format("ActivableAction: day %d, hourMin %04d", day, firstHourMin)); } while (c.moveToNext() && c.getInt(hourMinColIndex) == firstHourMin); } return infos.toArray(new ActionInfo[infos.size()]); } finally { if (c != null) c.close(); } } /** * Invokes {@link #getDayActivableActions(int, int, long[])} for the current * day. If nothing is found, look at the 6 previous days to see if we can * find an action. */ public ActionInfo[] getWeekActivableActions(int hourMin, int day, long[] prof_indexes) { ActionInfo[] actions = null; // Look for the last enabled action for day. // If none was found, loop up to 6 days before and check the last // action before 24:00. for (int k = 0; k < 7; k++) { actions = getDayActivableActions(hourMin, day, prof_indexes); if (actions != null && actions.length > 0) { break; } // Switch to previous day and loop from monday to sunday as needed. day = day >> 1; if (day == 0) day = Columns.SUNDAY; // Look for anything "before the end of the day". Since we // want to match 23:59 we need to add one minute thus 24h00 // is our target. hourMin = 24*60 + 0; } return actions; } /** * Given a day and an hourMin time, try to find the first event that happens * after that timestamp. If nothing if found on the day, look up to 6 days * ahead. * * prof_indexes is a list of profile indexes (not ids) that are currently * enabled. * * @return The number of minutes from the given timestamp to the next event * or 0 if there's no such event ("now" is not a valid next event) */ public int getWeekNextEvent(int hourMin, int day, long[] prof_indexes, ActionInfo[] out_actions) { // First try to find something today that is past the requested time. ActionInfo found = getDayNextEvent(hourMin, day, prof_indexes); if (found != null) { out_actions[0] = found; int delta = found.mHourMin - hourMin; if (delta > 0) { return delta; } } // Otherwise look for the 6 days of events int minutes = 24*60 - hourMin; for(int k = 1; k < 7; k++, minutes += 24*60) { // Switch to next day. Loop from sunday back to monday. day = day << 1; if (day > Columns.SUNDAY) day = Columns.MONDAY; found = getDayNextEvent(-1 /*One minute before 00:00*/, day, prof_indexes); if (found != null) { out_actions[0] = found; return minutes + found.mHourMin; } } return 0; } /** * Given a day and an hourMin time, try to find the first event that happens * after that timestamp on the singular day. * * prof_indexes is a list of profile indexes (not ids) that are currently * enabled. * * @return The hourMin of the event found (hourMin..23:59) or -1 if nothing found. * If the return value is not -1, it is guaranteed to be greater than the * given hourMin since we look for an event *past* this time. */ private ActionInfo getDayNextEvent(int hourMin, int day, long[] prof_indexes) { if (prof_indexes.length < 1) return null; StringBuilder profList = new StringBuilder(); for (long prof_index : prof_indexes) { if (profList.length() > 0) profList.append(","); profList.append(Long.toString(prof_index)); } // generates WHERE type=2 (aka action) // AND hourMin > targetHourMin // AND days & MASK != 0 // AND prof_id >> SHIFT IN (profList) String hourTest; if (hourMin == -1) { hourTest = String.format("%s >= 0", Columns.HOUR_MIN); } else { hourTest = String.format("%s > (%d)", Columns.HOUR_MIN, hourMin); } String where = String.format("%s=%d AND (%s) AND (%s & %d) != 0 AND (%s >> %d) IN (%s)", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, hourTest, Columns.DAYS, day, Columns.PROFILE_ID, Columns.PROFILE_SHIFT, profList); // ORDER BY hourMin ASC String orderBy = String.format("%s ASC", Columns.HOUR_MIN); // LIMIT 1 (we only want the first result) String limit = "1"; if (DEBUG) Log.d(TAG, "Get actions: WHERE " + where + " ORDER BY " + orderBy + " LIMIT " + limit); Cursor c = null; try { c = mDb.query( PROFILES_TABLE, // table new String[] { Columns._ID, Columns.HOUR_MIN, Columns.ACTIONS }, // columns where, // selection null, // selectionArgs null, // groupBy null, // having orderBy, limit ); int rowIdColIndex = c.getColumnIndexOrThrow(Columns._ID); int hourMinColIndex = c.getColumnIndexOrThrow(Columns.HOUR_MIN); int actionColIndex = c.getColumnIndexOrThrow(Columns.ACTIONS); if (c.moveToFirst()) { hourMin = c.getInt(hourMinColIndex); if (DEBUG) Log.d(TAG, String.format("NextEvent: day %d, hourMin %04d", day, hourMin)); return new ActionInfo( c.getLong(rowIdColIndex), hourMin, c.getString(actionColIndex)); } } finally { if (c != null) c.close(); } return null; } /** * Struct that describes a Timed Action returned by * {@link ProfilesDB#getDayActivableActions(int, int, long[])} */ public static class ActionInfo { public final long mRowId; private final int mHourMin; public final String mActions; public ActionInfo(long rowId, int hourMin, String actions) { mRowId = rowId; mHourMin = hourMin; mActions = actions; } @Override public String toString() { return String.format("Action<#.%d @%04d: %s>", mRowId, mActions); } } /** * Mark all the given actions as enabled for the given state. * Any previous actions with the given state are cleared. */ public void markActionsEnabled(ActionInfo[] actions, int state) { StringBuilder rowList = new StringBuilder(); for (ActionInfo info : actions) { if (rowList.length() > 0) rowList.append(","); rowList.append(Long.toString(info.mRowId)); } // generates WHERE type=2 (aka action) AND _id in (profList) String where_set = String.format("%s=%d AND %s IN (%s)", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns._ID, rowList); ContentValues values_set = new ContentValues(1); values_set.put(Columns.IS_ENABLED, state); if (DEBUG) Log.d(TAG, "Mark actions: WHERE " + where_set); // generates WHERE type=2 (aka action) AND is_enabled == state String where_clear = String.format("%s=%d AND %s == %d", Columns.TYPE, Columns.TYPE_IS_TIMED_ACTION, Columns.IS_ENABLED, state); ContentValues values_clear = new ContentValues(1); values_clear.put(Columns.IS_ENABLED, Columns.ACTION_MARK_DEFAULT); beginTransaction(); try { // clear previous marks mDb.update( PROFILES_TABLE, // table values_clear, // values where_clear, // whereClause null // whereArgs ); // set new ones mDb.update( PROFILES_TABLE, // table values_set, // values where_set, // whereClause null // whereArgs ); setTransactionSuccessful(); } finally { endTransaction(); } } }
110165172-description
TimeriSample/Timer1App/src/main/java/com/rdrrlabs/example/timer1app/core/profiles1/ProfilesDB.java
Java
gpl3
45,835