Commiting to continue stuff at home
[swf-overlay.git] / ConfigParserRegistry.as
1 package {
2 import flash.net.*
3 import flash.events.Event;
4 import flash.events.IOErrorEvent;
5
6 public class ConfigParserRegistry extends PollableBaseRegistry {
7 private var request:URLRequest;
8 private var loader:URLLoader;
9 private var fileLock:Boolean;
10 private var loadCallback:Function;
11
12 public function ConfigParserRegistry(fileName:String) {
13 super(this.parse);
14 this.fileLock = false;
15 this.request = new URLRequest(fileName);
16 this.loader = new URLLoader();
17 }
18
19 public function parse() {
20 if(!this.fileLock) {
21 this.loadCallback = this.onLoaded(this);
22
23 loader.addEventListener(Event.COMPLETE, this.loadCallback);
24 loader.addEventListener(IOErrorEvent.IO_ERROR, this.ioError);
25 this.fileLock = true;
26 this.loader.load(this.request);
27 } else {
28 trace("Lock active, not doing anything.");
29 }
30 }
31
32 private function releaseLock() {
33 this.fileLock = false;
34 }
35
36 // Sometimes I think this acesses the file at the same time it is being saved
37 // which causes havock. In that case I just release the lock and clear everything.
38 private function ioError(e:Event) {
39 this.loader.removeEventListener(Event.COMPLETE, this.loadCallback);
40 this.loader.removeEventListener(IOErrorEvent.IO_ERROR, this.ioError);
41 this.releaseLock();
42 }
43
44 private function onLoaded(configParser:ConfigParserRegistry):Function {
45 return function(e:Event):void {
46 //Deal with windows style line endings, and tabs.
47 var lines = configParser.loader.data.replace(/(\t|\r)/gi, "").split("\n");
48 configParser.parseVars(lines);
49 configParser.releaseLock();
50 configParser.loader.removeEventListener(Event.COMPLETE, configParser.loadCallback);
51 configParser.loader.removeEventListener(IOErrorEvent.IO_ERROR, configParser.ioError);
52 }
53 }
54
55 private function parseVars(lines:Array) {
56 var section:String = null;
57 var matches:Array;
58 var keyValue:Array;
59 var dotDelim:String;
60
61 for each(var line in lines) {
62 // I'm gonna hate myself for this in a few weeks
63 section = ((matches = line.match(/\[(\w+)\]/)) && matches[1]) || section;
64 keyValue = line.split("=", 2).map(Util.trim);
65
66 if(keyValue.length == 2) {
67 dotDelim = section ? section + "." + keyValue[0] : keyValue[0];
68 if(this.get(dotDelim) != keyValue[1]) {
69 var obj:Object = {};
70 if(section) {
71 obj[section] = new Object();
72 obj[section][keyValue[0]] = keyValue[1];
73
74 } else {
75 obj[keyValue[0]] = keyValue[1];
76 }
77
78 this.add(obj);
79 }
80 }
81 }
82
83 this.commit();
84 }
85 }
86 }