package { import flash.net.* import flash.events.Event; import flash.events.IOErrorEvent; public class ConfigParserRegistry extends PollableBaseRegistry { private var request:URLRequest; private var loader:URLLoader; private var fileLock:Boolean; private var loadCallback:Function; public function ConfigParserRegistry(fileName:String) { super(this.parse); this.fileLock = false; this.request = new URLRequest(fileName); this.loader = new URLLoader(); } public function parse() { if(!this.fileLock) { this.loadCallback = this.onLoaded(this); loader.addEventListener(Event.COMPLETE, this.loadCallback); loader.addEventListener(IOErrorEvent.IO_ERROR, this.ioError); this.fileLock = true; this.loader.load(this.request); } else { trace("Lock active, not doing anything."); } } private function releaseLock() { this.fileLock = false; } // Sometimes I think this acesses the file at the same time it is being saved // which causes havock. In that case I just release the lock and clear everything. private function ioError(e:Event) { this.loader.removeEventListener(Event.COMPLETE, this.loadCallback); this.loader.removeEventListener(IOErrorEvent.IO_ERROR, this.ioError); this.releaseLock(); } private function onLoaded(configParser:ConfigParserRegistry):Function { return function(e:Event):void { //Deal with windows style line endings, and tabs. var lines = configParser.loader.data.replace(/(\t|\r)/gi, "").split("\n"); configParser.parseVars(lines); configParser.releaseLock(); configParser.loader.removeEventListener(Event.COMPLETE, configParser.loadCallback); configParser.loader.removeEventListener(IOErrorEvent.IO_ERROR, configParser.ioError); } } private function parseVars(lines:Array) { var section:String = null; var matches:Array; var keyValue:Array; var dotDelim:String; for each(var line in lines) { // I'm gonna hate myself for this in a few weeks section = ((matches = line.match(/\[(\w+)\]/)) && matches[1]) || section; keyValue = line.split("=", 2).map(Util.trim); if(keyValue.length == 2) { dotDelim = section ? section + "." + keyValue[0] : keyValue[0]; if(this.get(dotDelim) != keyValue[1]) { var obj:Object = {}; if(section) { obj[section] = new Object(); obj[section][keyValue[0]] = keyValue[1]; } else { obj[keyValue[0]] = keyValue[1]; } this.add(obj); } } } this.commit(); } } }