home *** CD-ROM | disk | FTP | other *** search
/ Mundo do CD-ROM 119 / cdrom119.iso / internet / gsync / google-browsersync.xpi / lib / browserstate.js
Encoding:
JavaScript  |  2006-06-07  |  311.1 KB  |  1,269 lines

  1. function isDef(val){return typeof val!="undefined"}
  2. function isNull(val){return val===null}
  3. function isArray(val){return isObject(val)&&val.constructor==Array}
  4. function isString(val){return typeof val=="string"}
  5. function isFunction(val){return typeof val=="function"}
  6. function isObject(val){return val&&typeof val=="object"}
  7. function getObjectProps(obj){var ret=[];for(var p in obj){ret.push(p)}return ret}
  8. function isEmptyObject(val){if(!isObject(val)){return false}for(var p in val){return false}return true}
  9. var getHashCode;var removeHashCode;(function(){var hashCodeProperty="lang_hashCode_";getHashCode=function(obj){if(!obj[hashCodeProperty]){obj[hashCodeProperty]=++getHashCode.hashCodeCounter_}return obj[hashCodeProperty]}
  10. ;removeHashCode=function(obj){obj[hashCodeProperty]=undefined}
  11. ;getHashCode.hashCodeCounter_=0}
  12. )();String.prototype.startsWith=function(prefix){if(this.length<prefix.length){return false}if(this.substring(0,prefix.length)==prefix){return true}return false}
  13. ;String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}
  14. ;String.prototype.subs=function(){var ret=this;for(var i=0;i<arguments.length;i++){ret=ret.replace(/\%s/,String(arguments[i]))}return ret}
  15. ;if(!Function.prototype.apply){Function.prototype.apply=function(oScope,args){var sarg=[];var rtrn,call;if(!oScope)oScope=window;if(!args)args=[];for(var i=0;i<args.length;i++){sarg[i]="args["+i+"]"}call="oScope.__applyTemp__.peek().("+sarg.join(",")+");";if(!oScope.__applyTemp__){oScope.__applyTemp__=[]}oScope.__applyTemp__.push(this);rtrn=eval(call);oScope.__applyTemp__.pop();return rtrn}
  16. }if(!Array.prototype.push){Array.prototype.push=function(){for(var i=0;i<arguments.length;i++){this[this.length]=arguments[i]}return this.length}
  17. }if(!Array.prototype.pop){Array.prototype.pop=function(){if(!this.length){return}var val=this[this.length-1];this.length--;return val}
  18. }Array.prototype.peek=function(){return this[this.length-1]}
  19. ;if(!Array.prototype.shift){Array.prototype.shift=function(){if(this.length==0){return}var val=this[0];for(var i=0;i<this.length-1;i++){this[i]=this[i+1]}this.length--;return val}
  20. }if(!Array.prototype.unshift){Array.prototype.unshift=function(){var numArgs=arguments.length;for(var i=this.length-1;i>=0;i--){this[i+numArgs]=this[i]}for(var j=0;j<numArgs;j++){this[j]=arguments[j]}return this.length}
  21. }if(!Array.prototype.forEach){Array.prototype.forEach=function(callback,scope){for(var i=0;i<this.length;i++){callback.apply(scope,[this[i]])}}
  22. }function bind(fn,self,opt_args){var boundargs=fn.boundArgs_||[];boundargs=boundargs.concat(Array.prototype.slice.call(arguments,2));if(typeof fn.boundSelf_!="undefined"){self=fn.boundSelf_}if(typeof fn.foundFn_!="undefined"){fn=fn.boundFn_}var newfn=function(){var args=boundargs.concat(Array.prototype.slice.call(arguments));return fn.apply(self,args)}
  23. ;newfn.boundArgs_=boundargs;newfn.boundSelf_=self;newfn.boundFn_=fn;return newfn}
  24. Function.prototype.bind=function(self,opt_args){return bind.apply(null,[this,self].concat(Array.prototype.slice.call(arguments,1)))}
  25. ;function partial(fn,opt_args){return bind.apply(null,[fn,null].concat(Array.prototype.slice.call(arguments,1)))}
  26. Function.prototype.partial=function(opt_args){return bind.apply(null,[this,null].concat(Array.prototype.slice.call(arguments)))}
  27. ;function bindMethods(obj){for(var p in obj){if(isFunction(obj[p])){obj[p]=obj[p].bind(obj)}}}
  28. Function.prototype.inherits=function(parentCtor){var tempCtor=function(){}
  29. ;tempCtor.prototype=parentCtor.prototype;this.superClass_=parentCtor.prototype;this.prototype=new tempCtor}
  30. ;Function.prototype.mixin=function(props){for(var x in props){this.prototype[x]=props[x]}if(isFunction(props["toString"])&&props["toString"]!=this.prototype["toString"]){this.prototype.toString=props.toString}}
  31. ;
  32. function SHA1(){this._chain=new Array(5);this._buf=new Array(64);this._W=new Array(80);this._pad=new Array(64);this._pad[0]=128;for(var i=1;i<64;++i){this._pad[i]=0}this.reset()}
  33. SHA1.prototype.reset=function(){this._chain[0]=1732584193;this._chain[1]=4023233417;this._chain[2]=2562383102;this._chain[3]=271733878;this._chain[4]=3285377520;this._inbuf=0;this._total=0}
  34. ;SHA1.prototype._rotl=function(w,r){return(w<<r|w>>>32-r)&4294967295}
  35. ;SHA1.prototype._compress=function(buf){var W=this._W;for(var i=0;i<64;i+=4){var w=buf[i]<<24|buf[i+1]<<16|buf[i+2]<<8|buf[i+3];W[i/4]=w}for(var i=16;i<80;++i){W[i]=this._rotl(W[i-3]^W[i-8]^W[i-14]^W[i-16],1)}var A=this._chain[0];var B=this._chain[1];var C=this._chain[2];var D=this._chain[3];var E=this._chain[4];var f,k;for(var i=0;i<80;++i){if(i<40){if(i<20){f=D^B&(C^D);k=1518500249}else{f=B^C^D;k=1859775393}}else{if(i<60){f=B&C|D&(B|C);k=2400959708}else{f=B^C^D;k=3395469782}}var t=this._rotl(A,
  36. 5)+f+E+k+W[i]&4294967295;E=D;D=C;C=this._rotl(B,30);B=A;A=t}this._chain[0]=this._chain[0]+A&4294967295;this._chain[1]=this._chain[1]+B&4294967295;this._chain[2]=this._chain[2]+C&4294967295;this._chain[3]=this._chain[3]+D&4294967295;this._chain[4]=this._chain[4]+E&4294967295}
  37. ;SHA1.prototype.update=function(bytes,opt_length){if(!opt_length){opt_length=bytes.length}var n=0;if(this._inbuf==0){while(n+64<opt_length){this._compress(bytes.slice(n,n+64));n+=64;this._total+=64}}while(n<opt_length){this._buf[this._inbuf++]=bytes[n++];++this._total;if(this._inbuf==64){this._inbuf=0;this._compress(this._buf);while(n+64<opt_length){this._compress(bytes.slice(n,n+64));n+=64;this._total+=64}}}}
  38. ;SHA1.prototype.digest=function(){var digest=new Array(20);var totalBits=this._total*8;if(this._inbuf<56){this.update(this._pad,56-this._inbuf)}else{this.update(this._pad,64-(this._inbuf-56))}for(var i=63;i>=56;--i){this._buf[i]=totalBits&255;totalBits>>>=8}this._compress(this._buf);var n=0;for(var i=0;i<5;++i){for(var j=24;j>=0;j-=8){digest[n++]=this._chain[i]>>j&255}}return digest}
  39. ;
  40. function ARC4(){this._S=new Array(256);this._i=0;this._j=0}
  41. ARC4.prototype.setKey=function(key,opt_length){if(!isArray(key)){throw new Error("Key parameter must be a byte array");}if(!opt_length){opt_length=key.length}var S=this._S;for(var i=0;i<256;++i){S[i]=i}var j=0;for(var i=0;i<256;++i){j=j+S[i]+key[i%opt_length]&255;var tmp=S[i];S[i]=S[j];S[j]=tmp}this._i=0;this._j=0}
  42. ;ARC4.prototype.discard=function(n){var devnul=new Array(n);this.crypt(devnul)}
  43. ;ARC4.prototype.crypt=function(data,opt_length){if(!opt_length){opt_length=data.length}if(!isArray(data)){throw new Error("Data parameter must be a byte array");}var i=this._i;var j=this._j;var S=this._S;for(var n=0;n<opt_length;++n){i=i+1&255;j=j+S[i]&255;var tmp=S[i];S[i]=S[j];S[j]=tmp;data[n]^=S[S[i]+S[j]&255]}this._i=i;this._j=j}
  44. ;
  45. function RSAEP(m,dinv,rr){this._M=m;this._DINV=dinv;this._RR=rr;this._LEN=m.length;this._sha1=new SHA1;this._arc4=new ARC4}
  46. RSAEP.prototype._montdMulAdd=function(a,b,c){var A=a*b[0]+c[0];var d0=(A&65535)*this._DINV&65535;var B=d0*this._M[0]+(A&65535);for(var i=1;i<this._LEN;++i){A=(A>>>16)+a*b[i]+c[i];B=(B>>>16)+d0*this._M[i]+(A&65535);c[i-1]=B&65535}c[i-1]=(A>>>16)+(B>>>16)}
  47. ;RSAEP.prototype._bGeM=function(a){for(var i=this._LEN-1;i>0;--i){if(a[i]!=this._M[i]){return a[i]>this._M[i]}}return a[0]>=this._M[0]}
  48. ;RSAEP.prototype._bSubM=function(a){var accu=0;for(var i=0;i<this._LEN;++i){accu+=a[i]-this._M[i];a[i]=accu&65535;accu>>=16}}
  49. ;RSAEP.prototype._montMul=function(a,b,c){if(!c){c=new Array(this._LEN)}for(var i=0;i<this._LEN;++i){c[i]=0}for(var i=0;i<this._LEN;++i){this._montdMulAdd(a[i],b,c)}if(this._bGeM(c)){this._bSubM(c)}return c}
  50. ;RSAEP.prototype._pow3=function(a){var accu=this._montMul(a,this._RR);var sqr=this._montMul(accu,accu);return this._montMul(sqr,a,accu)}
  51. ;RSAEP.prototype.capacity=function(){return this._LEN*2-20-20-1}
  52. ;RSAEP.prototype.encrypt=function(M,r){if(r.length!=20){this._sha1.reset();this._sha1.update(r);r=this._sha1.digest()}r[19]&=63;this._sha1.reset();this._sha1.update(r);this._sha1.update(M);var GMr=this._sha1.digest();var p=new Array(this._LEN*2);var i=0;p[i++]=M.length;var j=0;while(j<M.length){p[i++]=M[j++]}j=0;while(i<p.length-20){p[i++]=GMr[j++%GMr.length]}j=0;while(i<p.length){p[i++]=r[j++]}if(j!=20){return null}this._arc4.setKey(r);this._arc4.crypt(p,p.length-20);this._sha1.reset();this._sha1.update(
  53. p,p.length-20);var rMask=this._sha1.digest();for(var i=0;i<20;++i){p[p.length-20+i]^=rMask[i]}p[p.length-1]&=63;var pw=new Array(this._LEN);for(i=0;i<p.length;i+=2){pw[i/2]=p[i]+p[i+1]*256}pw=this._pow3(pw);for(i=0;i<p.length;i+=2){p[p.length-1-i]=pw[i/2]&255;p[p.length-2-i]=pw[i/2]>>>8}return p}
  54. ;
  55. function G_SetXOR(list1,list2){var list1Map={};var list2Map={};var output1=[];var output2=[];for(var i=0;i<list1.length;i++){list1Map[list1[i]]=true}for(var i=0;i<list2.length;i++){list2Map[list2[i]]=true}for(var key in list1Map){if(!isDef(list2Map[key])){output1.push(key)}}for(var key in list2Map){if(!isDef(list1Map[key])){output2.push(key)}}return{xor:Array.concat(output1,output2),left:output1,right:output2}}
  56. function G_SetMerge(opt_arg1,opt_arg2,opt_arg3,opt_arg4,opt_arg5,opt_arg6,opt_arg7,opt_arg8,opt_arg9){var resultMap={};for(var i=0;i<arguments.length;i++){var arr=arguments[i];for(var j=0;j<arr.length;j++){resultMap[arr[j]]=true}}var result=[];for(var key in resultMap){result.push(key)}return result}
  57. ;
  58. function G_DoubleDictionary(opt_initialValues){this.keysToValues_={};this.valuesToKeys_={};if(opt_initialValues){this.addMultiple(opt_initialValues)}}
  59. G_DoubleDictionary.prototype.addItem=function(key,value){if(this.hasKey(key)){throw new Error("The specified key {%s} already exists".subs(key));}if(this.hasValue(value)){throw new Error("The specified value {%s} already exists.".subs(value));}this.keysToValues_[key]=value;this.valuesToKeys_[value]=key}
  60. ;G_DoubleDictionary.prototype.addMultiple=function(obj){for(var p in obj){this.addItem(p,obj[p])}}
  61. ;G_DoubleDictionary.prototype.getKey=function(val){return this.valuesToKeys_[val]}
  62. ;G_DoubleDictionary.prototype.getValue=function(key){return this.keysToValues_[key]}
  63. ;G_DoubleDictionary.prototype.getKeys=function(){return getObjectProps(this.keysToValues_)}
  64. ;G_DoubleDictionary.prototype.getValues=function(){return getObjectProps(this.valuesToKeys_)}
  65. ;G_DoubleDictionary.prototype.hasKey=function(key){return isDef(this.keysToValues_[key])}
  66. ;G_DoubleDictionary.prototype.hasValue=function(value){return isDef(this.valuesToKeys_[value])}
  67. ;{};
  68. function G_WorkQueue(){bindMethods(this);this.maxRunTime=200;this.pauseTime=0;this.queue_=[];this.running_=false;if(G_WorkQueue.global_.G_Alarm){this.scheduleResume_=this.scheduleAlarmResume_}else{this.scheduleResume_=this.scheduleTimeoutResume_}}
  69. G_WorkQueue.global_=this;G_WorkQueue.prototype.addJob=function(jobFn){this.queue_.push(jobFn);if(!this.running_){this.running_=true;this.resume_()}}
  70. ;G_WorkQueue.prototype.cancel=function(){if(this.alarm_){this.alarm_.cancel()}else if(this.timerID_){window.clearTimeout(this.timerID_)}}
  71. ;G_WorkQueue.prototype.onError=function(failedJob,e){throw e;}
  72. ;G_WorkQueue.prototype.resume_=function(){this.alarm_=null;this.timerID_=null;this.batchStart_=(new Date).getTime();var nextJob;while(nextJob=this.queue_[0]){if(new Date-this.batchStart_>this.maxRunTime){this.scheduleResume_();return}try{nextJob()}catch(e){this.onError(nextJob,e)}this.queue_.shift()}this.running_=false}
  73. ;G_WorkQueue.prototype.scheduleAlarmResume_=function(){this.alarm_=new G_Alarm(this.resume_,this.pauseTime)}
  74. ;G_WorkQueue.prototype.scheduleTimeoutResume_=function(){this.timerID_=window.setTimeout(this.resume_,this.pauseTime)}
  75. ;
  76. function G_Preferences(opt_startPoint,opt_getDefaultBranch){this.debugZone="prefs";this.observers_={};var startPoint=opt_startPoint||null;var prefSvc=Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);if(opt_getDefaultBranch){this.prefs_=prefSvc.getDefaultBranch(startPoint)}else{this.prefs_=prefSvc.getBranch(startPoint)}this.prefs_.QueryInterface(Ci.nsIPrefBranchInternal)}
  77. G_Preferences.setterMap_={string:"setCharPref","boolean":"setBoolPref",number:"setIntPref"};G_Preferences.getterMap_={};G_Preferences.getterMap_[Ci.nsIPrefBranch.PREF_STRING]="getCharPref";G_Preferences.getterMap_[Ci.nsIPrefBranch.PREF_BOOL]="getBoolPref";G_Preferences.getterMap_[Ci.nsIPrefBranch.PREF_INT]="getIntPref";G_Preferences.prototype.setPref=function(key,val){var datatype=typeof val;if(datatype=="number"&&val%1!=0){throw new Error("Cannot store non-integer numbers in preferences.");}var meth=
  78. G_Preferences.setterMap_[datatype];if(!meth){throw new Error("Pref datatype {"+datatype+"} not supported.");}return this.prefs_[meth](key,val)}
  79. ;G_Preferences.prototype.getPref=function(key,opt_default){var type=this.prefs_.getPrefType(key);if(type==Ci.nsIPrefBranch.PREF_INVALID){return opt_default}var meth=G_Preferences.getterMap_[type];if(!meth){throw new Error("Pref datatype {"+type+"} not supported.");}try{return this.prefs_[meth](key)}catch(e){return opt_default}}
  80. ;G_Preferences.prototype.setBoolPref=function(which,value){return this.setPref(which,value)}
  81. ;G_Preferences.prototype.getBoolPref=function(which){return this.prefs_.getBoolPref(which)}
  82. ;G_Preferences.prototype.getBoolPrefOrDefault=function(which,def){return this.getPref(which,def)}
  83. ;G_Preferences.prototype.getBoolPrefOrDefaultAndSet=function(which,def){try{return this.prefs_.getBoolPref(which)}catch(e){this.prefs_.setBoolPref(which,!(!def));return def}}
  84. ;G_Preferences.prototype.clearPref=function(which){try{this.prefs_.clearUserPref(which)}catch(e){}}
  85. ;G_Preferences.prototype.addObserver=function(which,callback){var observer=new G_PreferenceObserver(callback);if(!this.observers_[which])this.observers_[which]=new G_ObjectSafeMap;this.observers_[which].insert(callback,observer);this.prefs_.addObserver(which,observer,false)}
  86. ;G_Preferences.prototype.removeObserver=function(which,callback){var observer=this.observers_[which].find(callback);G_Assert(this,!(!observer),"Tried to unregister a nonexistant observer");this.prefs_.removeObserver(which,observer);this.observers_[which].erase(callback)}
  87. ;G_Preferences.prototype.getChildNames=function(opt_startingPoint){if(!opt_startingPoint){opt_startingPoint=""}return this.prefs_.getChildList(opt_startingPoint,{})}
  88. ;function G_PreferenceObserver(callback){this.debugZone="prefobserver";this.callback_=callback}
  89. G_PreferenceObserver.prototype.observe=function(subject,topic,data){G_Debug(this,"Observed pref change: "+data);this.callback_(data)}
  90. ;G_PreferenceObserver.prototype.QueryInterface=function(iid){var Ci=Ci;if(iid.equals(Ci.nsISupports)||iid.equals(Ci.nsIObserves)||iid.equals(Ci.nsISupportsWeakReference))return this;throw Components.results.NS_ERROR_NO_INTERFACE;}
  91. ;
  92. if(!isDef(true)){throw new Error("G_GDEBUG constant must be set before loading debug.js");}function G_Debug(who,msg){G_GetDebugZone(who).debug(msg)}
  93. function G_DebugL(who,msg){var zone=G_GetDebugZone(who);if(zone.zoneIsEnabled()){G_debugService.dump(G_File.LINE_END_CHAR+"************************************************************"+G_File.LINE_END_CHAR);G_Debug(who,msg);G_debugService.dump("************************************************************"+G_File.LINE_END_CHAR+G_File.LINE_END_CHAR)}}
  94. function G_TraceCall(who,msg){if(G_debugService.callTracingEnabled()){G_debugService.dump(msg+G_File.LINE_END_CHAR)}}
  95. function G_Error(who,msg){G_GetDebugZone(who).error(msg)}
  96. function G_Assert(who,condition,msg){G_GetDebugZone(who).assert(condition,msg)}
  97. function G_GetDebugZone(who){var zone="?";if(who&&who.debugZone){zone=who.debugZone}else if(isString(who)){zone=who}return G_debugService.getZone(zone)}
  98. function G_DebugZone(service,prefix,zone){this.debugService_=service;this.prefix_=prefix;this.zone_=zone;this.zoneEnabledPrefName_=prefix+".zone."+this.zone_;this.settings_=new G_DebugSettings}
  99. G_DebugZone.prototype.zoneIsEnabled=function(){var explicit=this.settings_.getSetting(this.zoneEnabledPrefName_,null);if(explicit!==null){return explicit}else{return this.debugService_.allZonesEnabled()}}
  100. ;G_DebugZone.prototype.enableZone=function(){this.settings_.setDefault(this.zoneEnabledPrefName_,true)}
  101. ;G_DebugZone.prototype.disableZone=function(){this.settings_.setDefault(this.zoneEnabledPrefName_,false)}
  102. ;G_DebugZone.prototype.debug=function(msg){if(this.zoneIsEnabled()){this.debugService_.dump("[%s] %s%s".subs(this.zone_,msg,G_File.LINE_END_CHAR))}}
  103. ;G_DebugZone.prototype.error=function(msg){this.debugService_.dump("[%s] %s%s".subs(this.zone_,msg,G_File.LINE_END_CHAR));throw new Error(msg);debugger}
  104. ;G_DebugZone.prototype.assert=function(condition,msg){if(condition!==true){G_Error(this.zone_,"ASSERT FAILED: "+msg)}}
  105. ;function G_DebugService(opt_prefix){this.prefix_=opt_prefix?opt_prefix:"google-debug-service";this.shellEnabledPrefName_=this.prefix_+".alsologtoshell";this.consoleEnabledPrefName_=this.prefix_+".alsologtoconsole";this.allZonesEnabledPrefName_=this.prefix_+".enableallzones";this.callTracingEnabledPrefName_=this.prefix_+".trace-function-calls";this.logFileEnabledPrefName_=this.prefix_+".logfileenabled";this.logFileErrorLevelPrefName_=this.prefix_+".logfile-errorlevel";this.zones_={};this.loggifier=
  106. new G_Loggifier;this.settings_=new G_DebugSettings;this.timer_=Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);this.timer_.initWithCallback(this,G_DebugService.TIMESTAMP_INTERVAL,Ci.nsITimer.TYPE_REPEATING_SLACK);this.activeSinceLastTimestamp_=false;Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService).registerListener(this)}
  107. G_DebugService.ERROR_LEVEL_INFO="INFO";G_DebugService.ERROR_LEVEL_WARNING="WARNING";G_DebugService.ERROR_LEVEL_EXCEPTION="EXCEPTION";G_DebugService.TIMESTAMP_INTERVAL=300000;G_DebugService.prototype.QueryInterface=function(iid){if(iid.equals(Ci.nsISupports)||iid.equals(Ci.nsITimerCallback)){return this}throw Components.results.NS_ERROR_NO_INTERFACE;}
  108. ;G_DebugService.prototype.alsoDumpToShell=function(){return this.settings_.getSetting(this.shellEnabledPrefName_,true)}
  109. ;G_DebugService.prototype.alsoDumpToConsole=function(){return this.settings_.getSetting(this.consoleEnabledPrefName_,false)}
  110. ;G_DebugService.prototype.logFileIsEnabled=function(){return this.settings_.getSetting(this.logFileEnabledPrefName_,false)}
  111. ;G_DebugService.prototype.enableLogFile=function(){this.settings_.setDefault(this.logFileEnabledPrefName_,true)}
  112. ;G_DebugService.prototype.disableLogFile=function(){this.settings_.setDefault(this.logFileEnabledPrefName_,false);this.closeLogFile()}
  113. ;G_DebugService.prototype.getLogFile=function(){return this.logFile_}
  114. ;G_DebugService.prototype.setLogFile=function(file){if(this.logWriter_){this.closeLogFile()}this.logFile_=file}
  115. ;G_DebugService.prototype.closeLogFile=function(){this.logWriter_.close();this.logWriter_=null}
  116. ;G_DebugService.prototype.enableDumpToShell=function(){this.settings_.setDefault(this.shellEnabledPrefName_,true)}
  117. ;G_DebugService.prototype.disableDumpToShell=function(){this.settings_.setDefault(this.shellEnabledPrefName_,false)}
  118. ;G_DebugService.prototype.enableDumpToConsole=function(){this.settings_.setDefault(this.consoleEnabledPrefName_,true)}
  119. ;G_DebugService.prototype.disableDumpToConsole=function(){this.settings_.setDefault(this.consoleEnabledPrefName_,false)}
  120. ;G_DebugService.prototype.getZone=function(zone){if(!this.zones_[zone])this.zones_[zone]=new G_DebugZone(this,this.prefix_,zone);return this.zones_[zone]}
  121. ;G_DebugService.prototype.enableZone=function(zone){var toEnable=this.getZone(zone);toEnable.enableZone()}
  122. ;G_DebugService.prototype.disableZone=function(zone){var toDisable=this.getZone(zone);toDisable.disableZone()}
  123. ;G_DebugService.prototype.allZonesEnabled=function(){return this.settings_.getSetting(this.allZonesEnabledPrefName_,false)}
  124. ;G_DebugService.prototype.enableAllZones=function(){this.settings_.setDefault(this.allZonesEnabledPrefName_,true)}
  125. ;G_DebugService.prototype.disableAllZones=function(){this.settings_.setDefault(this.allZonesEnabledPrefName_,false)}
  126. ;G_DebugService.prototype.callTracingEnabled=function(){return this.settings_.getSetting(this.callTracingEnabledPrefName_,false)}
  127. ;G_DebugService.prototype.enableCallTracing=function(){this.settings_.setDefault(this.callTracingEnabledPrefName_,true)}
  128. ;G_DebugService.prototype.disableCallTracing=function(){this.settings_.setDefault(this.callTracingEnabledPrefName_,false)}
  129. ;G_DebugService.prototype.getLogFileErrorLevel=function(){var level=this.settings_.getSetting(this.logFileErrorLevelPrefName_,G_DebugService.ERROR_LEVEL_EXCEPTION);return level.toUpperCase()}
  130. ;G_DebugService.prototype.setLogFileErrorLevel=function(level){level=level.toUpperCase();if(level!=G_DebugService.ERROR_LEVEL_INFO&&level!=G_DebugService.ERROR_LEVEL_WARNING&&level!=G_DebugService.ERROR_LEVEL_EXCEPTION){throw new Error("Invalid error level specified: {"+level+"}");}this.settings_.setDefault(this.logFileErrorLevelPrefName_,level)}
  131. ;G_DebugService.prototype.notify=function(timer){if(!this.activeSinceLastTimestamp_){return}this.dump(G_File.LINE_END_CHAR+"=========== Date: "+(new Date).toLocaleString()+" ============"+G_File.LINE_END_CHAR+G_File.LINE_END_CHAR);this.activeSinceLastTimestamp_=false}
  132. ;G_DebugService.prototype.dump=function(msg){if(this.alsoDumpToShell()){dump(msg)}if(this.alsoDumpToConsole()){try{var console=Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);console.logStringMessage(msg)}catch(e){dump("G_DebugZone ERROR: COULD NOT DUMP TO CONSOLE"+G_File.LINE_END_CHAR)}}this.maybeDumpToFile(msg);this.activeSinceLastTimestamp_=true}
  133. ;G_DebugService.prototype.maybeDumpToFile=function(msg){if(this.logFileIsEnabled()&&this.logFile_){if(!this.logWriter_){this.logWriter_=new G_FileWriter(this.logFile_,true)}this.logWriter_.write(msg)}}
  134. ;G_DebugService.prototype.observe=function(consoleMessage){var errorLevel=this.getLogFileErrorLevel();if(!(consoleMessage instanceof Ci.nsIScriptError)){if(errorLevel==G_DebugService.ERROR_LEVEL_INFO){this.maybeDumpToFile(G_DebugService.ERROR_LEVEL_INFO+": "+consoleMessage.message+G_File.LINE_END_CHAR)}return}var flags=consoleMessage.flags;var sourceName=consoleMessage.sourceName;var lineNumber=consoleMessage.lineNumber;if(!flags){flags=Ci.nsIScriptError.exceptionFlag}if(!sourceName){sourceName="<unknown>"
  135. }if(!lineNumber){lineNumber="<unknown>"}if(flags&Ci.nsIScriptError.warningFlag){if(errorLevel==G_DebugService.ERROR_LEVEL_WARNING||errorLevel==G_DebugService.ERROR_LEVEL_INFO){this.reportScriptError_(consoleMessage.message,sourceName,lineNumber,G_DebugService.ERROR_LEVEL_WARNING)}}else if(flags&Ci.nsIScriptError.exceptionFlag){this.reportScriptError_(consoleMessage.message,sourceName,lineNumber,G_DebugService.ERROR_LEVEL_EXCEPTION)}}
  136. ;G_DebugService.prototype.reportScriptError_=function(message,sourceName,lineNumber,label){if(sourceName.startsWith("http")){return}var message=["","------------------------------------------------------------",label+": "+message,"location: "+sourceName+", line: "+lineNumber,"------------------------------------------------------------","",""].join(G_File.LINE_END_CHAR);if(this.alsoDumpToShell()){dump(message)}this.maybeDumpToFile(message)}
  137. ;function G_Loggifier(){this.mark_(this)}
  138. G_Loggifier.prototype.mark_=function(obj){obj.__loggified_=true}
  139. ;G_Loggifier.prototype.isLoggified=function(obj){return!(!obj.__loggified_)}
  140. ;G_Loggifier.prototype.getFunctionName_=function(constructor){return constructor.name||"???"}
  141. ;G_Loggifier.prototype.loggify=function(obj){if(!G_debugService.callTracingEnabled()){return}if(typeof window!="undefined"&&obj==window||this.isLoggified(obj))return;var zone=G_GetDebugZone(obj);if(!zone||!zone.zoneIsEnabled()){return}this.mark_(obj);function wrap(meth,objName,methName){return function(){var args=new Array(arguments.length);var argsString="";for(var i=0;i<args.length;i++){args[i]=arguments[i];argsString+=i==0?"":", ";if(isFunction(args[i])){argsString+="[function]"}else{argsString+=
  142. args[i]}}G_TraceCall(this,"> "+objName+"."+methName+"("+argsString+")");try{var retVal=meth.apply(this,arguments);var reportedRetVal=retVal;if(typeof reportedRetVal=="undefined")reportedRetVal="void";else if(reportedRetVal==="")reportedRetVal='"" (empty string)'}catch(e){if(e&&!e.__logged){G_TraceCall(this,"Error: "+e.message+". "+e.fileName+": "+e.lineNumber);try{e.__logged=true}catch(e2){throw e;}}throw e;}G_TraceCall(this,"< "+objName+"."+methName+": "+reportedRetVal);return retVal}
  143. }
  144. ;var ignoreLookup={};if(arguments.length>1){for(var i=1;i<arguments.length;i++){ignoreLookup[arguments[i]]=true}}for(var p in obj){if(typeof obj[p]=="function"&&obj[p].call&&!ignoreLookup[p]){var objName=this.getFunctionName_(obj.constructor);obj[p]=wrap(obj[p],objName,p)}}}
  145. ;function G_DebugSettings(){this.defaults_={};this.prefs_=new G_Preferences}
  146. G_DebugSettings.prototype.getSetting=function(name,opt_default){var override=this.prefs_.getPref(name,null);if(override!==null){return override}else if(name in this.defaults_){return this.defaults_[name]}else{return opt_default}}
  147. ;G_DebugSettings.prototype.setDefault=function(name,val){this.defaults_[name]=val}
  148. ;var G_debugService=new G_DebugService;{G_debugService.enableAllZones()};
  149. var G_File={};G_File.getHomeFile=function(opt_file){return this.getSpecialFile("Home",opt_file)}
  150. ;G_File.getProfileFile=function(opt_file){return this.getSpecialFile("ProfD",opt_file)}
  151. ;G_File.getTempFile=function(opt_file){return this.getSpecialFile("TmpD",opt_file)}
  152. ;G_File.getSpecialFile=function(loc,opt_file){var file=Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get(loc,Ci.nsILocalFile);if(opt_file){file.append(opt_file)}return file}
  153. ;G_File.createUniqueTempFile=function(opt_baseName){var baseName=(opt_baseName||(new Date).getTime())+".tmp";var file=this.getSpecialFile("TmpD",baseName);file.createUnique(file.NORMAL_FILE_TYPE,420);return file}
  154. ;G_File.createUniqueTempDir=function(opt_baseName){var baseName=(opt_baseName||(new Date).getTime())+".tmp";var dir=this.getSpecialFile("TmpD",baseName);dir.createUnique(dir.DIRECTORY_TYPE,484);return dir}
  155. ;G_File.fromFileURI=function(uri){if(uri.indexOf("file://")!=0)throw new Error("File path must be a file:// URL");var fileHandler=Cc["@mozilla.org/network/protocol;1?name=file"].getService(Ci.nsIFileProtocolHandler);return fileHandler.getFileFromURLSpec(uri)}
  156. ;G_File.PR_RDONLY=1;G_File.PR_WRONLY=2;G_File.PR_RDWR=4;G_File.PR_CREATE_FILE=8;G_File.PR_APPEND=16;G_File.PR_TRUNCATE=32;G_File.PR_SYNC=64;G_File.PR_EXCL=128;G_File.__defineGetter__("LINE_END_CHAR",function(){var end_char;if("@mozilla.org/xre/app-info;1" in Cc){end_char=Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS=="WINNT"?"\r\n":"\n"}else{end_char=Cc["@mozilla.org/network/protocol;1?name=http"].getService(Ci.nsIHttpProtocolHandler).platform.toLowerCase().indexOf("win")==0?"\r\n"
  157. :"\n"}G_File.__defineGetter__("LINE_END_CHAR",function(){return end_char}
  158. );return end_char}
  159. );function G_FileReader(file){this.file_=isString(file)?G_File.fromFileURI(file):file}
  160. G_FileReader.readAll=function(file){var reader=new G_FileReader(file);try{return reader.read()}finally{reader.close()}}
  161. ;G_FileReader.prototype.read=function(opt_maxBytes){if(!this.stream_){var fs=Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);fs.init(this.file_,G_File.PR_RDONLY,292,0);this.stream_=Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);this.stream_.init(fs)}if(!isDef(opt_maxBytes)){opt_maxBytes=this.stream_.available()}return this.stream_.read(opt_maxBytes)}
  162. ;G_FileReader.prototype.close=function(opt_maxBytes){if(this.stream_){this.stream_.close();this.stream_=null}}
  163. ;function G_FileWriter(file,opt_append){this.file_=typeof file=="string"?G_File.fromFileURI(file):file;this.append_=!(!opt_append)}
  164. G_FileWriter.writeAll=function(file,data,opt_append){var writer=new G_FileWriter(file,opt_append);try{return writer.write(data)}finally{writer.close();return 0}}
  165. ;G_FileWriter.prototype.write=function(data){if(!this.stream_){this.stream_=Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);var flags=G_File.PR_WRONLY|G_File.PR_CREATE_FILE|(this.append_?G_File.PR_APPEND:G_File.PR_TRUNCATE);this.stream_.init(this.file_,flags,-1,0)}return this.stream_.write(data,data.length)}
  166. ;G_FileWriter.prototype.writeLine=function(data){this.write(data+G_File.LINE_END_CHAR)}
  167. ;G_FileWriter.prototype.close=function(){if(this.stream_){this.stream_.close();this.stream_=null}}
  168. ;
  169. function G_ObjectSafeMap(opt_name){this.debugZone="objectsafemap";this.name_=opt_name?opt_name:"noname";this.keys_=[];this.values_=[]}
  170. G_ObjectSafeMap.prototype.indexOfKey_=function(key){for(var i=0;i<this.keys_.length;i++)if(this.keys_[i]===key)return i;return-1}
  171. ;G_ObjectSafeMap.prototype.insert=function(key,value){if(key===null)throw new Error("Can't use null as a key");if(value===undefined)throw new Error("Can't store undefined values in this map");var i=this.indexOfKey_(key);if(i==-1){this.keys_.push(key);this.values_.push(value)}else{this.keys_[i]=key;this.values_[i]=value}G_Assert(this,this.keys_.length==this.values_.length,"Different number of keys than values!")}
  172. ;G_ObjectSafeMap.prototype.erase=function(key){var keyLocation=this.indexOfKey_(key);var keyFound=keyLocation!=-1;if(keyFound){this.keys_.splice(keyLocation,1);this.values_.splice(keyLocation,1)}G_Assert(this,this.keys_.length==this.values_.length,"Different number of keys than values!");return keyFound}
  173. ;G_ObjectSafeMap.prototype.find=function(key){var keyLocation=this.indexOfKey_(key);return keyLocation==-1?undefined:this.values_[keyLocation]}
  174. ;G_ObjectSafeMap.prototype.replace=function(other){this.keys_=[];this.values_=[];for(var i=0;i<other.keys_.length;i++){this.keys_.push(other.keys_[i]);this.values_.push(other.values_[i])}G_Assert(this,this.keys_.length==this.values_.length,"Different number of keys than values!")}
  175. ;G_ObjectSafeMap.prototype.forEach=function(func){if(typeof func!="function")throw new Error("argument to forEach is not a function, it's a(n) "+typeof func);for(var i=0;i<this.keys_.length;i++)func(this.keys_[i],this.values_[i])}
  176. ;G_ObjectSafeMap.prototype.size=function(){return this.keys_.length}
  177. ;
  178. function G_Alarm(callback,delayMS,opt_repeating,opt_maxTimes){this.debugZone="alarm";this.callback_=callback;this.repeating_=!(!opt_repeating);var Cc=Components.classes;var Ci=Components.interfaces;this.timer_=Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);var type=opt_repeating?this.timer_.TYPE_REPEATING_SLACK:this.timer_.TYPE_ONE_SHOT;this.maxTimes_=opt_maxTimes?opt_maxTimes:null;this.nTimes_=0;this.timer_.initWithCallback(this,delayMS,type)}
  179. G_Alarm.prototype.cancel=function(){if(this.timer_){this.timer_.cancel();this.timer_=null;this.callback_=null}}
  180. ;G_Alarm.prototype.notify=function(timer){var ret=this.callback_();this.nTimes_++;if(this.repeating_&&typeof this.maxTimes_=="number"&&this.nTimes_>=this.maxTimes_){this.cancel()}else if(!this.repeating_){this.cancel()}return ret}
  181. ;G_Alarm.prototype.QueryInterface=function(iid){if(iid.equals(Components.interfaces.nsISupports)||iid.equals(Components.interfaces.nsIObserver)||iid.equals(Components.interfaces.nsITimerCallback))return this;throw Components.results.NS_ERROR_NO_INTERFACE;}
  182. ;function G_ConditionalAlarm(callback,delayMS,opt_repeating,opt_maxTimes){G_Alarm.call(this,callback,delayMS,opt_repeating,opt_maxTimes);this.debugZone="conditionalalarm"}
  183. G_ConditionalAlarm.inherits(G_Alarm);G_ConditionalAlarm.prototype.notify=function(timer){var rv=G_Alarm.prototype.notify.call(this,timer);if(this.repeating_&&rv){G_Debug(this,"Callback of a repeating alarm returned true; cancelling.");this.cancel()}}
  184. ;
  185. function G_CryptoHasher(){this.debugZone="cryptohasher";this.decoder_=new G_Base64;this.hasher_=Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);this.initialized_=false}
  186. G_CryptoHasher.algorithms={MD2:Ci.nsICryptoHash.MD2,MD5:Ci.nsICryptoHash.MD5,SHA1:Ci.nsICryptoHash.SHA1,SHA256:Ci.nsICryptoHash.SHA256,SHA384:Ci.nsICryptoHash.SHA384,SHA512:Ci.nsICryptoHash.SHA512};G_CryptoHasher.prototype.init=function(algorithm){var validAlgorithm=false;for(var alg in G_CryptoHasher.algorithms)if(algorithm==G_CryptoHasher.algorithms[alg])validAlgorithm=true;if(!validAlgorithm)throw new Error("Invalid algorithm: "+algorithm);this.initialized_=true;this.hasher_.init(algorithm)}
  187. ;G_CryptoHasher.prototype.updateFromString=function(input){if(!this.initialized_)throw new Error("You must initialize the hasher first!");this.hasher_.update(this.decoder_.arrayifyString(input),input.length)}
  188. ;G_CryptoHasher.prototype.updateFromArray=function(input){if(!this.initialized_)throw new Error("You must initialize the hasher first!");this.hasher_.update(input,input.length)}
  189. ;G_CryptoHasher.prototype.updateFromStream=function(stream){if(!this.initialized_)throw new Error("You must initialize the hasher first!");this.hasher_.updateFromStream(stream,stream.available())}
  190. ;G_CryptoHasher.prototype.digestRaw=function(){return this.hasher_.finish(false)}
  191. ;G_CryptoHasher.prototype.digestBase64=function(){return this.hasher_.finish(true)}
  192. ;G_CryptoHasher.prototype.digestHex=function(){var raw=this.digestRaw();return this.toHex_(raw)}
  193. ;G_CryptoHasher.prototype.toHex_=function(str){var hexchars="0123456789ABCDEF";var hexrep=new Array(str.length*2);for(var i=0;i<str.length;++i){hexrep[i*2]=hexchars.charAt(str.charCodeAt(i)>>4&15);hexrep[i*2+1]=hexchars.charAt(str.charCodeAt(i)&15)}return hexrep.join("")}
  194. ;
  195. function G_JSModule(){this.factoryLookup_={};this.categoriesLookup_={}}
  196. G_JSModule.prototype.registerObject=function(classID,contractID,className,instance,opt_categories){this.factoryLookup_[classID]=new G_JSFactory(Components.ID(classID),contractID,className,instance,opt_categories);this.categoriesLookup_[classID]=opt_categories}
  197. ;G_JSModule.prototype.registerSelf=function(compMgr,fileSpec,location,type){compMgr=compMgr.QueryInterface(Ci.nsIComponentRegistrar);for(var factory in this.factoryLookup_){compMgr.registerFactoryLocation(this.factoryLookup_[factory].classID,this.factoryLookup_[factory].className,this.factoryLookup_[factory].contractID,fileSpec,location,type);this.factoryLookup_[factory].registerCategories()}}
  198. ;G_JSModule.prototype.getClassObject=function(compMgr,classID,interfaceID){var factory=this.factoryLookup_[classID.toString()];if(!factory){throw new Error("Invalid classID {%s}".subs(classID));}return factory}
  199. ;G_JSModule.prototype.canUnload=function(){return true}
  200. ;function G_JSFactory(classID,contractID,className,instance,opt_categories){this.classID=classID;this.contractID=contractID;this.className=className;this.instance_=instance;this.categories_=opt_categories}
  201. G_JSFactory.prototype.registerCategories=function(){if(this.categories_){var catMgr=Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);for(var i=0,cat;cat=this.categories_[i];i++){catMgr.addCategoryEntry(cat,this.className,this.contractID,true,true)}}}
  202. ;G_JSFactory.prototype.createInstance=function(outer,iid){return this.instance_}
  203. ;
  204. function G_Protocol4Parser(){this.debugZone="protocol4";this.protocol4RegExp_=/([^:]+):\d+:(.*)$/;this.newlineRegExp_=/(\r)?\n/}
  205. G_Protocol4Parser.prototype.parse=function(text){var response={};if(!text)return response;var lines=text.split(this.newlineRegExp_);for(var i=0;i<lines.length;i++)if(this.protocol4RegExp_.exec(lines[i]))response[RegExp.$1]=RegExp.$2;return response}
  206. ;G_Protocol4Parser.prototype.serialize=function(map){if(typeof map!="object")throw new Error("map must be an object");var text="";for(var key in map){if(typeof map[key]!="string")throw new Error("Keys and values must be strings");text+=key+":"+map[key].length+":"+map[key]+"\n"}return text}
  207. ;
  208. function jsInstanceOf(obj,iid){try{obj.QueryInterface(iid);return true}catch(e){if(e==Components.results.NS_ERROR_NO_INTERFACE){return false}else{throw e;}}}
  209. function BindToObject(func,obj,opt_A,opt_B,opt_C,opt_D,opt_E,opt_F){var args=Array.prototype.splice.call(arguments,1,arguments.length);return Function.prototype.bind.apply(func,args)}
  210. ;
  211. function ListDictionary(name){this.name_=name;this.members_=[]}
  212. ListDictionary.prototype.isMember=function(item){for(var i=0;i<this.members_.length;i++)if(this.members_[i]==item)return true;return false}
  213. ;ListDictionary.prototype.addMember=function(item){this.members_.push(item)}
  214. ;ListDictionary.prototype.removeMember=function(item){for(var i=0;i<this.members_.length;i++){if(this.members_[i]==item){for(var j=i;j<this.members_.length;j++)this.members_[j]=this.members_[j+1];this.members_.length--;return true}}return false}
  215. ;ListDictionary.prototype.forEach=function(func){if(typeof func!="function")throw new Error("argument to forEach is not a function, it's a(n) "+typeof func);for(var i=0;i<this.members_.length;i++)func(this.members_[i])}
  216. ;
  217. function EventRegistrar(eventTypes){this.eventTypes=[];this.listeners_={};if(eventTypes instanceof Array){var events=eventTypes}else if(typeof eventTypes=="object"){var events=[];for(var e in eventTypes)events.push(eventTypes[e])}else{throw new Error("Unrecognized init parameter to EventRegistrar");}for(var i=0;i<events.length;i++){this.eventTypes.push(events[i]);this.listeners_[events[i]]=new ListDictionary(events[i]+"Listeners")}}
  218. EventRegistrar.prototype.isKnownEventType=function(eventType){for(var i=0;i<this.eventTypes.length;i++)if(eventType==this.eventTypes[i])return eventType;return false}
  219. ;EventRegistrar.prototype.addEventType=function(eventType){if(this.isKnownEventType(eventType))throw new Error("Event type already known: "+eventType);this.eventTypes.push(eventType);this.listeners_[eventType]=new ListDictionary(eventType+"Listeners")}
  220. ;EventRegistrar.prototype.registerListener=function(eventType,listener){if(this.isKnownEventType(eventType)===false)throw new Error("Unknown event type: "+eventType);this.listeners_[eventType].addMember(listener)}
  221. ;EventRegistrar.prototype.removeListener=function(eventType,listener){if(this.isKnownEventType(eventType)===false)throw new Error("Unknown event type: "+eventType);this.listeners_[eventType].removeMember(listener)}
  222. ;EventRegistrar.prototype.fire=function(eventType,e){if(this.isKnownEventType(eventType)===false)throw new Error("Unknown event type: "+eventType);var invoke=function(listener){listener(e)}
  223. ;this.listeners_[eventType].forEach(invoke)}
  224. ;
  225. function G_TabbedBrowserWatcher(tabBrowser,name,opt_filterAboutBlank){this.debugZone="tabbedbrowserwatcher";this.tabBrowser_=tabBrowser;this.filterAboutBlank_=!(!opt_filterAboutBlank);this.events=G_TabbedBrowserWatcher.events;G_Assert(this,typeof name=="string"&&!(!name),"Need a probabilistically unique name");this.name_=name;this.mark_=G_TabbedBrowserWatcher.mark_+"-"+this.name_;this.registrar_=new EventRegistrar(G_TabbedBrowserWatcher.events);this.tabbox_=this.getTabBrowser().mTabBox;this.onDOMContentLoadedClosure_=
  226. BindToObject(this.onDOMContentLoaded,this);this.tabbox_.addEventListener("DOMContentLoaded",this.onDOMContentLoadedClosure_,true);this.onDOMNodeInsertedClosure_=BindToObject(this.onDOMNodeInserted,this);this.tabbox_.addEventListener("DOMNodeInserted",this.onDOMNodeInsertedClosure_,true);this.onTabSwitchClosure_=BindToObject(this.onTabSwitch,this);this.tabbox_.addEventListener("select",this.onTabSwitchClosure_,true);var win=this.tabbox_.ownerDocument.defaultView;this.onChromeUnloadClosure_=BindToObject(
  227. this.onChromeUnload_,this);win.addEventListener("unload",this.onChromeUnloadClosure_,false);this.lastTab_=this.getCurrentBrowser();this.detectNewTabs_()}
  228. G_TabbedBrowserWatcher.events={DOMCONTENTLOADED:"domcontentloaded",LOCATIONCHANGE:"locationchange",PAGESHOW:"pageshow",PAGEHIDE:"pagehide",LOAD:"load",UNLOAD:"unload",TABLOAD:"tabload",TABUNLOAD:"tabunload",TABSWITCH:"tabswitch",TABMOVE:"tabmove"};G_TabbedBrowserWatcher.mark_="watcher-marked";G_TabbedBrowserWatcher.prototype.onChromeUnload_=function(event){G_Debug(this,"Removing event listeners");if(this.tabbox_){this.tabbox_.removeEventListener("DOMContentLoaded",this.onDOMContentLoadedClosure_,
  229. true);this.tabbox_.removeEventListener("DOMNodeInserted",this.onDOMNodeInsertedClosure_,true);this.tabbox_.removeEventListener("select",this.onTabSwitchClosure_,true);var win=this.tabbox_.ownerDocument.defaultView;win.removeEventListener("unload",this.onChromeUnloadClosure_,false);this.tabbox_=null}if(this.lastTab_){this.lastTab_=null}if(this.tabBrowser_){this.tabBrowser_=null}}
  230. ;G_TabbedBrowserWatcher.prototype.isInstrumented_=function(browser){return!(!browser[this.mark_])}
  231. ;G_TabbedBrowserWatcher.prototype.instrumentBrowser_=function(browser){G_Assert(this,!this.isInstrumented_(browser),"Browser already instrumented!");new G_BrowserWatcher(this,browser);browser[this.mark_]=true}
  232. ;G_TabbedBrowserWatcher.prototype.detectNewTabs_=function(){var tb=this.getTabBrowser();for(var i=0;i<tb.browsers.length;++i)this.maybeFireTabLoad(tb.browsers[i])}
  233. ;G_TabbedBrowserWatcher.prototype.registerListener=function(eventType,listener){this.registrar_.registerListener(eventType,listener)}
  234. ;G_TabbedBrowserWatcher.prototype.removeListener=function(eventType,listener){this.registrar_.removeListener(eventType,listener)}
  235. ;G_TabbedBrowserWatcher.prototype.fire=function(eventType,e){this.registrar_.fire(eventType,e)}
  236. ;G_TabbedBrowserWatcher.prototype.fireDocEvent_=function(eventType,doc,browser){if(!this.tabBrowser_){G_Debug(this,"Firing event after shutdown: "+eventType);return}try{var isTop=doc==browser.contentDocument}catch(e){var isTop=undefined}var inSelected=browser==this.getCurrentBrowser();var location=doc?doc.location.href:undefined;if(!this.filterAboutBlank_||location!="about:blank"){G_Debug(this,"firing "+eventType+" for "+location+(isTop?" (isTop)":"")+(inSelected?" (inSelected)":""));this.fire(eventType,
  237. {doc:doc,isTop:isTop,inSelected:inSelected,browser:browser})}}
  238. ;G_TabbedBrowserWatcher.prototype.maybeFireTabLoad=function(browser){if(!this.isInstrumented_(browser)){this.instrumentBrowser_(browser);G_Debug(this,"firing tabload");this.fire(this.events.TABLOAD,{browser:browser})}}
  239. ;G_TabbedBrowserWatcher.prototype.onDOMContentLoaded=function(e){G_Debug(this,"onDOMContentLoaded for a "+e.target);var doc=e.target;var browser=this.getBrowserFromDocument(doc);if(!browser){G_Debug(this,"domcontentloaded: no browser for "+doc.location.href);return}this.maybeFireTabLoad(browser);G_Debug(this,"DOMContentLoaded broken for forward/back buttons.");this.fireDocEvent_(this.events.DOMCONTENTLOADED,doc,browser)}
  240. ;G_TabbedBrowserWatcher.prototype.onDOMNodeInserted=function(e){G_Debug(this,"onDOMNodeInserted for a "+e.target+" related: "+e.relatedNode);if(e.target.localName!="tab"){return}if(!isDef(e.target._tPos)){return}var fromPos=e.target._tPos;var toPos;for(var i=0;i<e.relatedNode.childNodes.length;i++){var child=e.relatedNode.childNodes[i];if(child==e.target){toPos=i;break}}G_Debug(this,"firing tabmove");this.fire(this.events.TABMOVE,{tab:e.target,fromIndex:fromPos,toIndex:toPos})}
  241. ;G_TabbedBrowserWatcher.prototype.onTabSwitch=function(e){if(e.target==null||e.target.localName!="tabs"&&e.target.localName!="tabpanels")return;var fromBrowser=this.lastTab_;var toBrowser=this.getCurrentBrowser();if(fromBrowser!=toBrowser){this.lastTab_=toBrowser;G_Debug(this,"firing tabswitch");this.fire(this.events.TABSWITCH,{fromBrowser:fromBrowser,toBrowser:toBrowser})}}
  242. ;G_TabbedBrowserWatcher.prototype.getTabBrowser=function(){return this.tabBrowser_}
  243. ;G_TabbedBrowserWatcher.prototype.getCurrentBrowser=function(){return this.getTabBrowser().selectedBrowser}
  244. ;G_TabbedBrowserWatcher.prototype.getCurrentWindow=function(){return this.getCurrentBrowser().contentWindow}
  245. ;G_TabbedBrowserWatcher.prototype.getBrowserFromDocument=function(doc){function docInWindow(doc,win){if(win.document==doc)return true;if(win.frames)for(var i=0;i<win.frames.length;i++)if(docInWindow(doc,win.frames[i]))return true;return false}
  246. var browsers=this.getTabBrowser().browsers;for(var i=0;i<browsers.length;i++)if(docInWindow(doc,browsers[i].contentWindow))return browsers[i];return null}
  247. ;G_TabbedBrowserWatcher.prototype.getDocumentFromURL=function(url,opt_browser){function docWithURL(win,url){if(win.document.location.href==url)return win.document;if(win.frames)for(var i=0;i<win.frames.length;i++){var rv=docWithURL(win.frames[i],url);if(rv)return rv}return null}
  248. if(opt_browser)return docWithURL(opt_browser.contentWindow,url);var browsers=this.getTabBrowser().browsers;for(var i=0;i<browsers.length;i++){var rv=docWithURL(browsers[i].contentWindow,url);if(rv)return rv}return null}
  249. ;G_TabbedBrowserWatcher.prototype.getDocumentsFromURL=function(url,opt_browser){var docs=[];function getDocsWithURL(win,url){if(win.document.location.href==url)docs.push(win.document);if(win.frames)for(var i=0;i<win.frames.length;i++)getDocsWithURL(win.frames[i],url)}
  250. if(opt_browser)return getDocsWithURL(opt_browser.contentWindow,url);var browsers=this.getTabBrowser().browsers;for(var i=0;i<browsers.length;i++)getDocsWithURL(browsers[i].contentWindow,url);return docs}
  251. ;G_TabbedBrowserWatcher.prototype.getBrowserFromWindow=function(sub){function containsSubWindow(sub,win){if(win==sub)return true;if(win.frames)for(var i=0;i<win.frames.length;i++)if(containsSubWindow(sub,win.frames[i]))return true;return false}
  252. var browsers=this.getTabBrowser().browsers;for(var i=0;i<browsers.length;i++)if(containsSubWindow(sub,browsers[i].contentWindow))return browsers[i];return null}
  253. ;G_TabbedBrowserWatcher.getTabElementFromBrowser=function(tabBrowser,browser){for(var i=0;i<tabBrowser.browsers.length;i++)if(tabBrowser.browsers[i]==browser)return tabBrowser.mTabContainer.childNodes[i];return null}
  254. ;{G_debugService.loggifier.loggify(G_TabbedBrowserWatcher.prototype)}function G_BrowserWatcher(tabbedBrowserWatcher,browser){this.debugZone="browserwatcher";this.parent_=tabbedBrowserWatcher;this.browser_=browser;this.onPageShowClosure_=BindToObject(this.onPageShow,this);this.browser_.addEventListener("pageshow",this.onPageShowClosure_,true);this.onPageHideClosure_=BindToObject(this.onPageHide,this);this.browser_.addEventListener("pagehide",this.onPageHideClosure_,true);this.onLoadClosure_=BindToObject(
  255. this.onLoad,this);this.browser_.addEventListener("load",this.onLoadClosure_,true);this.onUnloadClosure_=BindToObject(this.onUnload,this);this.browser_.addEventListener("unload",this.onUnloadClosure_,true);this.webProgressListener_={QueryInterface:function(){return this}
  256. ,onLocationChange:bind(this.onLocationChange,this),onStateChange:function(){}
  257. ,onStatusChange:function(){}
  258. ,onSecurityChange:function(){}
  259. ,onProgressChange:function(){}
  260. };G_Debug(this,"adding progress listener");this.browser_.addProgressListener(this.webProgressListener_,Ci.nsIWebProgress.NOTIFY_LOCATION);G_Debug(this,"Done")}
  261. G_BrowserWatcher.prototype.onLocationChange=function(webProgress,request,location){G_Debug(this,"onLocationChange for {%s}".subs(location.spec));if(!this.parent_){G_Debug(this,"onLocationChange after tab close");return}var e={browser:this.browser_,isTop:true};this.parent_.fire(this.parent_.events.LOCATIONCHANGE,e)}
  262. ;G_BrowserWatcher.prototype.onPageShow=function(e){G_Debug(this,"onPageShow for "+(e.target?e.target:"undefined"));if(e.target&&e.target.nodeName=="#document"){var doc=e.target;this.parent_.fireDocEvent_(this.parent_.events.PAGESHOW,doc,this.browser_)}}
  263. ;G_BrowserWatcher.prototype.onLoad=function(e){G_Debug(this,"onLoad for a "+e.target);if(!e.target){G_Debug(this,"e.target is null; canceling onload event");return}if(e.target.nodeName!="#document")return;var doc=e.target;this.parent_.fireDocEvent_(this.parent_.events.LOAD,doc,this.browser_)}
  264. ;G_BrowserWatcher.prototype.onUnload=function(e){G_Debug(this,"onUnload for "+(e.target?e.target:"undefined"));var doc=e.target;if(doc&&doc.nodeName=="#document")this.parent_.fireDocEvent_("unload",doc,this.browser_);if(!doc){G_Debug(this,"firing tabunload for a "+this.browser_+"("+this.browser_.nodename+")");this.parent_.fire(this.parent_.events.TABUNLOAD,{browser:this.browser_});this.browser_.removeEventListener("pageshow",this.onPageShowClosure_,true);this.browser_.removeEventListener("pagehide"
  265. ,this.onPageHideClosure_,true);this.browser_.removeEventListener("load",this.onLoadClosure_,true);this.browser_.removeEventListener("unload",this.onUnloadClosure_,true);this.parent_=null;this.browser_=null;G_Debug(this,"Removed event listeners")}}
  266. ;G_BrowserWatcher.prototype.onPageHide=function(e){G_Debug(this,"onPageHide for a "+e.target+"("+e.target.nodeName+")");if(e.target.nodeName!="#document")return;var doc=e.target;this.parent_.fireDocEvent_(this.parent_.events.PAGEHIDE,doc,this.browser_)}
  267. ;
  268. function G_Base64(){this.byteToCharMap_={};this.charToByteMap_={};this.byteToCharMapWebSafe_={};this.charToByteMapWebSafe_={};this.init_()}
  269. G_Base64.ENCODED_VALS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";G_Base64.ENCODED_VALS_WEBSAFE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";G_Base64.prototype.init_=function(){for(var i=0;i<G_Base64.ENCODED_VALS.length;i++){this.byteToCharMap_[i]=G_Base64.ENCODED_VALS.charAt(i);this.charToByteMap_[this.byteToCharMap_[i]]=i;this.byteToCharMapWebSafe_[i]=G_Base64.ENCODED_VALS_WEBSAFE.charAt(i);this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]]=
  270. i}}
  271. ;G_Base64.prototype.encodeByteArray=function(input,opt_webSafe){if(!(input instanceof Array))throw new Error("encodeByteArray takes an array as a parameter");var byteToCharMap=opt_webSafe?this.byteToCharMapWebSafe_:this.byteToCharMap_;var output=[];var i=0;while(i<input.length){var byte1=input[i];var haveByte2=i+1<input.length;var byte2=haveByte2?input[i+1]:0;var haveByte3=i+2<input.length;var byte3=haveByte3?input[i+2]:0;var outByte1=byte1>>2;var outByte2=(byte1&3)<<4|byte2>>4;var outByte3=(byte2&
  272. 15)<<2|byte3>>6;var outByte4=byte3&63;if(!haveByte3){outByte4=64;if(!haveByte2)outByte3=64}output.push(byteToCharMap[outByte1]);output.push(byteToCharMap[outByte2]);output.push(byteToCharMap[outByte3]);output.push(byteToCharMap[outByte4]);i+=3}return output.join("")}
  273. ;G_Base64.prototype.decodeString=function(input,opt_webSafe){if(input.length%4)throw new Error("Length of b64-encoded data must be zero mod four");var charToByteMap=opt_webSafe?this.charToByteMapWebSafe_:this.charToByteMap_;var output=[];var i=0;while(i<input.length){var byte1=charToByteMap[input.charAt(i)];var byte2=charToByteMap[input.charAt(i+1)];var byte3=charToByteMap[input.charAt(i+2)];var byte4=charToByteMap[input.charAt(i+3)];if(byte1===undefined||byte2===undefined||byte3===undefined||byte4===
  274. undefined)throw new Error("String contains characters not in our alphabet: "+input);var outByte1=byte1<<2|byte2>>4;output.push(outByte1);if(byte3!=64){var outByte2=byte2<<4&240|byte3>>2;output.push(outByte2);if(byte4!=64){var outByte3=byte3<<6&192|byte4;output.push(outByte3)}}i+=4}return output}
  275. ;G_Base64.prototype.arrayifyString=function(str){var output=[];for(var i=0;i<str.length;i++){var c=str.charCodeAt(i);while(c>255){output.push(c&255);c>>=8}output.push(c)}return output}
  276. ;G_Base64.prototype.stringifyArray=function(array){var output=[];for(var i=0;i<array.length;i++)output[i]=String.fromCharCode(array[i]);return output.join("")}
  277. ;
  278. function G_Requester(timeoutMillis){this.status="";this.responseText="";this.timeout_=timeoutMillis?timeoutMillis:10000;this.timeoutExpired_=false}
  279. G_Requester.prototype.Open=function(url,options){G_Debug(this,"Sending Async Req To: %s".subs(url));var channel=Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService).newChannel(url,null,null);channel.QueryInterface(Ci.nsIHttpChannel);if(options.postData){var newData=new Array;for(var i=0;i<options.postData.length;i++){if(options.postData.charCodeAt(i)>128){G_Debug(this,"Fixing %s".subs(options.postData.charCodeAt(i)));newData.push("&#"+options.postData.charCodeAt(i)+";")}else{newData.push(
  280. options.postData.charAt(i))}}newData=newData.join("");var uploadCh=channel.QueryInterface(Ci.nsIUploadChannel);var sis=Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);sis.setData(newData,-1);uploadCh.setUploadStream(sis,"application/xml",-1);channel.requestMethod="POST"}if(isDef(options.username)||isDef(options.password)){var encoder=new G_Base64;var as=encoder.arrayifyString(options.username+":"+options.password);var enc=encoder.encodeByteArray(as);channel.setRequestHeader(
  281. "Authorization","BASIC "+enc,false)}channel.setRequestHeader("Content-Type","application/xml",false);channel.setRequestHeader("Accept-Encoding","compress, gzip",false);channel.setRequestHeader("Connection","close",false);if(options.headers){for(var headerName in options.headers){channel.setRequestHeader(headerName,options.headers[headerName],false)}}channel.asyncOpen(this,null);this.timer_=new G_Alarm(this.Timeout.bind(this),this.timeout_)}
  282. ;G_Requester.prototype.Timeout=function(){G_Debug(this,"Timeout Fired");this.timeoutExpired_=true;this.OnFailure()}
  283. ;G_Requester.prototype.onStartRequest=function(request,context){if(this.timeoutExpired_){return false}this.status=request.QueryInterface(Ci.nsIHttpChannel).responseStatus}
  284. ;G_Requester.prototype.onDataAvailable=function(request,context,inputStream,offset,count){if(this.timeoutExpired_){return false}var sis=Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);sis.init(inputStream);var text=sis.read(count);this.responseText+=text;G_Debug(this,"Streaming: %s".subs(text))}
  285. ;G_Requester.prototype.onStopRequest=function(request,context,status){G_Debug(this,"On Stop Request");if(this.timeoutExpired_){return false}this.timer_.cancel();this.OnSuccess()}
  286. ;G_Requester.prototype.OnSuccess=function(){}
  287. ;G_Requester.prototype.OnFailure=function(){}
  288. ;G_Requester.prototype.debugZone="G_Requester";{G_debugService.loggifier.loggify(G_Requester.prototype)};
  289. function G_ExtensionUpdater(id,requestOptions){if(!id){G_Debug(this,"You need to specify an extension id");return false}this.RDFSvc_=Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService);if(requestOptions){this.requestOptions_=requestOptions}else{this.requestOptions_={}}this.id=id;this.updating=false;this.preferences=new G_Preferences("extensions.google.updater.")}
  290. G_ExtensionUpdater.prototype.Update=function(){if(this.updating){return false}this.updating=true;this.appVersion="";this.appID="";this.currentVersion="";this.updateURL="";this.updateLink="";this.updateVersion="";if(!this.GetCurrent()){this.Failure("'%s' not found in extension manager.".subs(this.name));return false}this.AttemptUpdate()}
  291. ;G_ExtensionUpdater.prototype.UpdatePeriodically=function(opt_makeTimer){var lastUpdate=this.preferences.getPref(this.id,0);var timeBetweenUpdates=86400000;var nextUpdate=Number(lastUpdate)+timeBetweenUpdates;var now=(new Date).getTime();G_Debug(this,"Last update: "+lastUpdate+", next: "+nextUpdate+"\n");if(now>nextUpdate){this.preferences.setPref(this.id,String(now));this.Update();nextUpdate=now+timeBetweenUpdates}if(opt_makeTimer){G_Debug(this,"Setting timer for update in "+(nextUpdate-now)+"ms\n"
  292. );this.loop_=new G_Alarm(this.UpdatePeriodically.bind(this,true),nextUpdate-now,false)}}
  293. ;G_ExtensionUpdater.prototype.CompareVersions=function(aV1,aV2){var v1=aV1.split(".");var v2=aV2.split(".");var numSubversions=v1.length>v2.length?v1.length:v2.length;for(var i=0;i<numSubversions;i++){if(typeof v2[i]=="undefined"){return 1}if(typeof v1[i]=="undefined"){return-1}if(parseInt(v2[i])>parseInt(v1[i])){return-1}else if(parseInt(v2[i])<parseInt(v1[i])){return 1}}return 0}
  294. ;G_ExtensionUpdater.prototype.GetCurrent=function(){var updItem=Cc["@mozilla.org/extensions/manager;1"].getService(Ci.nsIExtensionManager).getItemForID(this.id);if(updItem){var appInfo=Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo);this.name=updItem.name;this.currentVersion=updItem.version;G_Debug(this,updItem.name);G_Debug(this,updItem.version);G_Debug(this,updItem.updateRDF);this.updateURL=updItem.updateRDF;this.updateURL=this.updateURL.replace(/%ITEM_VERSION%/gi,this.currentVersion)
  295. .replace(/%ITEM_ID%/gi,this.id).replace(/%APP_VERSION%/gi,appInfo.version).replace(/%APP_ID%/gi,appInfo.ID);G_Debug(this,this.updateURL);return true}return false}
  296. ;G_ExtensionUpdater.prototype.AttemptUpdate=function(){G_Debug(this,"AttemptUpdate");if(!this.updateURL){return false}this.req_=new G_Requester;this.req_.OnSuccess=this.OnReqSuccess.bind(this);this.req_.OnFailure=this.OnReqFailure.bind(this);this.req_.Open(this.updateURL,this.requestOptions_)}
  297. ;G_ExtensionUpdater.prototype.OnReqFailure=function(){G_Debug(this,"OnReqFailure");this.OnFail()}
  298. ;G_ExtensionUpdater.prototype.OnReqSuccess=function(){G_Debug(this,"OnReqSuccess");if(this.req_.status!=200||!this.req_.responseText.match(/<rdf/gi)){G_Debug(this,"Error: Invalid Update RDF contents. HTTP Status '%s'".subs(this.req_.status));this.OnFail();return false}var uri=Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService).newURI(this.updateURL,null,null);var parser=Cc["@mozilla.org/rdf/xml-parser;1"].createInstance(Ci.nsIRDFXMLParser);var memoryDS=Cc["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"
  299. ].createInstance(Ci.nsIRDFDataSource);parser.parseString(memoryDS,uri,this.req_.responseText);G_Debug(this,"RDF loaded");var moz="http://www.mozilla.org/2004/em-rdf#";var versionArc=this.RDFSvc_.GetResource(moz+"version");var updateLinkArc=this.RDFSvc_.GetResource(moz+"updateLink");var thisResource=null;var dsResources=memoryDS.GetAllResources();G_Debug(this,"Cycling through RDF");while(dsResources.hasMoreElements()){thisResource=dsResources.getNext().QueryInterface(Ci.nsIRDFResource);var versionRes=
  300. memoryDS.GetTarget(thisResource,versionArc,true);if(versionRes){this.updateVersion=versionRes.QueryInterface(Ci.nsIRDFLiteral).Value}var updateLinkRes=memoryDS.GetTarget(thisResource,updateLinkArc,true);if(updateLinkRes){this.updateLink=updateLinkRes.QueryInterface(Ci.nsIRDFLiteral).Value}}if(this.updateVersion&&this.updateLink){G_Debug(this,"currentVersion:%s\nupdateVersion: %s\nupdateLink: %s".subs(this.currentVersion,this.updateVersion,this.updateLink));if(this.CompareVersions(this.updateVersion,
  301. this.currentVersion)==1){G_Debug(this,"Local version is old, now installing update...");this.InstallUpdate()}else{G_Debug(this,"No need to update")}}}
  302. ;G_ExtensionUpdater.prototype.InstallUpdate=function(){if(!this.updateLink){this.Failure("Failure");return false}var manager=Cc["@mozilla.org/xpinstall/install-manager;1"].createInstance(Ci.nsIXPInstallManager);if(manager!=null){G_Debug(this,"UpdateLink: %s".subs(this.updateLink));this.OnUpdateAvailable();var items=[this.updateLink];var p=new G_Preferences;var autoupdate=p.getPref("extensions.google.%s.autoupdate".subs(this.id.split("@")[0]),false);if(autoupdate==false){G_DebugL(this,"Extension '%s' would've been updated"
  303. .subs(this.name));this.Success()}else{G_DebugL(this,"Extension '%s' updating...".subs(this.name));manager.initManagerFromChrome(items,items.length,this)}}else{G_Debug(this,"Error creating manager");this.Failure()}}
  304. ;G_ExtensionUpdater.prototype.onStateChange=function(index,state,value){if(state==Ci.nsIXPIProgressDialog.INSTALL_DONE){G_DebugL(this,"Value: "+value);if(value!=0){G_Debug(this,"Download Error");this.Failure()}else{G_Debug(this,"Success!");this.Success()}}}
  305. ;G_ExtensionUpdater.prototype.onProgress=function(index,value,maxValue){}
  306. ;G_ExtensionUpdater.prototype.Failure=function(aMessage){G_Debug(this,"Failure: %s".subs(aMessage));this.updating=false;this.OnFail(aMessage)}
  307. ;G_ExtensionUpdater.prototype.Success=function(){this.updating=false;this.OnSuccess()}
  308. ;G_ExtensionUpdater.prototype.OnFail=function(aMessage){}
  309. ;G_ExtensionUpdater.prototype.OnSuccess=function(){}
  310. ;G_ExtensionUpdater.prototype.OnUpdateAvailable=function(){}
  311. ;G_ExtensionUpdater.prototype.debugZone="G_ExtensionUpdater";
  312. var G_FirefoxXMLUtils={};G_FirefoxXMLUtils.XSI_NAMESPACE="http://www.w3.org/2001/XMLSchema-instance";G_FirefoxXMLUtils.XMLNS_NAMESPACE="http://www.w3.org/2000/xmlns/";G_FirefoxXMLUtils.XUL_NAMESPACE="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";G_FirefoxXMLUtils.newXML=function(opt_root,opt_namespace,opt_nsMap){if(!this.domImpl_){this.domImpl_=Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser).parseFromString("<foo/>","text/xml").implementation}if(!isDef(opt_root)
  313. ){opt_root=null}if(!isDef(opt_namespace)){opt_namespace=null}var doc=this.domImpl_.createDocument(opt_namespace,opt_root,null);if(opt_nsMap){var root=doc.documentElement;for(var prefix in opt_nsMap){root.setAttributeNS(this.XMLNS_NAMESPACE,"xmlns:"+prefix,opt_nsMap[prefix])}}return doc}
  314. ;G_FirefoxXMLUtils.getXMLString=function(node){return Cc["@mozilla.org/xmlextras/xmlserializer;1"].createInstance(Ci.nsIDOMSerializer).serializeToString(node)}
  315. ;G_FirefoxXMLUtils.loadXML=function(file){var fis=Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);fis.init(file,1,0,0);var doc=Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser).parseFromStream(fis,null,fis.available(),"text/xml");if(doc.documentElement.nodeName=="parsererror"){throw new Error(doc.documentElement.firstChild.nodeValue);}return doc}
  316. ;G_FirefoxXMLUtils.saveXML=function(xml,file){G_FileWriter.writeAll(file,this.getXMLString(xml))}
  317. ;G_FirefoxXMLUtils.selectNodes=function(context,xpath,opt_nsResolver){var doc=context.nodeType==context.DOCUMENT_NODE?context:context.ownerDocument;if(!isDef(opt_nsResolver)){opt_nsResolver=null}return doc.evaluate(xpath,context,opt_nsResolver,Ci.nsIDOMXPathResult.ORDERED_NODE_ITERATOR_TYPE,null)}
  318. ;G_FirefoxXMLUtils.selectSingleNode=function(context,xpath,opt_nsResolver){var doc=context.nodeType==context.DOCUMENT_NODE?context:context.ownerDocument;if(!isDef(opt_nsResolver)){opt_nsResolver=null}return doc.evaluate(xpath,context,opt_nsResolver,Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}
  319. ;G_FirefoxXMLUtils.isNil=function(elm){return elm.getAttributeNS(this.XSI_NAMESPACE,"nil")=="true"}
  320. ;G_FirefoxXMLUtils.setNil=function(elm){elm.setAttributeNS(this.XSI_NAMESPACE,"xsi:nil","true")}
  321. ;
  322. Date.prototype.setISO8601=function(string){var regexp="([0-9]{4})(-([0-9]{2})(-([0-9]{2})(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(.([0-9]+))?)?(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";var d=string.match(new RegExp(regexp));if(!d){throw new Error("Not a valid ISO8601 date: {%s}".subs(string));}var offset=0;var date=new Date(d[1],0,1);if(d[3]){date.setMonth(d[3]-1)}if(d[5]){date.setDate(d[5])}if(d[7]){date.setHours(d[7])}if(d[8]){date.setMinutes(d[8])}if(d[10]){date.setSeconds(d[10])}if(d[12]){date.setMilliseconds(
  323. Number("0."+d[12])*1000)}if(d[14]){offset=Number(d[16])*60+Number(d[17]);offset*=d[15]=="-"?1:-1}offset-=date.getTimezoneOffset();var time=Number(date)+offset*60*1000;this.setTime(Number(time))}
  324. ;Date.prototype.toISO8601String=function(format,offset){if(!format){var format=6}if(!offset){var offset="Z";var date=this}else{var d=offset.match(/([-+])([0-9]{2}):([0-9]{2})/);var offsetnum=Number(d[2])*60+Number(d[3]);offsetnum*=d[1]=="-"?-1:1;var date=new Date(Number(Number(this)+offsetnum*60000))}var zeropad=function(num){return(num<10?"0":"")+num}
  325. ;var str="";str+=date.getUTCFullYear();if(format>1){str+="-"+zeropad(date.getUTCMonth()+1)}if(format>2){str+="-"+zeropad(date.getUTCDate())}if(format>3){str+="T"+zeropad(date.getUTCHours())+":"+zeropad(date.getUTCMinutes())}if(format>5){var secs=Number(date.getUTCSeconds()+"."+(date.getUTCMilliseconds()<100?"0":"")+zeropad(date.getUTCMilliseconds()));str+=":"+zeropad(secs)}else if(format>4){str+=":"+zeropad(date.getUTCSeconds())}if(format>3){str+=offset}return str}
  326. ;
  327. function CLB_Application(){this.initialized_=false;this.originalHandlers_=[];this.obsSvc_=Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);this.catMan_=Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);this.promptSvc_=Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);this.extMan_=Cc["@mozilla.org/extensions/manager;1"].getService(Ci.nsIExtensionManager);this.rdfSvc_=Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService)
  328. ;this.startSeq_=new CLB_StartupSequence;this.prefs=new G_Preferences("extensions.browserstate.");this.googPrefs=new G_Preferences("extensions.google.browserstate.");this.debugPrefs=new G_Preferences("google-debug-service.");this.browserPrefs=new G_Preferences("browser.");this.bmSyncer=new CLB_BookmarkSyncer;CLB_syncMan.registerComponent(this.bmSyncer);this.tabSyncer=new CLB_TabSyncer;CLB_syncMan.registerComponent(this.tabSyncer);this.settingsSyncer=new CLB_SettingsSyncer;CLB_syncMan.registerComponent(
  329. this.settingsSyncer);this.passwordSyncer=new CLB_PasswordSyncer;CLB_syncMan.registerComponent(this.passwordSyncer);this.cookieSyncer=new CLB_CookieSyncer;CLB_syncMan.registerComponent(this.cookieSyncer);this.historySyncer=new CLB_HistorySyncer;CLB_syncMan.registerComponent(this.historySyncer);this.prefSvc_=Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);this.appInfo_=Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).QueryInterface(Ci.nsIXULRuntime);this.updater_=
  330. null;this.updateLoop_=null;this.uninstalled_=false;this.errorURL=null;this.errorURLShown=false;this.reconnectTime_=0;this.uniqueCount_=0;this.base64r=new G_Base64;this.statusObservers_=[]}
  331. CLB_Application.STATUS_ONLINE=0;CLB_Application.STATUS_OFFLINE=1;CLB_Application.STATUS_KICKED=2;CLB_Application.STATUS_UPDATE_ERROR=3;CLB_Application.STATUS_NEEDS_CAPTCHA=4;CLB_Application.STATUS_PING_REDIRECT=5;CLB_Application.STATUS_BACKED_OFF=6;CLB_Application.PROGRESS_UNOFFLINING="Processing offline changes...";CLB_Application.PROGRESS_GATHERING="Gathering local changes...";CLB_Application.PROGRESS_INDEXING="Preparing conflict resolution rules...";CLB_Application.PROGRESS_DOWNLOADING="Downloading server changes..."
  332. ;CLB_Application.PROGRESS_PARSING="Processing server changes...";CLB_Application.PROGRESS_RESOLVING="Applying conflict resolution rules...";CLB_Application.PROGRESS_PREPARING="Preparing server update...";CLB_Application.PROGRESS_UPDATING="Updating server...";CLB_Application.PROGRESS_APPLYING="Updating browser...";CLB_Application.MESSAGE_WORKING_OFFLINE="Google Browser Sync will not run while you are working offline.";CLB_Application.MESSAGE_BACKED_OFF="The Google Browser Sync server has requested that you stay offline for a period of time, please try again later."
  333. ;CLB_Application.HTTP_STATUS_FORBIDDEN=403;CLB_Application.HTTP_STATUS_UNAVAILABLE=503;CLB_Application.ERROR_INVALID_PIN="Invalid token.";CLB_Application.MESSAGE_INVALID_PIN="Your PIN was incorrect, please try again";CLB_Application.ERROR_SINGLE_UPLOAD_LIMIT="Update exceeds single upload limit.";CLB_Application.MESSAGE_SINGLE_UPLOAD_LIMIT="You have too much stuff, please try disabling some components and trying again.";CLB_Application.ERROR_DAILY_UPLOAD_LIMIT="Daily upload quota exceeded.";CLB_Application.MESSAGE_DAILY_UPLOAD_LIMIT=
  334. "You've uploaded too much stuff today, please try again tomorrow.";CLB_Application.ERROR_PIN_LIMIT="Too many invalid PINs provided.";CLB_Application.MESSAGE_PIN_LIMIT="PIN authentication has failed too many times.";CLB_Application.ERROR_SERVER_UNAVAILABLE="Server unavailable.";CLB_Application.MESSAGE_SERVER_UNAVAILABLE="The Google Browser Sync server was unavailable.";CLB_Application.MESSAGE_UNKNOWN="An unknown error has occured while trying to contact the server.";CLB_Application.CIPHER_DISCARD_BYTES=
  335. 1536;CLB_Application.MAX_LOG_AGE=172800000;CLB_Application.LOG_ROTATE_INTERVAL=86400000;CLB_Application.UPDATE_CYCLE=86400000;CLB_Application.RECONNECT_MAX_TIME=600000;CLB_Application.CONFLICTING_EXTENSIONS=["{909409b9-2e3b-4682-a5d1-71ca80a76456}","foxmarks@kei.com"];CLB_Application.prototype.debugZone="CLB_Application";CLB_Application.prototype.isKickError=function(code,status,message){if(code==CLB_Application.HTTP_STATUS_FORBIDDEN&&message=="Invalid mid."){return true}else{return false}}
  336. ;CLB_Application.prototype.handleServerError=function(code,status,opt_message){if(!opt_message){return}var message=opt_message.split("\n");if(message.length>1&&message[1].indexOf("BACKOFF=")==0){var seconds=parseInt(message[1].split("=")[1]);CLB_app.backOff(seconds*1000)}G_DebugL(this,"Server Error: code: %s, message: %s".subs(code,opt_message));if(code==CLB_Application.HTTP_STATUS_FORBIDDEN){switch(message[0]){case CLB_Application.ERROR_SINGLE_UPLOAD_LIMIT:return CLB_Application.MESSAGE_SINGLE_UPLOAD_LIMIT;
  337. case CLB_Application.ERROR_DAILY_UPLOAD_LIMIT:return CLB_Application.MESSAGE_DAILY_UPLOAD_LIMIT;case CLB_Application.ERROR_PIN_LIMIT:return CLB_Application.MESSAGE_PIN_LIMIT}}else if(code==CLB_Application.HTTP_STATUS_UNAVAILABLE){switch(message[0]){case CLB_Application.ERROR_SERVER_UNAVAILABLE:return CLB_Application.MESSAGE_SERVER_UNAVAILABLE}}}
  338. ;CLB_Application.prototype.isGAIATimeoutError=function(code,status,message){if(code==CLB_Application.HTTP_STATUS_FORBIDDEN&&message=="Invalid SID cookie."||message=="Need to refresh SID cookie."){return true}else{return false}}
  339. ;CLB_Application.prototype.isInvalidKeyError=function(code,status,message){if(code==CLB_Application.HTTP_STATUS_FORBIDDEN&&message=="Invalid key."){return true}else{return false}}
  340. ;CLB_Application.prototype.isInvalidUserError=function(code,status,message){if(code==CLB_Application.HTTP_STATUS_FORBIDDEN&&message=="Account does not exist for this user."){return true}else{return false}}
  341. ;CLB_Application.prototype.getMID=function(){return this.prefs.getPref("MID")}
  342. ;CLB_Application.prototype.setMID=function(val){this.maybeSetPref_("MID",val)}
  343. ;CLB_Application.prototype.getSID=function(){return this.prefs.getPref("SID")}
  344. ;CLB_Application.prototype.setSID=function(val){this.maybeSetPref_("SID",val)}
  345. ;CLB_Application.prototype.getUsername=function(){return this.prefs.getPref("username")}
  346. ;CLB_Application.prototype.setUsername=function(val){this.maybeSetPref_("username",val)}
  347. ;CLB_Application.prototype.getKey=function(){return this.prefs.getPref("key")}
  348. ;CLB_Application.prototype.setKey=function(val){this.maybeSetPref_("key",val)}
  349. ;CLB_Application.prototype.getEncryptedKey=function(){return this.prefs.getPref("encryptedKey")}
  350. ;CLB_Application.prototype.setEncryptedKey=function(val){this.maybeSetPref_("encryptedKey",val)}
  351. ;CLB_Application.prototype.getToken=function(){var blindToken=CLB_app.prefs.getPref("blindToken");var token=CLB_app.prefs.getPref("token");if(!blindToken&&token){this.setToken(token);this.maybeSetPref_("token","");return this.getToken()}else{var encoder=new G_Base64;return encoder.stringifyArray(encoder.decodeString(blindToken))}}
  352. ;CLB_Application.prototype.setToken=function(str){var encoder=new G_Base64;this.maybeSetPref_("blindToken",encoder.encodeByteArray(encoder.arrayifyString(str)))}
  353. ;CLB_Application.prototype.savePrefs=function(){this.prefSvc_.savePrefFile(null)}
  354. ;CLB_Application.prototype.setupIsComplete=function(){return Boolean(this.getSID()&&this.getKey()&&this.getMID()&&this.getToken())}
  355. ;CLB_Application.prototype.isBackedOff=function(){return this.getStatus()==CLB_Application.STATUS_BACKED_OFF||(new Date).valueOf()<this.prefs.getPref("backoff",0)}
  356. ;CLB_Application.prototype.canReconnect=function(){if(this.isBackedOff()){return false}else{return new Date<this.reconnectTime_}}
  357. ;CLB_Application.prototype.backOff=function(time){var backoffTime=(new Date).valueOf()+time;this.prefs.setPref("backoff",String(backoffTime));this.reconnectTime_=backoffTime+CLB_Application.RECONNECT_MAX_TIME;CLB_app.setStatus(CLB_Application.STATUS_BACKED_OFF)}
  358. ;CLB_Application.prototype.canSend=function(){var status=this.getStatus();if(!isDef(status)){return true}else if(status==CLB_Application.STATUS_ONLINE){return true}else if(status==CLB_Application.STATUS_UPDATE_ERROR){if(this.canReconnect()){return true}else{return false}}return false}
  359. ;CLB_Application.prototype.setStatus=function(statusCode){if(statusCode==CLB_Application.STATUS_UPDATE_ERROR&&this.getStatus()!=CLB_Application.STATUS_UPDATE_ERROR){G_Debug(this,"Setting reconnect time");this.reconnectTime_=(new Date).valueOf()+CLB_Application.RECONNECT_MAX_TIME}this.prefs.setPref("status",statusCode)}
  360. ;CLB_Application.prototype.getStatus=function(){return this.prefs.getPref("status")}
  361. ;CLB_Application.prototype.getVersion=function(){if(!this.version_){var item=this.extMan_.getItemForID("browserstate@google.com");this.version_=item.version}return this.version_}
  362. ;CLB_Application.prototype.isLinux=function(){return this.appInfo_.OS=="Linux"}
  363. ;CLB_Application.prototype.isMac=function(){return this.isMac_}
  364. ;CLB_Application.prototype.handleStatusChange_=function(){for(var i=0,obs;obs=this.statusObservers_[i];i++){obs()}}
  365. ;CLB_Application.prototype.addStatusObserver=function(observer){G_Debug(this,"Adding status observer...");if(this.statusObservers_.indexOf(observer)>-1){G_DebugL(this,"Status observer already exists! Skipping...");return}this.statusObservers_.push(observer);G_Debug(this,"Done.")}
  366. ;CLB_Application.prototype.removeStatusObserver=function(observer){G_Debug(this,"Removing status observer...");var idx=this.statusObservers_.indexOf(observer);if(idx==-1){G_DebugL(this,"Could not find observer! Skipping.");return}this.statusObservers_.splice(idx,1);G_Debug(this,"Done.")}
  367. ;CLB_Application.prototype.setListPref=function(prefName,list){var escaped=new Array(list.length);for(var i=0;i<list.length;i++){escaped[i]=escape(list[i]);G_Debug(this,"Adding '%s'".subs(escaped[i]))}this.prefs.setPref(prefName,escaped.join(","))}
  368. ;CLB_Application.prototype.deleteUserSettings=function(){this.prefs.clearPref("SID");this.prefs.clearPref("MID");this.prefs.clearPref("key");this.prefs.clearPref("encryptedKey");this.prefs.clearPref("token");this.prefs.clearPref("blindToken");this.prefs.clearPref("username");this.prefs.clearPref("lastUpdate");this.prefs.clearPref("lastSync");this.prefs.clearPref("encryptedComponents");this.prefs.clearPref("syncedComponents");this.prefs.clearPref("hasOfflineData");this.prefs.clearPref("reimport");
  369. this.prefs.clearPref("status");this.prefs.clearPref("showWelcome");this.prefs.clearPref("reimportPasswords");var reimportPrefNames=this.prefs.getChildNames(CLB_SyncManager.REIMPORT_PREF_PREFIX);for(var i=0,name;name=reimportPrefNames[i];i++){this.prefs.clearPref(name)}}
  370. ;CLB_Application.prototype.autoupdate=function(){var p=new G_Preferences;if(!p.getPref("extensions.google.browserstate.autoupdate",false)){G_DebugL(this,"Browser not set to autoupdate, skipping.");return}this.updater_=new G_ExtensionUpdater("browserstate@google.com");this.updater_.Update();if(!this.updateLoop_){this.updateLoop_=new G_Alarm(this.autoupdate.bind(this),CLB_Application.UPDATE_CYCLE,true)}}
  371. ;CLB_Application.prototype.handleUpdateSuccess_=function(){this.updateLoop_.cancel();this.promptSvc_.alert(null,"Google Browser Sync update complete","Google Browser Sync has successfully updated itself. Please restart Firefox to finish installing the update.")}
  372. ;CLB_Application.prototype.getListPref=function(prefName){var list=this.prefs.getPref(prefName,"");if(list==""){list=[]}else{list=list.split(",");for(var i=0;i<list.length;i++){list[i]=unescape(list[i])}}return list}
  373. ;CLB_Application.prototype.maybeSetPref_=function(name,val){if(val){this.prefs.setPref(name,val)}else{this.prefs.clearPref(name)}}
  374. ;CLB_Application.prototype.defaultDebugPref_=function(name,val){if(!isDef(this.debugPrefs.getPref(name))){this.debugPrefs.setPref(name,val)}}
  375. ;CLB_Application.prototype.setDebugPref_=function(prefs,name,debVal,releaseVal){if(typeof prefs.getPref(name)=="undefined"){prefs.setPref(name,releaseVal)}}
  376. ;CLB_Application.prototype.handle=function(cmdLine){if(this.initialized_){return}this.initialized_=true;this.cmdLine_=cmdLine;var handlersEnum=this.catMan_.enumerateCategory("command-line-handler");while(handlersEnum.hasMoreElements()){var entry=handlersEnum.getNext().QueryInterface(Ci.nsISupportsCString).data;var value=this.catMan_.getCategoryEntry("command-line-handler",entry);this.originalHandlers_.push({entry:entry,value:value})}this.catMan_.deleteCategory("command-line-handler");this.start()
  377. }
  378. ;CLB_Application.prototype.observe=function(subject,topic,data){if(topic=="quit-application"){this.handleApplicationQuit()}else if(topic=="em-action-requested"&&data=="item-uninstalled"){var updateItem=subject.QueryInterface(Ci.nsISupports).QueryInterface(Ci.nsIUpdateItem);if(updateItem.id=="browserstate@google.com"){G_DebugL(this,"Google Browser Sync is being uninstalled.");this.uninstalled_=true}}else{throw new Error("Caught unexpected topic {"+topic+"}.");}}
  379. ;CLB_Application.prototype.start=function(){this.initializeLog();new G_Alarm(this.rotateLogs.bind(this),this.prefs.getPref("log-rotate-interval",CLB_Application.LOG_ROTATE_INTERVAL),true);this.setDebugPref_(this.googPrefs,"autoupdate",false,true);this.setDebugPref_(this.debugPrefs,"alsologtoshell",true,false);this.setDebugPref_(this.prefs,"log-xml",true,false);CLB_app.prefs.clearPref("status");this.maybeRunUnitTests();this.prefs.addObserver("status",this.handleStatusChange_.bind(this));this.startSeq_.start(
  380. this.handleStartupSequenceSuccess.bind(this),this.handleStartupSequenceFailure.bind(this));this.isMac_=Cc["@mozilla.org/appshell/appShellService;1"].getService(Ci.nsIAppShellService).hiddenDOMWindow.navigator.platform.substring(0,3).toLowerCase()=="mac"}
  381. ;CLB_Application.prototype.handleStartupSequenceSuccess=function(){this.setStatus(CLB_Application.STATUS_ONLINE);CLB_syncMan.start();this.startBrowser();this.obsSvc_.addObserver(this,"quit-application",false);this.obsSvc_.addObserver(this,"em-action-requested",false)}
  382. ;CLB_Application.prototype.handleStartupSequenceFailure=function(){G_Debug(this,"Unsuccessful start sequence... not starting syncmanager");if(!isDef(this.getStatus())){this.setStatus(CLB_Application.STATUS_OFFLINE)}if(this.getSID()){CLB_syncMan.start()}this.startBrowser();this.obsSvc_.addObserver(this,"quit-application",false);this.obsSvc_.addObserver(this,"em-action-requested",false)}
  383. ;CLB_Application.prototype.handleApplicationQuit=function(){if(CLB_app.getSID()){this.obsSvc_.removeObserver(this,"quit-application");if((CLB_syncMan.checkPending()||CLB_syncMan.checkSending())&&!CLB_app.browserPrefs.getPref("offline",false)){Cc["@mozilla.org/embedcomp/window-watcher;1"].getService(Ci.nsIWindowWatcher).openWindow(null,"chrome://browserstate/content/updating.xul","browserstate-updating","modal,centerscreen,chrome",null)}else{G_Debug(this,"Skipping final update because there is nothing pending."
  384. )}}if(!this.uninstalled_){this.cleanUpLogs()}else{CLB_syncMan.stopSyncedComponents();var prefsToDelete=this.prefs.getChildNames();for(var i=0,name;name=prefsToDelete[i];i++){this.prefs.clearPref(name)}this.googPrefs.clearPref("autoupdate");this.obsSvc_.removeObserver(this,"em-action-requested");G_debugService.disableLogFile();try{CLB_Updater.getOfflineFile().remove(false)}catch(e){G_DebugL(this,"ERROR deleting offline file: %s".subs(e.toString()))}try{this.logFolder_.remove(true)}catch(e){G_DebugL(
  385. this,"ERROR deleting log folder: %s".subs(e.toString()))}this.logFolder_=null}}
  386. ;CLB_Application.prototype.detectConflicts=function(){G_Debug(this,"Looking for conflicting extensions...");for(var i in CLB_Application.CONFLICTING_EXTENSIONS){var extID=CLB_Application.CONFLICTING_EXTENSIONS[i];var extItem=this.extMan_.getItemForID(extID);if(extItem&&extItem.name){G_Debug(this,"{%s} conflicts. Checking whether disabled.".subs(extID));if(!this.extensionIsDisabled(extID)){G_Debug(this,"Asking user...");var msg="You have '%s' installed - it may conflict with Google Browser Sync. Disable it?"
  387. .subs(extItem.name);var res=this.promptSvc_.confirm(this.win,"Conflicting Extension",msg);if(res){G_Debug(this,"User has cancelled install because of conflicting extension.");this.extMan_.disableItem(extID);this.logOff();return true}else{G_Debug(this,"User is going for it. Booya.")}}}}return false}
  388. ;CLB_Application.prototype.extensionIsDisabled=function(id){var ns="http://www.mozilla.org/2004/em-rdf#";var thisApi=this.rdfSvc_.GetResource("urn:mozilla:item:"+id);var is=this.rdfSvc_.GetResource(ns+"userDisabled");var so=this.rdfSvc_.GetResource(ns+"appDisabled");var stupid=this.rdfSvc_.GetLiteral("true");var truthVal=true;return this.extMan_.datasource.HasAssertion(thisApi,is,so,truthVal)||this.extMan_.datasource.HasAssertion(thisApi,is,stupid,truthVal)}
  389. ;CLB_Application.prototype.startBrowser=function(){G_Debug(this,"Calling original handlers...");this.originalHandlers_.forEach(function(entryData){this.catMan_.addCategoryEntry("command-line-handler",entryData.entry,entryData.value,false,false)}
  390. ,this);this.originalHandlers_.forEach(function(entryData){G_Debug(this,"  %s: %s".subs(entryData.entry,entryData.value));var handler=Cc[entryData.value].getService(Ci.nsICommandLineHandler);try{G_Debug(this,"telling "+handler+" to handle");handler.handle(this.cmdLine_)}catch(e){if(e==Components.results.NS_ERROR_ABORT){throw e;}else{G_Debug(this,"Swallowing error {%s}".subs(e))}}}
  391. ,this);CLB_app.autoupdate();G_Debug(this,"Done.")}
  392. ;CLB_Application.prototype.logOff=function(){Cc["@mozilla.org/toolkit/app-startup;1"].getService(Ci.nsIAppStartup).quit(Ci.nsIAppStartup.eRestart|Ci.nsIAppStartup.eForceQuit)}
  393. ;CLB_Application.prototype.cleanUpLogs=function(){G_Debug(this,"Clearing old log files...");var files=this.logFolder_.directoryEntries;var startTime=(new Date).getTime();var maxLogAge=this.prefs.getPref("max-log-age",CLB_Application.MAX_LOG_AGE);var clearDate=(new Date).getTime()-maxLogAge;var file;while(files.hasMoreElements()){file=files.getNext().QueryInterface(Ci.nsILocalFile);if(file.lastModifiedTime<=clearDate){G_Debug(this,"Removing old log file: {%s}".subs(file.leafName));try{file.remove(
  394. false)}catch(e){G_DebugL(this,"ERROR: Could not delete log file: "+"{%s},\nMessage: %s".subs(file.leafName,e.toString()))}}}G_Debug(this,"Success.")}
  395. ;CLB_Application.prototype.rotateLogs=function(){G_Debug(this,"Rotating log files...");this.cleanUpLogs();this.initializeLog()}
  396. ;CLB_Application.prototype.initializeLog=function(){var now=new Date;function pad(number,digits){var ret=number.toString();var diff=digits-ret.length;for(var i=0;i<diff;i++){ret="0"+ret}return ret}
  397. var logFileName="log-%s%s%s-%s%s%s-%s.txt".subs(now.getFullYear(),pad(now.getMonth()+1,2),pad(now.getDate(),2),pad(now.getHours(),2),pad(now.getMinutes(),2),pad(now.getSeconds(),2),pad(now.getMilliseconds(),3));try{this.logFolder_=G_File.getProfileFile("browserstate-logs");if(!this.logFolder_.exists()){this.logFolder_.create(Ci.nsIFile.DIRECTORY_TYPE,this.logFolder_.parent.permissions)}var logFile=this.logFolder_.clone();logFile.append(logFileName);G_debugService.autoLoggify=false;G_debugService.setLogFile(
  398. logFile);G_debugService.enableLogFile();G_debugService.setLogFileErrorLevel(G_DebugService.ERROR_LEVEL_INFO);this.defaultDebugPref_("enableallzones",true);this.defaultDebugPref_("trace-function-calls",false);this.logHeader()}catch(e){G_DebugL(this,"ERROR: Error initializing log: "+e)}}
  399. ;CLB_Application.prototype.logHeader=function(){G_debugService.dump(G_File.LINE_END_CHAR+"=========================================================="+G_File.LINE_END_CHAR);G_debugService.dump("Google Browser Sync starting up..."+G_File.LINE_END_CHAR+"Version: "+this.getVersion()+G_File.LINE_END_CHAR+"Date: "+(new Date).toLocaleString()+G_File.LINE_END_CHAR);G_debugService.dump("=========================================================="+G_File.LINE_END_CHAR+G_File.LINE_END_CHAR)}
  400. ;CLB_Application.prototype.getUniqueTempFile=function(baseName,extension){var file=this.logFolder_.clone();file.append("%s-%s-%s.%s".subs(baseName,(new Date).getTime(),this.uniqueCount_++,extension));return file}
  401. ;CLB_Application.prototype.maybeRunUnitTests=function(){}
  402. ;G_debugService.loggifier.loggify(CLB_Application.prototype,"getToken","setToken","getEncryptedKey","setEncryptedKey","getKey","setKey","getSID","setSID","maybeSetPref_");
  403. function CLB_ArrayEnumerator(aItems){this._index=0;this._contents=aItems}
  404. CLB_ArrayEnumerator.prototype={debugZone:"CLB_ArrayEnumerator",QueryInterface:function(iid){if(iid.equals(Ci.nsISupports)||iid.equals(Ci.nsISimpleEnumerator)){return this}else{throw Components.results.NS_ERROR_NO_INTERFACE;}}
  405. ,hasMoreElements:function(){return this._index<this._contents.length}
  406. ,getNext:function(){return this._contents[this._index++]}
  407. };CLB_ArrayEnumerator.prototype.__defineGetter__("numItems",function(){return this._contents.length}
  408. );
  409. function CLB_BadCertListener(){}
  410. CLB_BadCertListener.prototype.QueryInterface=function(iid){if(iid.equals(Ci.nsIBadCertListener)||iid.equals(Ci.nsIInterfaceRequestor)||iid.equals(Ci.nsISupports)){return this}throw Components.results.NS_ERROR_NO_INTERFACE;}
  411. ;CLB_BadCertListener.prototype.getInterface=function(iid){if(iid.equals(Ci.nsIBadCertListener)){return this}Components.returnCode=Components.results.NS_ERROR_NO_INTERFACE;return null}
  412. ;CLB_BadCertListener.prototype.confirmUnknownIssuer=function(){return false}
  413. ;CLB_BadCertListener.prototype.confirmCertExpired=function(){return false}
  414. ;CLB_BadCertListener.prototype.notifyCrlNextupdate=function(){}
  415. ;CLB_BadCertListener.prototype.confirmMismatchDomain=function(socketInfo,targetURL,cert){if(cert.commonName=="www.google.com"){return true}return false}
  416. ;
  417. function CLB_BookmarkEnumerator(bmEnumerator){this.bmEnumerator_=bmEnumerator;this.nextBookmarkItem_=null;this.advanceToValidBookmark()}
  418. CLB_BookmarkEnumerator.prototype.debugZone="CLB_BookmarkEnumerator";CLB_BookmarkEnumerator.prototype.QueryInterface=function(iid){if(iid.equals(Ci.nsISupports)||iid.equals(Ci.nsISimpleEnumerator)){return this}else{throw Components.results.NS_ERROR_NO_INTERFACE;}}
  419. ;CLB_BookmarkEnumerator.prototype.hasMoreElements=function(){return this.nextBookmarkItem_!=null}
  420. ;CLB_BookmarkEnumerator.prototype.getNext=function(){var next=this.nextBookmarkItem_;this.advanceToValidBookmark();return next}
  421. ;CLB_BookmarkEnumerator.prototype.advanceToValidBookmark=function(){this.nextBookmarkItem_=null;while(this.bmEnumerator_.hasMoreElements()){var candidate=this.bmEnumerator_.getNext();if(!CLB_app.bmSyncer.shouldUpdateGivenTarget(candidate)){continue}var item=CLB_app.bmSyncer.fillBookmarkItem(candidate);this.nextBookmarkItem_=item;break}}
  422. ;G_debugService.loggifier.loggify(CLB_BookmarkEnumerator.prototype);
  423. function CLB_BookmarkResolver(){this.folders_={}}
  424. CLB_BookmarkResolver.folderPathSeparator="/";CLB_BookmarkResolver.oldToolbarName="Personal Toolbar Folder";CLB_BookmarkResolver.newToolbarName="Bookmarks Toolbar Folder";CLB_BookmarkResolver.prototype.clear=function(){this.folders_={}}
  425. ;CLB_BookmarkResolver.prototype.addDownloadedItem=function(item){var parent,pos;if(!item.isRemove){parent=CLB_app.bmSyncer.getParent(item);pos=CLB_app.bmSyncer.getPosition(item)}else{var bmNode;if(item.typeID=="separator"){bmNode=CLB_app.bmSyncer.getSeparatorResource(item.itemID)}else{bmNode=CLB_app.bmSyncer.bmRdfServ.GetResource(item.itemID)}if(!bmNode){G_Debug(this,"Warning, could not form resource from item "+item.itemID+", skipping");return}if(!CLB_app.bmSyncer.bmServ.isBookmarkedResource(bmNode)
  426. ){G_Debug(this,"Warning: bogus isRemove sent from the server  with itemID "+item.itemID);return}var parentNode=CLB_app.bmSyncer.bmServ.getParent(bmNode);var container=Cc["@mozilla.org/rdf/container;1"].getService(Ci.nsIRDFContainer);container.Init(CLB_app.bmSyncer.bmDS,parentNode);parent=CLB_rdf.getValueFromNode(parentNode);pos=container.IndexOf(bmNode)}if(!parent||!pos){G_Debug(this,"Error: every bookmark item should contain a parent and  position - perhaps this is old data?");return}var parentFolder=
  427. this.getFolder(parent);if(item.isRemove){parentFolder.removeBookmark(item.itemID)}else{parentFolder.addBookmark(item.itemID,item.typeID,pos)}if(!item.isRemove&&item.typeID=="folder"){var folder=this.getFolder(item.itemID);var folderParent=CLB_app.bmSyncer.getParent(item);folder.setParent(folderParent);var nameProperty=CLB_app.bmSyncer.propertiesToCollect_.getKey(CLB_BookmarkSyncer.nameRdfStr);if(item.hasProperty(nameProperty)){var folderName=item.getProperty(nameProperty);folder.setName(folderName)
  428. }}}
  429. ;CLB_BookmarkResolver.prototype.getFolder=function(parent){var folder=this.folders_[parent];if(!isDef(folder)){folder=new CLB_Folder(parent);this.folders_[parent]=folder}return folder}
  430. ;CLB_BookmarkResolver.prototype.shiftItems=function(folderID,startPosition,shiftDown){var folder=this.getFolder(folderID);var foundItemAtStartPosition=false;var shiftedItems=[];for(var bm in folder.contents_){var currentBmPosition=folder.getBookmarkPosition(bm);var typeID=folder.getBookmarkTypeID(bm);if(currentBmPosition==parseInt(startPosition)){foundItemAtStartPosition=true;if(shiftDown){return[]}}if(currentBmPosition>=parseInt(startPosition)){var newBmPosition;if(shiftDown){newBmPosition=currentBmPosition-
  431. 1}else{newBmPosition=currentBmPosition+1}var itemID;if(typeID=="separator"){var separatorDeleteItem=new CLB_SyncItem({componentID:CLB_app.bmSyncer.componentID,typeID:typeID,itemID:bm,isRemove:true,properties:{}});shiftedItems.push(separatorDeleteItem);itemID=CLB_app.bmSyncer.createSeparatorID(folderID,newBmPosition)}else{itemID=bm}var item=new CLB_SyncItem({componentID:CLB_app.bmSyncer.componentID,typeID:typeID,itemID:itemID,properties:{parents:folderID,positions:newBmPosition}});shiftedItems.push(
  432. item)}}if(!shiftDown&&!foundItemAtStartPosition){return[]}shiftedItems.forEach(function(shiftedItem){if(shiftedItem.isRemove){folder.removeBookmark(shiftedItem.itemID)}else{this.addItemToFolder(shiftedItem,false)}}
  433. ,this);return shiftedItems}
  434. ;CLB_BookmarkResolver.prototype.removeItemFromFolder=function(item,shiftItems){if(item.isRemove){G_Debug(this,"Error: removeItemFromFolder should never be called  with an isRemove item because these items don't contain  parent and position info.");return}var parent=CLB_app.bmSyncer.getParent(item);var positionToInsert=CLB_app.bmSyncer.getPosition(item);var folder=this.getFolder(parent);folder.removeBookmark(item.itemID);var shiftedItems;if(!shiftItems){shiftedItems=[]}else{shiftedItems=this.shiftItems(
  435. parent,positionToInsert,true)}return shiftedItems}
  436. ;CLB_BookmarkResolver.prototype.addItemToFolder=function(item,shiftItems){if(item.isRemove){G_Debug(this,"Error: addItemToFolder should never be called  with an isRemove item because these items don't contain  parent and position info.");return}var parent=CLB_app.bmSyncer.getParent(item);var positionToInsert=CLB_app.bmSyncer.getPosition(item);var folder=this.getFolder(parent);folder.removeBookmark(item.itemID);var shiftedItems;if(!shiftItems){shiftedItems=[]}else{shiftedItems=this.shiftItems(parent,
  437. positionToInsert,false)}folder.addBookmark(item.itemID,item.typeID,positionToInsert);return shiftedItems}
  438. ;CLB_BookmarkResolver.prototype.getParentPath=function(id){var path="";var currentParent=id;do{var nextParent=null;if(isDef(this.folders_[currentParent])){nextParent=this.folders_[currentParent].getParent()}if(nextParent==null){var bmNode=CLB_app.bmSyncer.bmRdfServ.GetResource(currentParent);var nextParentNode=CLB_app.bmSyncer.bmServ.getParent(bmNode);if(!nextParentNode){G_Debug(this,"Error: Tried to get parent for folder "+currentParent+" but it did not exist in the local store");return null}nextParent=
  439. CLB_rdf.getValueFromNode(nextParentNode)}var folderName=null;if(isDef(this.folders_[nextParent])){folderName=this.folders_[nextParent].getName()}if(folderName==null){var nextParentNode=CLB_app.bmSyncer.bmRdfServ.GetResource(nextParent);var nameArc=CLB_app.bmSyncer.bmRdfServ.GetResource(CLB_BookmarkSyncer.nameRdfStr);var tar=CLB_app.bmSyncer.bmDS.GetTarget(nextParentNode,nameArc,true);if(!tar){G_Debug(this,"Error: Tried to get name for folder "+nextParent+" but it did not exist in the local store"
  440. );return null}folderName=CLB_rdf.getValueFromNode(tar)}path=encodeURIComponent(folderName)+CLB_BookmarkResolver.folderPathSeparator+path;currentParent=nextParent}while(currentParent!=CLB_BookmarkSyncer.rootRdfStr);return path}
  441. ;CLB_BookmarkResolver.prototype.resolveFolderNameConflict=function(oldItem,newItem){if(oldItem.typeID!="folder"&&newItem.typeID!="folder"){G_Debug(this,"Error: trying to resolve a folder name conflict  for non folders - how did we get here?");return[]}var path1=this.getParentPath(oldItem.itemID);var path2=this.getParentPath(newItem.itemID);if(isNull(path1)||isNull(path2)||path1!=path2){return[]}return this.mergeFolders(oldItem,newItem)}
  442. ;CLB_BookmarkResolver.prototype.mergeFolders=function(oldFolder,newFolder){var resolvedItems=this.removeItemFromFolder(oldFolder,true);var folder=this.getFolder(oldFolder.itemID);var parent=newFolder.itemID;for(var id in folder.contents_){var position=folder.getBookmarkPosition(id);var typeID=folder.getBookmarkTypeID(id);var itemID;if(typeID=="separator"){var separatorDeleteItem=new CLB_SyncItem({componentID:CLB_app.bmSyncer.componentID,typeID:typeID,itemID:id,isRemove:true,properties:{}});resolvedItems.push(
  443. separatorDeleteItem);itemID=CLB_app.bmSyncer.createSeparatorID(parent,position)}else{itemID=id}var item=new CLB_SyncItem({componentID:CLB_app.bmSyncer.componentID,typeID:typeID,itemID:itemID,properties:{parents:parent,positions:position}});resolvedItems.push(item);folder.removeBookmark(itemID);this.addItemToFolder(item,false)}var toolbarProperty=CLB_app.bmSyncer.propertiesToCollect_.getKey(CLB_BookmarkSyncer.toolbarFolder);if(oldFolder.hasProperty(toolbarProperty)&&!isNull(oldFolder.getProperty(toolbarProperty)
  444. )){var newItemUpdate=newFolder.clone();newItemUpdate.setProperty(toolbarProperty,"true");resolvedItems.push(newItemUpdate)}oldFolder.clearProperties();oldFolder.isRemove=true;return resolvedItems}
  445. ;CLB_BookmarkResolver.prototype.resolveUrlConflict=function(oldItem,newItem){var resolvedItems=this.removeItemFromFolder(oldItem,true);oldItem.clearProperties();oldItem.isRemove=true;return resolvedItems}
  446. ;CLB_BookmarkResolver.prototype.resolvePositionConflict=function(oldItem,newItem){var position=CLB_app.bmSyncer.getPosition(oldItem);var parent=CLB_app.bmSyncer.getParent(oldItem);var newPosition=parseInt(position)+1;var itemToInsert;if(oldItem.typeID=="separator"){itemToInsert=oldItem.clone();itemToInsert.itemID=CLB_app.bmSyncer.createSeparatorID(parent,newPosition);this.removeItemFromFolder(oldItem);oldItem.clearProperties();oldItem.isRemove=true}else{itemToInsert=oldItem}itemToInsert.setProperty(
  447. "positions",newPosition);var shiftedItems=this.addItemToFolder(itemToInsert,true);if(itemToInsert.typeID=="separator"){shiftedItems.push(itemToInsert)}return shiftedItems}
  448. ;CLB_BookmarkResolver.prototype.resolveToolbarConflict=function(oldItem,newItem){if(oldItem.typeID!="folder"){return[]}var toolbarProperty=CLB_app.bmSyncer.propertiesToCollect_.getKey(CLB_BookmarkSyncer.toolbarFolder);oldItem.setProperty(toolbarProperty,null);var titleProperty=CLB_app.bmSyncer.propertiesToCollect_.getKey(CLB_BookmarkSyncer.nameRdfStr);var oldItemTitle=oldItem.getProperty(titleProperty);var newItemTitle=newItem.getProperty(titleProperty);if(oldItemTitle==CLB_BookmarkResolver.oldToolbarName&&
  449. newItemTitle==CLB_BookmarkResolver.newToolbarName||oldItemTitle==CLB_BookmarkResolver.newToolbarName&&newItemTitle==CLB_BookmarkResolver.oldToolbarName){return this.mergeFolders(oldItem,newItem)}return[]}
  450. ;G_debugService.loggifier.loggify(CLB_BookmarkResolver.prototype);function CLB_Folder(parent){this.maxPosition_=0;this.name_=null;this.parent_=null;this.contents_={};var parentNode=CLB_app.bmSyncer.bmRdfServ.GetResource(parent);if(!CLB_app.bmSyncer.bmServ.isBookmarkedResource(parentNode)){return}var container=Cc["@mozilla.org/rdf/container;1"].getService(Ci.nsIRDFContainer);container.Init(CLB_app.bmSyncer.bmDS,parentNode);var localBms=container.GetElements();while(localBms.hasMoreElements()){var bm=
  451. localBms.getNext();var bmValue=CLB_rdf.getValueFromNode(bm);var pos=container.IndexOf(bm);var typeID=CLB_app.bmSyncer.getTypeID(bm);if(typeID=="separator"){var itemID=CLB_app.bmSyncer.createSeparatorID(parent,pos);this.addBookmark(itemID,typeID,pos)}else{this.addBookmark(bmValue,typeID,pos)}}}
  452. CLB_Folder.prototype.addBookmark=function(id,typeID,position){if(isDef(this.contents_[id])){G_Debug(this,"Warning: adding the same bookmark again.  id: "+id+" Old position: "+this.contents_[id].position+" New position: "+position)}position=parseInt(position);if(isNaN(position)){G_Debug(this,"Could not parse position value, not adding bookmark "+id);return}this.contents_[id]={position:position,typeID:typeID};if(position>this.maxPosition_){this.maxPosition_=position}}
  453. ;CLB_Folder.prototype.removeBookmark=function(id){var bm=this.contents_[id];if(!isDef(bm)){G_Debug(this,"Warning: deleting nonexistant item "+id+" from a folder");return}if(this.maxPosition_>0&&this.maxPosition_==bm.position){this.maxPosition_=this.maxPosition_-1}delete this.contents_[id]}
  454. ;CLB_Folder.prototype.hasBookmark=function(id){return isDef(this.contents_[id])}
  455. ;CLB_Folder.prototype.getBookmarkPosition=function(id){return this.contents_[id].position}
  456. ;CLB_Folder.prototype.getBookmarkTypeID=function(id){return this.contents_[id].typeID}
  457. ;CLB_Folder.prototype.setName=function(newName){this.name_=newName}
  458. ;CLB_Folder.prototype.getName=function(){return this.name_}
  459. ;CLB_Folder.prototype.setParent=function(parentID){this.parent_=parentID}
  460. ;CLB_Folder.prototype.getParent=function(){return this.parent_}
  461. ;CLB_Folder.prototype.toString=function(){var str="{ CLB_Folder Max Position: %s Contents: ".subs(this.maxPosition_);for(var id in this.contents_){str+="id=%s, typeid=%s, position=%s - ".subs(id,this.getBookmarkTypeID(id),this.getBookmarkPosition(id))}str+=" }";return str}
  462. ;G_debugService.loggifier.loggify(CLB_Folder.prototype);
  463. function CLB_BookmarkSyncer(){this.bmDS=Cc["@mozilla.org/rdf/datasource;1?name=bookmarks"].getService(Ci.nsIRDFDataSource);this.bmRdfServ=Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService);this.container=Cc["@mozilla.org/rdf/container;1"].getService(Ci.nsIRDFContainer);this.containerUtils=Cc["@mozilla.org/rdf/container-utils;1"].getService(Ci.nsIRDFContainerUtils);this.bmServ=Cc["@mozilla.org/browser/bookmarks-service;1"].getService(Ci.nsIBookmarksService);this.started_=false;this.propertiesToCollect_=
  464. new G_DoubleDictionary;this.propertiesToCollect_.addMultiple({title:CLB_BookmarkSyncer.nameRdfStr,url:CLB_BookmarkSyncer.urlRdfStr,description:CLB_BookmarkSyncer.descriptionRdfStr,addDate:CLB_BookmarkSyncer.bookmarkAddDateRdfStr,shortcutURL:CLB_BookmarkSyncer.shortcutRdfStr,webPanel:CLB_BookmarkSyncer.showInSidebarRdfStr,forwardProxy:CLB_BookmarkSyncer.forwardProxyRdfStr,bookmarksToolbarFolder:CLB_BookmarkSyncer.toolbarFolder,feedURL:CLB_BookmarkSyncer.feedUrlRdfStr});CLB_syncMan.registerConflict(
  465. this,"folder",CLB_BookmarkSyncer.toolbarFolderConflict,new CLB_ArrayEnumerator([this.propertiesToCollect_.getKey(CLB_BookmarkSyncer.toolbarFolder)]));CLB_syncMan.registerConflict(this,"folder",CLB_BookmarkSyncer.folderNameConflict,new CLB_ArrayEnumerator([this.propertiesToCollect_.getKey(CLB_BookmarkSyncer.nameRdfStr)]));CLB_syncMan.registerConflict(this,"bookmark",CLB_BookmarkSyncer.urlConflict,new CLB_ArrayEnumerator(["parents",this.propertiesToCollect_.getKey(CLB_BookmarkSyncer.urlRdfStr)]));CLB_syncMan.registerConflict(
  466. this,null,CLB_BookmarkSyncer.positionConflict,new CLB_ArrayEnumerator(["parents","positions"]));this.resolver=new CLB_BookmarkResolver;this.orphanChildren={};this.toolbarItemToDelete=null;CLB_syncMan.addObserver(this);this.updateBatchData_={};this.inUpdateBatch=false}
  467. CLB_BookmarkSyncer.folderNameConflict="folderName";CLB_BookmarkSyncer.urlConflict="url";CLB_BookmarkSyncer.positionConflict="position";CLB_BookmarkSyncer.toolbarFolderConflict="toolbar";CLB_BookmarkSyncer.rootRdfStr="NC:BookmarksRoot";CLB_BookmarkSyncer.oldRootRdfStr="NC:PersonalToolbarFolder";CLB_BookmarkSyncer.rdfPrefix="http://home.netscape.com/NC-rdf#";CLB_BookmarkSyncer.nameRdfStr=CLB_BookmarkSyncer.rdfPrefix+"Name";CLB_BookmarkSyncer.urlRdfStr=CLB_BookmarkSyncer.rdfPrefix+"URL";CLB_BookmarkSyncer.bookmarkAddDateRdfStr=
  468. CLB_BookmarkSyncer.rdfPrefix+"BookmarkAddDate";CLB_BookmarkSyncer.idRdfStr=CLB_BookmarkSyncer.rdfPrefix+"ID";CLB_BookmarkSyncer.descriptionRdfStr=CLB_BookmarkSyncer.rdfPrefix+"Description";CLB_BookmarkSyncer.iconRdfStr=CLB_BookmarkSyncer.rdfPrefix+"Icon";CLB_BookmarkSyncer.shortcutRdfStr=CLB_BookmarkSyncer.rdfPrefix+"ShortcutURL";CLB_BookmarkSyncer.showInSidebarRdfStr=CLB_BookmarkSyncer.rdfPrefix+"WebPanel";CLB_BookmarkSyncer.livemarkRdfStr=CLB_BookmarkSyncer.rdfPrefix+"Livemark";CLB_BookmarkSyncer.feedUrlRdfStr=
  469. CLB_BookmarkSyncer.rdfPrefix+"FeedURL";CLB_BookmarkSyncer.separatorRdfStr=CLB_BookmarkSyncer.rdfPrefix+"BookmarkSeparator";CLB_BookmarkSyncer.toolbarFolder=CLB_BookmarkSyncer.rdfPrefix+"BookmarksToolbarFolder";CLB_BookmarkSyncer.forwardProxyRdfStr="http://developer.mozilla.org/rdf/vocabulary/forward-proxy#forward-proxy";CLB_BookmarkSyncer.webRdfPrefix="http://home.netscape.com/WEB-rdf#";CLB_BookmarkSyncer.lastCharsetRdfStr=CLB_BookmarkSyncer.webRdfPrefix+"LastCharset";CLB_BookmarkSyncer.lastModifiedRdfStr=
  470. CLB_BookmarkSyncer.webRdfPrefix+"LastModifiedDate";CLB_BookmarkSyncer.w3RdfPrefix="http://www.w3.org/1999/02/22-rdf-syntax-ns#";CLB_BookmarkSyncer.nextValRdfStr=CLB_BookmarkSyncer.w3RdfPrefix+"nextVal";CLB_BookmarkSyncer.seqRdfStr=CLB_BookmarkSyncer.w3RdfPrefix+"_";CLB_BookmarkSyncer.typeRdfStr=CLB_BookmarkSyncer.w3RdfPrefix+"type";CLB_BookmarkSyncer.instanceOfRdfStr=CLB_BookmarkSyncer.w3RdfPrefix+"instanceOf";CLB_BookmarkSyncer.sequenceRdfStr=CLB_BookmarkSyncer.w3RdfPrefix+"Seq";CLB_BookmarkSyncer.anonContentPrefix=
  471. "rdf:#$";CLB_BookmarkSyncer.scratchFolderID="rdf:#$111111";CLB_BookmarkSyncer.RDF_LITERAL=0;CLB_BookmarkSyncer.RDF_DATE_LITERAL=1;CLB_BookmarkSyncer.RDF_RESOURCE=2;CLB_BookmarkSyncer.prototype.debugZone="CLB_BookmarkSyncer";CLB_BookmarkSyncer.prototype.QueryInterface=function(aIID){if(!aIID.equals(Ci.nsISupports)&&!aIID.equals(Ci.nsIRDFObserver)&&!aIID.equals(Ci.GISyncComponent))throw Components.results.NS_ERROR_NO_INTERFACE;return this}
  472. ;CLB_BookmarkSyncer.prototype.updateStart=(CLB_BookmarkSyncer.prototype.updateComplete=(CLB_BookmarkSyncer.prototype.updateFailure=(CLB_BookmarkSyncer.prototype.syncProgress=(CLB_BookmarkSyncer.prototype.updateProgress=function(){}
  473. ))));CLB_BookmarkSyncer.prototype.syncStart=function(){this.bmServ.readBookmarks();G_Debug(this,"Checking for scratch folder before sync");this.ensureScratchFolderRemoved();if(this.inUpdateBatch){G_DebugL(this,"WARNING: syncStart called twice without syncFailure.");return}this.bmDS.beginUpdateBatch();this.inUpdateBatch=true}
  474. ;CLB_BookmarkSyncer.prototype.syncComplete=(CLB_BookmarkSyncer.prototype.syncFailure=function(){this.bmServ.readBookmarks();G_Debug(this,"Checking for scratch folder after sync");this.ensureScratchFolderRemoved();if(!this.inUpdateBatch){G_DebugL(this,"WARNING: syncFailure called without corresponding syncStart.");return}this.bmDS.endUpdateBatch();this.inUpdateBatch=false}
  475. );CLB_BookmarkSyncer.prototype.componentID="@google.com/browserstate/bookmark-syncer;1";CLB_BookmarkSyncer.prototype.componentName="Bookmarks";CLB_BookmarkSyncer.prototype.encryptionRequred=false;CLB_BookmarkSyncer.prototype.syncOfflineChanges=true;CLB_BookmarkSyncer.prototype.syncBehavior=Ci.GISyncComponent.SYNC_SINCE_LAST_UDPATE;CLB_BookmarkSyncer.prototype.start=function(){G_Debug(this,"Starting bookmark syncer");if(!this.started_){this.bmServ.readBookmarks();this.orphanChildren={};this.resolver.clear(
  476. );if(this.toolbarItemToDelete){G_Debug(this,"Error: we should have already deleted the old toolbar  folder with itemID "+this.toolbarItemToDelete.itemID+"  Perhaps no other item was set to the toolbar folder");this.toolbarItemToDelete=null}this.ensureScratchFolderRemoved();this.bmDS.AddObserver(this);this.started_=true}}
  477. ;CLB_BookmarkSyncer.prototype.stop=function(){G_Debug(this,"Stopping bookmark syncer");this.bmDS.RemoveObserver(this);this.started_=false}
  478. ;CLB_BookmarkSyncer.prototype.onBeforeResolveConflict=function(item){this.bmServ.readBookmarks();this.resolver.addDownloadedItem(item)}
  479. ;CLB_BookmarkSyncer.prototype.onItemConflict=function(conflict,oldItem,newItem){this.bmServ.readBookmarks();var resolvedItems;G_Debug(this,"Conflict detected between "+oldItem.toStringVerbose()+" and "+newItem.toStringVerbose());if(conflict==CLB_BookmarkSyncer.folderNameConflict){resolvedItems=this.resolver.resolveFolderNameConflict(oldItem,newItem)}else if(conflict==CLB_BookmarkSyncer.urlConflict){resolvedItems=this.resolver.resolveUrlConflict(oldItem,newItem)}else if(conflict==CLB_BookmarkSyncer.positionConflict)
  480. {resolvedItems=this.resolver.resolvePositionConflict(oldItem,newItem)}else if(conflict==CLB_BookmarkSyncer.toolbarFolderConflict){resolvedItems=this.resolver.resolveToolbarConflict(oldItem,newItem)}G_Debug(this,"After resolving conflict, syncItem is: "+oldItem.toStringVerbose());G_Debug(this,"There are %s other resolved items.".subs(resolvedItems.length));return new CLB_ArrayEnumerator(resolvedItems)}
  481. ;CLB_BookmarkSyncer.prototype.onItemAvailable=function(item){this.bmServ.readBookmarks();this.addBookmarkItem(item)}
  482. ;CLB_BookmarkSyncer.prototype.getItemByID=function(id,typeid){var rdfNode;if(typeid=="separator"){rdfNode=this.getSeparatorResource(id)}else{rdfNode=this.bmRdfServ.GetResource(id)}if(!rdfNode){G_Debug(this,"Warning - could not retrieve resource using id "+id+" and typeID "+typeid);return null}return this.fillBookmarkItem(rdfNode)}
  483. ;CLB_BookmarkSyncer.prototype.getCurrentItems=function(){this.bmServ.readBookmarks();var e=this.bmDS.GetAllResources();return new CLB_BookmarkEnumerator(e)}
  484. ;CLB_BookmarkSyncer.prototype.beforeUpdate=function(){}
  485. ;CLB_BookmarkSyncer.prototype.onChange=function(aDataSource,aSource,aProperty,aOldTarget,aNewTarget){var newValue=CLB_rdf.getValueFromNode(aNewTarget);if(isNull(newValue)){G_Debug(this,"Could not extract value from target, skipping");return}G_Debug(this,"onChange: %s %s changed to %s\n\n".subs(aSource.Value,aProperty.Value,newValue));var items=this.getUpdateItems(aSource,aProperty,newValue,false);if(items){items.forEach(function(item){CLB_syncMan.update(item)}
  486. )}}
  487. ;CLB_BookmarkSyncer.prototype.onAssert=function(aDataSource,aSource,aProperty,aTarget){var newValue=CLB_rdf.getValueFromNode(aTarget);if(isNull(newValue)){G_Debug(this,"Could not extract value from target, skipping");return}G_Debug(this,"onAssert: %s %s %s".subs(aSource.Value,aProperty.Value,newValue));var items=this.getUpdateItems(aSource,aProperty,newValue,false);if(items){items.forEach(function(item){CLB_syncMan.update(item)}
  488. )}}
  489. ;CLB_BookmarkSyncer.prototype.onUnassert=function(aDataSource,aSource,aProperty,aTarget){G_Debug(this,"onunassert: src: %s property: %s".subs(aSource.Value,aProperty.Value));var value=CLB_rdf.getValueFromNode(aTarget);if(isNull(value)){G_Debug(this,"Could not extract value from target, skipping");return}G_Debug(this,"onUnassert: %s %s %s".subs(aSource.Value,aProperty.Value,value));var items=this.getUpdateItems(aSource,aProperty,value,true);if(items){items.forEach(function(item){CLB_syncMan.update(
  490. item)}
  491. )}}
  492. ;CLB_BookmarkSyncer.prototype.onMove=function(aDataSource,aOldSource,aNewSource,aProperty,aTarget){G_Debug(this,"Warning: bookmark is calling onMove!!");var value=CLB_rdf.getValueFromNode(aTarget);G_Debug(this,"onMove: %s %s %s %s".subs(aOldSource.Value,aNewSource.Value,aProperty.Value,value))}
  493. ;CLB_BookmarkSyncer.prototype.onBeginUpdateBatch=function(aDataSource){G_Debug(this,"Bookmark component calling onBeginUpdateBatch");var e=this.bmDS.GetAllResources();while(e.hasMoreElements()){var bm=e.getNext();if(!this.shouldUpdateGivenTarget(bm)){continue}var bookmarkID=CLB_rdf.getValueFromNode(bm);var parent=this.bmServ.getParent(bm);var parentID=CLB_rdf.getValueFromNode(parent);var container=CLB_rdf.getInitializedContainer(this.bmDS,parent);var position=container.IndexOf(bm);var typeID=this.getTypeID(
  494. bm);this.updateBatchData_[bookmarkID]={parentID:parentID,position:position,typeID:typeID}}}
  495. ;CLB_BookmarkSyncer.prototype.onEndUpdateBatch=function(aDataSource){G_Debug(this,"Bookmark component calling onEndUpdateBatch");var e=this.bmDS.GetAllResources();while(e.hasMoreElements()){var bm=e.getNext();if(!this.shouldUpdateGivenTarget(bm)){continue}var bookmarkID=CLB_rdf.getValueFromNode(bm);var batchInfo=this.updateBatchData_[bookmarkID];if(!isDef(batchInfo)){G_Debug(this,"New item inserted");var item=this.fillBookmarkItem(bm);CLB_syncMan.update(item);continue}var parent=this.bmServ.getParent(
  496. bm);var parentID=CLB_rdf.getValueFromNode(parent);var container=CLB_rdf.getInitializedContainer(this.bmDS,parent);var position=container.IndexOf(bm);if(batchInfo.parentID!=parentID||batchInfo.position!=position){G_Debug(this,"Old parentID: "+batchInfo.parentID+", New parentID: "+parentID+", Old position: "+batchInfo.position+", New position: "+position);var item=this.fillBookmarkItem(bm);CLB_syncMan.update(item)}delete this.updateBatchData_[bookmarkID]}for(var bmID in this.updateBatchData_){G_Debug(
  497. this,"Item deleted");var item=new CLB_SyncItem({componentID:this.componentID,typeID:this.updateBatchData_[bmID].typeID,itemID:bmID,isRemove:true,properties:{}});CLB_syncMan.update(item)}this.updateBatchData_={}}
  498. ;CLB_BookmarkSyncer.prototype.getNodeFromProperty=function(propertyString,target){if(propertyString==CLB_BookmarkSyncer.nameRdfStr||propertyString==CLB_BookmarkSyncer.urlRdfStr||propertyString==CLB_BookmarkSyncer.descriptionRdfStr||propertyString==CLB_BookmarkSyncer.shortcutRdfStr||propertyString==CLB_BookmarkSyncer.showInSidebarRdfStr||propertyString==CLB_BookmarkSyncer.feedUrlRdfStr){return this.bmRdfServ.GetLiteral(target)}else if(propertyString==CLB_BookmarkSyncer.bookmarkAddDateRdfStr){return this.bmRdfServ.GetDateLiteral(
  499. target)}else if(propertyString==CLB_BookmarkSyncer.idRdfStr||propertyString==CLB_BookmarkSyncer.forwardProxyRdfStr||propertyString==CLB_BookmarkSyncer.typeRdfStr){return this.bmRdfServ.GetResource(target)}else{G_Debug(this,"WARNING: addBookmark item got an unexpected assertation");return null}}
  500. ;CLB_BookmarkSyncer.prototype.isSourceResource=function(value){return value.startsWith(CLB_BookmarkSyncer.anonContentPrefix)||value.startsWith(CLB_BookmarkSyncer.rootRdfStr)||value.startsWith(CLB_BookmarkSyncer.oldRootRdfStr)}
  501. ;CLB_BookmarkSyncer.prototype.shouldUpdateGivenTarget=function(bookmarkTarget){if(!(bookmarkTarget instanceof Ci.nsIRDFResource)){G_Debug(this,"Failed to cast a resource to nsIRDFResource");return false}if(!this.bmServ.isBookmarkedResource(bookmarkTarget)){return false}var arcs=this.bmDS.ArcLabelsIn(bookmarkTarget);if(!arcs.hasMoreElements()){return false}var positionArc=arcs.getNext();if(!this.containerUtils.IsOrdinalProperty(positionArc)){return false}var srcs=this.bmDS.GetSources(positionArc,bookmarkTarget,
  502. true);if(!srcs.hasMoreElements()){return false}var parent=srcs.getNext();if(!this.shouldUpdate(parent,positionArc)){return false}return true}
  503. ;CLB_BookmarkSyncer.prototype.shouldUpdate=function(aSource,aProperty){var typeArc=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.typeRdfStr);var livemarkTarget=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.livemarkRdfStr);if(this.bmDS.HasAssertion(aSource,typeArc,livemarkTarget,true)){var prop=CLB_rdf.getValueFromNode(aProperty);if(this.propertiesToCollect_.hasValue(prop)){return true}else{G_Debug(this,"skipping livemark");return false}}var arcs=this.bmDS.ArcLabelsIn(aSource);if(!arcs.hasMoreElements(
  504. )){G_Debug(this,"Skipping assertation not in the rdf tree");return false}while(arcs.hasMoreElements()){var arc=arcs.getNext();var srcs=this.bmDS.GetSources(arc,aSource,true);while(srcs.hasMoreElements()){var src=srcs.getNext();if(this.bmDS.HasAssertion(src,typeArc,livemarkTarget,true)){G_Debug(this,"skipping livemark");return false}}}return true}
  505. ;CLB_BookmarkSyncer.prototype.parsePositionFromProperty=function(aProperty){var val=CLB_rdf.getValueFromNode(aProperty);val=val.replace(CLB_BookmarkSyncer.seqRdfStr,"");return parseInt(val)}
  506. ;CLB_BookmarkSyncer.prototype.getPropertyFromPosition=function(position){return CLB_BookmarkSyncer.seqRdfStr+position}
  507. ;CLB_BookmarkSyncer.prototype.getAllChildProperties=function(aSource,item){var arcs=this.bmDS.ArcLabelsOut(aSource);while(arcs.hasMoreElements()){var arc=arcs.getNext();var arcValue=CLB_rdf.getValueFromNode(arc);if(!this.propertiesToCollect_.hasValue(arcValue)){continue}var targets=this.bmDS.GetTargets(aSource,arc,true);if(targets.hasMoreElements()){var targetValue=CLB_rdf.getValueFromNode(targets.getNext());G_Debug(this,"Found child %s, %s, %s".subs(aSource.Value,arcValue,targetValue));var itemArcValue=
  508. this.propertiesToCollect_.getKey(arcValue);if(!item.hasProperty(itemArcValue)){item.setProperty(itemArcValue,targetValue)}}}}
  509. ;CLB_BookmarkSyncer.prototype.removeAllChildProperties=function(aSource,url){if(this.isLivemark(aSource)){this.removeLivemarkType(aSource)}var allArcs=[];var shouldDeleteIcon=false;var arcs=this.bmDS.ArcLabelsOut(aSource);while(arcs.hasMoreElements()){var arc=arcs.getNext();var arcVal=CLB_rdf.getValueFromNode(arc);if(arcVal==CLB_BookmarkSyncer.iconRdfStr){if(url!=null&&url!=""){shouldDeleteIcon=true}}else{allArcs[allArcs.length]=arc}}if(shouldDeleteIcon){G_Debug(this,"About to delete icon with url %s"
  510. .subs(url));this.bmServ.removeBookmarkIcon(url)}for(var i=0;i<allArcs.length;i++){var arc=allArcs[i];var arcValue=CLB_rdf.getValueFromNode(arc);var tar=this.bmDS.GetTarget(aSource,arc,true);if(isNull(tar)){continue}if(arcValue!=CLB_BookmarkSyncer.idRdfStr&&tar instanceof Ci.nsIRDFResource){var newUrl=this.getBookmarkUrl(tar);this.removeAllChildProperties(tar,newUrl)}var srcVal=CLB_rdf.getValueFromNode(aSource);arcVal=CLB_rdf.getValueFromNode(arc);var tarVal=CLB_rdf.getValueFromNode(tar);G_Debug(this,
  511. "About to unassert %s, %s, %s".subs(srcVal,arcVal,tarVal));this.bmDS.Unassert(aSource,arc,tar)}}
  512. ;CLB_BookmarkSyncer.prototype.getDeletedFolderContents=function(node,items){if(this.isFolder(node)){this.container.Init(this.bmDS,node);var bookmarks=this.container.GetElements();while(bookmarks.hasMoreElements()){var bm=bookmarks.getNext();if(this.isFolder(bm)){this.getDeletedFolderContents(bm,items)}var item=this.setRequiredFields(bm);item.isRemove=true;items[items.length]=item}}}
  513. ;CLB_BookmarkSyncer.prototype.removeLivemarkType=function(node){var t=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.typeRdfStr);var lm=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.livemarkRdfStr);return this.bmDS.Unassert(node,t,lm,true)}
  514. ;CLB_BookmarkSyncer.prototype.isFolder=function(node){return this.containerUtils.IsSeq(this.bmDS,node)}
  515. ;CLB_BookmarkSyncer.prototype.isLivemark=function(node){var t=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.typeRdfStr);var lm=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.livemarkRdfStr);return this.bmDS.HasAssertion(node,t,lm,true)}
  516. ;CLB_BookmarkSyncer.prototype.isSeparator=function(node){var t=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.typeRdfStr);var s=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.separatorRdfStr);return this.bmDS.HasAssertion(node,t,s,true)}
  517. ;CLB_BookmarkSyncer.prototype.setTypeID=function(node,item){item.typeID=this.getTypeID(node)}
  518. ;CLB_BookmarkSyncer.prototype.getTypeID=function(node){if(this.isLivemark(node)){return"livemark"}else if(this.isSeparator(node)){return"separator"}else if(this.isFolder(node)){return"folder"}else{return"bookmark"}}
  519. ;CLB_BookmarkSyncer.prototype.setItemID=function(node,item,opt_parent,opt_pos){if(this.isSeparator(node)){var parentNode,position;if(isDef(opt_parent)){if(!isDef(opt_pos)){throw new Error("Both parent and position should be specified");}parentNode=opt_parent;position=this.parsePositionFromProperty(opt_pos);if(isNaN(position)){throw new Error("Incorrectly formatted ordinal node");}}else{parentNode=this.bmServ.getParent(node);this.container.Init(this.bmDS,parentNode);position=this.container.IndexOf(
  520. node)}var parentValue=CLB_rdf.getValueFromNode(parentNode);item.itemID=this.createSeparatorID(parentValue,position)}else{var value=CLB_rdf.getValueFromNode(node);item.itemID=value}}
  521. ;CLB_BookmarkSyncer.prototype.createSeparatorID=function(parent,position){return parent+","+position}
  522. ;CLB_BookmarkSyncer.prototype.annotateType=function(type,node){var t=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.typeRdfStr);if(type=="folder"){this.containerUtils.MakeSeq(this.bmDS,node)}else if(type=="livemark"){var lm=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.livemarkRdfStr);this.bmDS.Assert(node,t,lm,true)}else if(type=="separator"){var s=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.separatorRdfStr);this.bmDS.Assert(node,t,s,true)}}
  523. ;CLB_BookmarkSyncer.prototype.setRequiredFields=function(node,opt_parent,opt_pos){var item=new CLB_SyncItem({componentID:this.componentID});this.setTypeID(node,item);this.setItemID(node,item,opt_parent,opt_pos);return item}
  524. ;CLB_BookmarkSyncer.prototype.fillBookmarkItem=function(bmNode){var item=this.setRequiredFields(bmNode);this.setContainerInfo(item,bmNode);this.getAllChildProperties(bmNode,item);return item}
  525. ;CLB_BookmarkSyncer.prototype.getUpdateItems=function(aSource,aProperty,value,isRemove){if(!this.shouldUpdate(aSource,aProperty)){G_Debug(this,"Skipping update...");return null}var valueNode=this.bmRdfServ.GetResource(value);var item;if(this.isSourceResource(value.toString())){item=this.setRequiredFields(valueNode,aSource,aProperty);if(isRemove){item.isRemove=isRemove;var otherItems=[];this.getDeletedFolderContents(valueNode,otherItems);otherItems[otherItems.length]=item;return otherItems}if(!this.setContainerInfo(
  526. item,valueNode)){G_Debug(this,"Problem setting parent and position info. Perhaps the node {%s} is not attached to the rdf "+"tree".subs(valueNode));return null}this.getAllChildProperties(valueNode,item);var childItems=this.getAllChildItems(valueNode);childItems[childItems.length]=item;return childItems}else if(this.isSourceResource(aSource.Value)){if(!this.propertiesToCollect_.hasValue(aProperty.Value)){G_Debug(this,"Skipping update to non-recorded property {%s}".subs(aProperty.Value));return null}
  527. item=this.setRequiredFields(aSource);this.setContainerInfo(item,aSource);var itemPropertyValue=this.propertiesToCollect_.getKey(aProperty.Value);if(isRemove){item.setProperty(itemPropertyValue,null)}else{item.setProperty(itemPropertyValue,value)}item.isRemove=false;G_Debug(this,"Updating for %s".subs(aProperty.Value));G_Debug(this,"source: %s".subs(aSource.Value));G_Debug(this,"value: %s".subs(value));G_Debug(this,"Item ID is %s\n".subs(item.itemID));return[item]}else{return null}}
  528. ;CLB_BookmarkSyncer.prototype.setContainerInfo=function(item,bmNode){G_Debug(this,"getting parent for node %s".subs(bmNode.Value));var parent=this.bmServ.getParent(bmNode);if(!parent){return false}this.container.Init(this.bmDS,parent);var position=this.container.IndexOf(bmNode);var parValue=CLB_rdf.getValueFromNode(parent);G_Debug(this,"setting parents: "+parValue+"\n");G_Debug(this,"setting positions: "+position+"\n");item.setProperty("parents",parValue);item.setProperty("positions",position);return true}
  529.  
  530. ;CLB_BookmarkSyncer.prototype.getAllChildItems=function(src){var currentItems=[];var outArcs=this.bmDS.ArcLabelsOut(src);while(outArcs.hasMoreElements()){var arc=outArcs.getNext();var pos=this.parsePositionFromProperty(arc);if(isNaN(pos)){continue}if(!this.shouldUpdate(src,arc)){continue}var tar=this.bmDS.GetTarget(src,arc,true);if(tar){var item=this.fillBookmarkItem(tar);if(item!=null){currentItems[currentItems.length]=item}if(tar instanceof Ci.nsIRDFResource){currentItems=currentItems.concat(this.getAllChildItems(
  531. tar))}}}return currentItems}
  532. ;CLB_BookmarkSyncer.prototype.getContainerFromSeparatorID=function(id){var idComponents=id.split(",");if(idComponents.length!=2){G_Debug(this,"WARNING: separator ID incorrectly formatted: "+id);return null}return idComponents[0]}
  533. ;CLB_BookmarkSyncer.prototype.getPositionFromSeparatorID=function(id){var idComponents=id.split(",");if(idComponents.length!=2){G_Debug(this,"WARNING: separator ID incorrectly formatted: "+id);return null}return idComponents[1]}
  534. ;CLB_BookmarkSyncer.prototype.isToolbarFolder=function(folderValue){var toolbarNode=this.bmServ.getBookmarksToolbarFolder();if(CLB_rdf.getValueFromNode(toolbarNode)==folderValue){return true}return false}
  535. ;CLB_BookmarkSyncer.prototype.maybeDeleteOldToolbarFolder=function(){if(!this.toolbarItemToDelete){return}if(this.isToolbarFolder(this.toolbarItemToDelete.itemID)){return}this.handleDeleteItem(this.toolbarItemToDelete);this.toolbarItemToDelete=null}
  536. ;CLB_BookmarkSyncer.prototype.handleDeleteItem=function(item){var contRes,position;if(item.typeID=="separator"){var cont=this.getContainerFromSeparatorID(item.itemID);position=this.getPositionFromSeparatorID(item.itemID);if(isNull(cont)||isNull(position)){G_Debug(this,"Error: skipping delete of separator with malformed id");return}contRes=this.bmRdfServ.GetResource(cont);if(!this.bmServ.isBookmarkedResource(contRes)){G_Debug(this,"Warning: trying to delete a separator that doesn't  exist");return}
  537. this.container.Init(this.bmDS,contRes);var positionProp=this.bmRdfServ.GetResource(this.getPropertyFromPosition(position));var sep=this.bmDS.GetTarget(contRes,positionProp,true);if(sep&&this.isSeparator(sep)){G_Debug(this,"Found and deleting separator at position "+position);this.container.RemoveElement(sep,false)}}else{var srcRes=this.bmRdfServ.GetResource(item.itemID);if(!this.bmServ.isBookmarkedResource(srcRes)){return}contRes=this.bmServ.getParent(srcRes);if(!contRes){G_Debug(this,"Warning: trying to delete an element that doesn't exist"
  538. );return}if(item.typeID=="folder"&&this.isToolbarFolder(item.itemID)){if(this.toolbarItemToDelete){G_Debug(this,"Error: we should never have 2 toolbar folders to delete!  itemIDs are "+this.toolbarItemToDelete.itemID+" and "+item.itemID)}this.toolbarItemToDelete=item;return}if(item.typeID=="folder"){this.rescueFolderChildren(srcRes)}this.container.Init(this.bmDS,contRes);position=this.container.IndexOf(srcRes);var url=this.getBookmarkUrl(srcRes);this.removeAllChildProperties(srcRes,url);this.container.RemoveElement(
  539. srcRes,false);this.maybeDecrementNextVal(contRes,position)}G_Debug(this,"Just deleted item with container "+CLB_rdf.getValueFromNode(contRes)+" and position "+position)}
  540. ;CLB_BookmarkSyncer.prototype.getSeparatorResource=function(itemID){var position=this.getPositionFromSeparatorID(itemID);var container=this.getContainerFromSeparatorID(itemID);if(isNull(position)||isNull(container)){return null}var positionRes=this.bmRdfServ.GetResource(this.getPropertyFromPosition(position));var containerRes=this.bmRdfServ.GetResource(container);var oldSep=this.bmDS.GetTarget(containerRes,positionRes,true);if(!isNull(oldSep)&&this.isSeparator(oldSep)){return oldSep}else{return this.bmRdfServ.GetAnonymousResource(
  541. )}}
  542. ;CLB_BookmarkSyncer.prototype.addBookmarkItem=function(item){G_Debug(this,"About to add bookmark with syncitem: "+item.toStringVerbose());if(!isDef(item.itemID)){G_DebugL(this,"Warning: itemID is null, skipping!!\n");return}if(item.isRemove){this.handleDeleteItem(item);return}var srcRes;if(item.typeID=="separator"){srcRes=this.getSeparatorResource(item.itemID)}else{srcRes=this.bmRdfServ.GetResource(item.itemID)}var target,tarRes,propRes;if(item.hasProperty("positions")){if(!item.hasProperty("parents"
  543. )){G_Debug(this,"Update item has position but not parents! skipping...");return}var parent=this.getParent(item);var position=this.getPosition(item);var contRes=this.bmRdfServ.GetResource(parent);if(!this.bmServ.isBookmarkedResource(contRes)){this.recordOrphanChild(parent,CLB_rdf.getValueFromNode(srcRes),position);contRes=this.getScratchFolder(true);this.container.Init(this.bmDS,contRes);position=parseInt(this.container.GetCount()+1);parent=CLB_rdf.getValueFromNode(contRes)}this.container.Init(this.bmDS,
  544. contRes);var isBookmarked=this.bmServ.isBookmarkedResource(srcRes);if(isBookmarked){this.maybeMoveBookmark(srcRes,parent,position,item.typeID)}else{this.insertBookmark(contRes,srcRes,position,item.typeID)}}this.maybeAssert(srcRes,this.bmRdfServ.GetResource(CLB_BookmarkSyncer.idRdfStr),this.getNodeFromProperty(CLB_BookmarkSyncer.idRdfStr,CLB_rdf.getValueFromNode(srcRes)));item.getPropertyNames().forEach(function(prop){if(prop=="positions"||prop=="parents"){return}target=item.getProperty(prop);if(!
  545. this.propertiesToCollect_.hasKey(prop)){G_Debug(this,"Item contains property "+prop+" that does not correspond to an rdf property")}else{var rdfProp=this.propertiesToCollect_.getValue(prop);if(rdfProp==CLB_BookmarkSyncer.toolbarFolder){if(target!="true"){G_DebugL(this,"Skipping unexpected target for toolbarFolder: "+target);return}this.bmServ.setBookmarksToolbarFolder(srcRes)}propRes=this.bmRdfServ.GetResource(rdfProp);if(isNull(target)){this.unassertTargets(srcRes,propRes)}else if(target==""){G_Debug(
  546. this,"Skipping target with value empty string")}else{tarRes=this.getNodeFromProperty(rdfProp,target);if(isNull(tarRes)){return}this.maybeAssert(srcRes,propRes,tarRes)}}}
  547. ,this);this.maybeMoveOrphanChildren(srcRes);this.maybeDeleteOldToolbarFolder()}
  548. ;CLB_BookmarkSyncer.prototype.maybeMoveOrphanChildren=function(parentRes){var parent=CLB_rdf.getValueFromNode(parentRes);if(!parent){G_Debug(this,"Failed to extract rdf value from parent node - this should never happen")}var children=this.orphanChildren[parent];if(!isDef(children)){return}children.forEach(function(childObj){var node=this.bmRdfServ.GetResource(childObj.child);if(!node){G_Debug(this,"Could not create a resource from child "+childObj.child)}else{this.maybeMoveBookmark(node,parent,childObj.position)
  549. }}
  550. ,this);this.maybeRemoveScratchFolder()}
  551. ;CLB_BookmarkSyncer.prototype.recordOrphanChild=function(parent,child,position){var children=this.orphanChildren[parent];var childObj={child:child,position:position};if(isDef(children)){children.push(childObj)}else{this.orphanChildren[parent]=[childObj]}}
  552. ;CLB_BookmarkSyncer.prototype.rescueFolderChildren=function(folderResource){if(!this.isFolder(folderResource)){G_Debug(this,"Error: trying to rescue children for an item that is not  a folder, skipping");return}G_Debug(this,"Moving folder children to the scratch folder");var scratchFolder=this.getScratchFolder(true);var container=CLB_rdf.getInitializedContainer(this.bmDS,folderResource);var children=container.GetElements();while(children.hasMoreElements()){var childResource=children.getNext();if(
  553. this.isSeparator(childResource)){G_Debug(this,"Skipping moving separator to the scratch folder");continue}var scratchFolderPosition=CLB_rdf.getContainerCount(this.bmDS,scratchFolder)+1;this.maybeMoveBookmark(childResource,CLB_BookmarkSyncer.scratchFolderID,scratchFolderPosition)}}
  554. ;CLB_BookmarkSyncer.prototype.getScratchFolder=function(maybeInsert){if(!this.scratchFolder){this.scratchFolder=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.scratchFolderID);if(!this.bmServ.isBookmarkedResource(this.scratchFolder)){if(maybeInsert){G_Debug(this,"Initializing scratch folder");this.container.Init(this.bmDS,this.bmRdfServ.GetResource(CLB_BookmarkSyncer.rootRdfStr));this.container.InsertElementAt(this.scratchFolder,1,false);this.annotateType("folder",this.scratchFolder)}else{this.scratchFolder=
  555. null}}}return this.scratchFolder}
  556. ;CLB_BookmarkSyncer.prototype.maybeRemoveScratchFolder=function(){if(!this.scratchFolder){return}this.container.Init(this.bmDS,this.scratchFolder);G_Debug(this,"Scratch folder count: "+this.container.GetCount());if(this.container.GetCount()==0){this.removeScratchFolder()}}
  557. ;CLB_BookmarkSyncer.prototype.removeScratchFolder=function(){this.container.Init(this.bmDS,this.bmRdfServ.GetResource(CLB_BookmarkSyncer.rootRdfStr));this.container.RemoveElement(this.scratchFolder,false);this.scratchFolder=null}
  558. ;CLB_BookmarkSyncer.prototype.ensureScratchFolderRemoved=function(){this.getScratchFolder(false);if(!this.scratchFolder){return}G_Debug(this,"Scratch folder found, deleting folder and contents");this.container.Init(this.bmDS,this.scratchFolder);var bms=this.container.GetElements();while(bms.hasMoreElements()){var bm=bms.getNext();G_Debug(this,"Deleting "+CLB_rdf.getValueFromNode(bm)+" from scratch folder");this.removeBookmark(this.scratchFolder,bm)}if(this.container.GetCount()!=0){G_Debug(this,"Error: Count is still not 0 after removing every element"
  559. )}this.removeScratchFolder()}
  560. ;CLB_BookmarkSyncer.prototype.insertBookmark=function(parentRes,bookmarkRes,position,opt_type){this.maybeIncrementNextVal(parentRes,position);this.container.Init(this.bmDS,parentRes);this.container.InsertElementAt(bookmarkRes,position,false);if(isDef(opt_type)){this.annotateType(opt_type,bookmarkRes)}}
  561. ;CLB_BookmarkSyncer.prototype.removeBookmark=function(parentRes,bookmarkRes){this.container.Init(this.bmDS,parentRes);var position=this.container.IndexOf(bookmarkRes);this.container.RemoveElement(bookmarkRes,false);this.maybeDecrementNextVal(parentRes,position)}
  562. ;CLB_BookmarkSyncer.prototype.getParent=function(item){return item.getProperty("parents")}
  563. ;CLB_BookmarkSyncer.prototype.getPosition=function(item){return item.getProperty("positions")}
  564. ;CLB_BookmarkSyncer.prototype.getBookmarkUrl=function(node){var urlProp=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.urlRdfStr);var tar=this.bmDS.GetTarget(node,urlProp,true);if(tar){return CLB_rdf.getValueFromNode(tar)}else{return null}}
  565. ;CLB_BookmarkSyncer.prototype.maybeIncrementNextVal=function(containerRes,position){var prop=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.nextValRdfStr);var oldTar=this.bmDS.GetTarget(containerRes,prop,true);var count=CLB_rdf.getValueFromNode(oldTar);if(parseInt(count)<=parseInt(position)){var tar=this.bmRdfServ.GetLiteral(parseInt(position)+1);G_Debug(this,"Just changed from nextVal: %s to: %s".subs(count,tar.Value));this.bmDS.Change(containerRes,prop,oldTar,tar)}}
  566. ;CLB_BookmarkSyncer.prototype.maybeDecrementNextVal=function(containerRes,position){var prop=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.nextValRdfStr);var oldTar=this.bmDS.GetTarget(containerRes,prop,true);var count=CLB_rdf.getValueFromNode(oldTar);if(parseInt(count)==parseInt(position)+1){var tar=this.bmRdfServ.GetLiteral(this.getNewNextVal(containerRes));G_Debug(this,"Just changed from nextVal: %s to: %s".subs(count,tar.Value));this.bmDS.Change(containerRes,prop,oldTar,tar)}}
  567. ;CLB_BookmarkSyncer.prototype.setNewNextVal=function(containerRes){var arc=this.bmRdfServ.GetResource(CLB_BookmarkSyncer.nextValRdfStr);var pos=this.getNewNextVal(containerRes);var oldTar=this.bmDS.GetTarget(containerRes,arc,true);var tar=this.bmRdfServ.GetLiteral(pos);this.bmDS.Change(containerRes,arc,oldTar,tar)}
  568. ;CLB_BookmarkSyncer.prototype.getNewNextVal=function(containerRes){var arcs=this.bmDS.ArcLabelsOut(containerRes);var currentMax=0;while(arcs.hasMoreElements()){var arc=arcs.getNext();var pos=this.parsePositionFromProperty(arc);if(isNaN(pos)){continue}else if(parseInt(pos)>currentMax){currentMax=parseInt(pos)}}return parseInt(currentMax)+1}
  569. ;CLB_BookmarkSyncer.prototype.maybeMoveBookmark=function(node,containerID,position,opt_type){var parentRes=this.bmRdfServ.GetResource(containerID);var posRes=this.bmRdfServ.GetResource(this.getPropertyFromPosition(position));if(!parentRes||!posRes){G_Debug(this,"Warning: failed to create parent: %s or position node: %s. "+"skipping....\n".subs(containerID,position));return}var existingNode=this.bmDS.GetTarget(parentRes,posRes,true);if(!existingNode||CLB_rdf.getValueFromNode(existingNode)!=CLB_rdf.getValueFromNode(
  570. node)){var oldParent=this.bmServ.getParent(node);this.removeBookmark(oldParent,node);this.insertBookmark(parentRes,node,position,opt_type)}}
  571. ;CLB_BookmarkSyncer.prototype.unassertTargets=function(src,prop){var tars=this.bmDS.GetTargets(src,prop,true);while(tars.hasMoreElements()){var tar=tars.getNext();this.bmDS.Unassert(src,prop,tar);G_Debug(this,"removing: src: %s prop: %s tar: %s".subs(src.Value,prop.Value,tar.Value))}}
  572. ;CLB_BookmarkSyncer.prototype.maybeAssert=function(src,prop,tar){if(this.bmDS.HasAssertion(src,prop,tar,true)){return}this.unassertTargets(src,prop);this.bmDS.Assert(src,prop,tar,true)}
  573. ;G_debugService.loggifier.loggify(CLB_BookmarkSyncer.prototype);
  574. function CLB_BrowserOverlay(win){this.win_=win;this.doc_=this.win_.document;this.statusObserver_=this.handleStatusChange_.bind(this,false);this.win_.addEventListener("load",this.handleLoad_.bind(this),false);this.win_.addEventListener("unload",this.handleUnload_.bind(this),false);CLB_syncMan.addObserver(this)}
  575. CLB_BrowserOverlay.IMAGE_ONLINE="chrome://browserstate/content/icon-small.png";CLB_BrowserOverlay.IMAGE_OFFLINE="chrome://browserstate/content/icon-small-disabled.png";CLB_BrowserOverlay.MESSAGE_LOCAL_CHANGES="Your changes will be sent to the server the next time you connect. ";CLB_BrowserOverlay.MESSAGE_KICKED="Google Browser Sync is disconnected because you logged in on a different machine. "+CLB_BrowserOverlay.MESSAGE_LOCAL_CHANGES;CLB_BrowserOverlay.MESSAGE_OFFLINE="Google Browser Sync is offline. "
  576. +CLB_BrowserOverlay.MESSAGE_LOCAL_CHANGES;CLB_BrowserOverlay.MESSAGE_CAPTCHA_REQUIRED="Google Browser Sync is disconnected because your account is temporarily locked. Please verify your account and then reconnect.";CLB_BrowserOverlay.MESSAGE_PING_REDIRECT="Google Browser Sync could not contact the server. Please verify your network settings and then reconnect.";CLB_BrowserOverlay.MESSAGE_SETUP="Your changes are not being saved because Google Browser Sync has not been set up.";CLB_BrowserOverlay.MESSAGE_WELCOME=
  577. "You've successfully installed Google Browser Sync.  Google Browser Sync will continuously synchronize the browser settings you selected. Click on this icon to update your settings and account info.";CLB_BrowserOverlay.WELCOME_URL="http://google.com/";CLB_BrowserOverlay.SETTINGS_DIALOG_WIDTH=450;CLB_BrowserOverlay.SETTINGS_DIALOG_HEIGHT=420;CLB_BrowserOverlay.INFO_BUBBLE_WIDTH=200;CLB_BrowserOverlay.prototype.syncStart=(CLB_BrowserOverlay.prototype.syncFailure=(CLB_BrowserOverlay.prototype.updateProgress=
  578. (CLB_BrowserOverlay.prototype.updateStart=(CLB_BrowserOverlay.prototype.updateFailure=(CLB_BrowserOverlay.prototype.updateComplete=(CLB_BrowserOverlay.prototype.syncProgress=function(){}
  579. ))))));CLB_BrowserOverlay.prototype.syncComplete=function(){this.updateComplete()}
  580. ;CLB_BrowserOverlay.prototype.handleLoad_=function(){this.initializeToolbars_();this.tabBrowser_=this.doc_.getElementById("content");this.toolbarButton_=this.doc_.getElementById("clb-toolbarbutton");this.toolsMenu_=this.doc_.getElementById("clb-toolsmenu");this.menu_=this.doc_.getElementById("clb-menu");this.settingsDlg_=null;this.reconnectItem_=this.doc_.getElementById("clb-status-reconnect");this.settingsItem_=this.doc_.getElementById("clb-status-settings");this.setupItem_=this.doc_.getElementById(
  581. "clb-status-setup");if(CLB_app.prefs.getPref("show-debug-menu",false)){this.doc_.getElementById("clb-debug-menu").hidden=false;this.doc_.getElementById("clb-debug-separator").hidden=false}var updateSleep=CLB_syncMan.updateSleepyState.bind(CLB_syncMan);this.win_.addEventListener("mousedown",updateSleep,false);this.win_.addEventListener("keypress",updateSleep,false);this.win_.addEventListener("focus",updateSleep,false);var nsResolver=function(prefix){return G_FirefoxXMLUtils.XUL_NAMESPACE}
  582. ;var bubbleRoot=G_FirefoxXMLUtils.selectSingleNode(this.doc_,"//xul:vbox[@class='clb-infobubble'][1]",nsResolver);var restoreBubbleRoot=G_FirefoxXMLUtils.selectSingleNode(this.doc_,"//xul:vbox[@class='clb-infobubble'][2]",nsResolver);this.tabWatcher_=new G_TabbedBrowserWatcher(this.tabBrowser_,"browserstate",true);this.infoBubble_=new CLB_InfoBubble(bubbleRoot,this.tabWatcher_,CLB_BrowserOverlay.INFO_BUBBLE_WIDTH);this.tabWatcher_.registerListener("tabload",partial(CLB_app.tabSyncer.onTabLoad,this.win_)
  583. );this.tabWatcher_.registerListener("tabunload",partial(CLB_app.tabSyncer.onTabUnload,this.win_));this.tabWatcher_.registerListener("pageshow",partial(CLB_app.tabSyncer.onPageShow,this.win_));this.tabWatcher_.registerListener("tabswitch",partial(CLB_app.tabSyncer.onTabSwitch,this.win_));this.tabWatcher_.registerListener("tabmove",partial(CLB_app.tabSyncer.onTabMove,this.win_));CLB_app.tabSyncer.onLoad(this.win_);if(CLB_app.getUsername()&&this.toolbarButton_){this.toolbarButton_.label=CLB_app.getUsername(
  584. )}if(CLB_app.errorURL&&!CLB_app.errorURLShown){this.showURL_(CLB_app.errorURL);CLB_app.errorURLShown=true}this.handleStatusChange_(true);this.restoreUI_=new CLB_RestoreTabsUI(this.win_,this.tabBrowser_,restoreBubbleRoot,this.tabWatcher_);this.chord_=new CLB_Chord(this.win_,"clb");this.chord_.onComplete=this.handleChord_.bind(this);this.chord_.start();CLB_app.addStatusObserver(this.statusObserver_);this.win_.setTimeout(this.delayedInit.bind(this),1)}
  585. ;CLB_BrowserOverlay.prototype.delayedInit=function(){this.navToolbox_=this.doc_.getElementById("navigator-toolbox");this.oldToolboxCustomizeDone=this.navToolbox_.customizeDone;this.navToolbox_.customizeDone=this.onToolboxCustomizeDone_.bind(this)}
  586. ;CLB_BrowserOverlay.prototype.onToolboxCustomizeDone_=function(aToolboxChanged){this.toolbarButton_=this.doc_.getElementById("clb-toolbarbutton");if(CLB_app.getUsername()&&this.toolbarButton_){this.toolbarButton_.label=CLB_app.getUsername()}if(!CLB_InfoBubble.allHidden){CLB_InfoBubble.repositionAll(this.toolbarButton_)}this.cloneMenu_();this.oldToolboxCustomizeDone(aToolboxChanged)}
  587. ;CLB_BrowserOverlay.prototype.cloneMenu_=function(){if(this.toolbarButton_){while(this.toolbarButton_.childNodes.length){this.toolbarButton_.removeChild(this.toolbarButton_.childNodes[0])}this.toolbarButton_.appendChild(this.menu_.cloneNode(true))}}
  588. ;CLB_BrowserOverlay.prototype.handleUnload_=function(){CLB_app.removeStatusObserver(this.statusObserver_);CLB_syncMan.removeObserver(this);CLB_app.tabSyncer.onUnload(this.win_)}
  589. ;CLB_BrowserOverlay.prototype.setToolbarButtonImage_=function(img){if(this.toolbarButton_){this.toolbarButton_.image=img}}
  590. ;CLB_BrowserOverlay.prototype.handleStatusChange_=function(opt_isPageLoad){var newStatus=CLB_app.getStatus();G_Debug(this,"Updating status to {%s}. isPageLoad: {%s}".subs(newStatus,opt_isPageLoad));if(!CLB_app.setupIsComplete()){this.setToolbarButtonImage_(CLB_BrowserOverlay.IMAGE_OFFLINE);this.setupItem_.hidden=false;this.settingsItem_.setAttribute("disabled",true);this.reconnectItem_.setAttribute("disabled",true)}else if(CLB_Application.STATUS_ONLINE==newStatus){this.setToolbarButtonImage_(CLB_BrowserOverlay.IMAGE_ONLINE)
  591. ;this.reconnectItem_.setAttribute("disabled",true)}else{this.setToolbarButtonImage_(CLB_BrowserOverlay.IMAGE_OFFLINE);this.reconnectItem_.setAttribute("disabled",false);if(this.settingsDlg_&&this.settingsDlg_.CLB_form){this.settingsDlg_.CLB_form.setOffline()}}this.cloneMenu_();if(!opt_isPageLoad){this.updateBubble_(newStatus,false)}else{this.win_.setTimeout(this.updateBubble_.bind(this,newStatus,true),0)}}
  592. ;CLB_BrowserOverlay.prototype.updateBubble_=function(newStatus,isPageLoad){G_Debug(this,"Updating bubble to status: {%s}".subs(newStatus));if(CLB_Application.STATUS_ONLINE==newStatus){if(CLB_app.prefs.getPref("showWelcome",false)){this.showWelcomeMessage();this.infoBubble_.show(this.toolbarButton_)}else{this.infoBubble_.hide()}CLB_app.prefs.setPref("showWelcome",false);return}this.restoreUI_.hide();this.infoBubble_.clear();if(CLB_Application.STATUS_UPDATE_ERROR==newStatus){G_Debug(this,"Not showing bubble while offline."
  593. );return}if(CLB_Application.STATUS_NEEDS_CAPTCHA==newStatus){this.showCaptchaMessage()}else if(CLB_Application.STATUS_BACKED_OFF==newStatus){this.infoBubble_.setMessage(CLB_Application.MESSAGE_BACKED_OFF)}else if(!CLB_app.setupIsComplete()){this.showSetupMessage()}else if(CLB_Application.STATUS_PING_REDIRECT==newStatus){this.showReconnectMessage(CLB_BrowserOverlay.MESSAGE_PING_REDIRECT)}else if(CLB_Application.STATUS_KICKED==newStatus){this.showReconnectMessage(CLB_BrowserOverlay.MESSAGE_KICKED)}
  594. else if(CLB_Application.STATUS_OFFLINE==newStatus){this.showReconnectMessage(CLB_BrowserOverlay.MESSAGE_OFFLINE)}else{G_DebugL(this,"Unexpected status {%s}. Hiding InfoBubble.".subs(newStatus));this.infoBubble_.hide();return}if(!CLB_InfoBubble.allHidden||!isPageLoad){this.infoBubble_.show(this.toolbarButton_)}}
  595. ;CLB_BrowserOverlay.prototype.handleStatusImageClick=function(event){if(!event.button){this.handleStatusChange_()}}
  596. ;CLB_BrowserOverlay.prototype.showWelcomeLink_=function(){this.showURL_(CLB_BrowserOverlay.WELCOME_URL);CLB_InfoBubble.hideAll()}
  597. ;CLB_BrowserOverlay.prototype.showWelcomeMessage=function(){this.infoBubble_.setMessage(CLB_BrowserOverlay.MESSAGE_WELCOME)}
  598. ;CLB_BrowserOverlay.prototype.showSetupMessage=function(){this.infoBubble_.setMessage(CLB_BrowserOverlay.MESSAGE_SETUP);this.infoBubble_.addButton("Setup Now...",this.startSetup_.bind(this))}
  599. ;CLB_BrowserOverlay.prototype.showCaptchaMessage=function(){this.infoBubble_.setMessage(CLB_BrowserOverlay.MESSAGE_CAPTCHA_REQUIRED)}
  600. ;CLB_BrowserOverlay.prototype.showReconnectMessage=function(message){this.infoBubble_.setMessage(message);this.infoBubble_.addButton("Reconnect",this.startReconnect_.bind(this))}
  601. ;CLB_BrowserOverlay.prototype.showURL_=function(url){this.tabBrowser_.selectedTab=this.tabBrowser_.addTab(url)}
  602. ;CLB_BrowserOverlay.prototype.startSetup_=function(){var promptSvc=Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);if(promptSvc.confirm(null,"Warning","Setting up Google Browser Sync requires closing all open browser windows. OK to proceed?")){CLB_app.logOff()}}
  603. ;CLB_BrowserOverlay.prototype.startReconnect_=function(){CLB_RestoreTabsUI.isReconnecting=true;var args=Cc["@mozilla.org/hash-property-bag;1"].createInstance(Ci.nsIWritablePropertyBag);this.win_.openDialog("chrome://browserstate/content/syncing.xul","clb-syncing","dialog,modal,centerscreen",args)}
  604. ;CLB_BrowserOverlay.prototype.handleSettingsClicked=function(){var left=(this.win_.outerWidth-CLB_BrowserOverlay.SETTINGS_DIALOG_WIDTH)/2+this.win_.screenX;var top=(this.win_.outerHeight-CLB_BrowserOverlay.SETTINGS_DIALOG_HEIGHT)/2+this.win_.screenY;this.settingsDlg_=this.win_.openDialog("chrome://browserstate/content/settings.xul","clb-settings","dialog,modal,left=%s,top=%s".subs(left,top))}
  605. ;CLB_BrowserOverlay.prototype.handleLogOff=function(){CLB_app.setSID(null);CLB_app.logOff()}
  606. ;CLB_BrowserOverlay.prototype.handleShowLogClicked=function(e){this.launchFile_(G_debugService.getLogFile())}
  607. ;CLB_BrowserOverlay.prototype.handleDumpBookmarksClicked=function(e){var ds=Cc["@mozilla.org/rdf/datasource;1?name=bookmarks"].getService(Ci.nsIRDFDataSource);var file=CLB_rdf.writeRdfToFile(ds,0,"bookmarks-dump.txt");this.launchFile_(file)}
  608. ;CLB_BrowserOverlay.prototype.initializeToolbars_=function(){var toolbar;if(CLB_app.isMac()){toolbar=this.doc_.getElementById("PersonalToolbar")}else{toolbar=this.doc_.getElementById("toolbar-menubar")}if(toolbar.hasAttribute("clb-initialized2")){G_Debug(this,"clb-intialized already set. skipping init.");return}var defaultSet=this.insertToolbarItem_(toolbar.getAttribute("defaultset"),CLB_app.isMac());var currentSet;if(toolbar.hasAttribute("currentset")){currentSet=this.insertToolbarItem_(toolbar.getAttribute(
  609. "currentset"),CLB_app.isMac())}else{currentSet=defaultSet}toolbar.collapsed=false;toolbar.currentSet=currentSet;toolbar.setAttribute("currentset",currentSet);toolbar.setAttribute("defaultset",defaultSet);this.doc_.persist(toolbar.id,"defaultset");this.doc_.persist(toolbar.id,"currentset");toolbar.setAttribute("clb-initialized2","1");this.doc_.persist(toolbar.id,"clb-initialized2")}
  610. ;CLB_BrowserOverlay.prototype.insertToolbarItem_=function(prevVals,isMac){var prevVals=prevVals.split(",");var insertPos;if(!isMac&&prevVals[prevVals.length-1]=="throbber-box"){insertPos=prevVals.length-1}else{insertPos=prevVals.length}prevVals.splice(insertPos,0,"clb-toolbarbutton");return prevVals.join(",")}
  611. ;CLB_BrowserOverlay.prototype.launchFile_=function(file){this.showURL_(file.path)}
  612. ;CLB_BrowserOverlay.prototype.handleChord_=function(){this.setToolbarButtonImage_("chrome://browserstate/content/icon.gif")}
  613. ;function CLB_Chord(win,word){bindMethods(this);this.win_=win;this.members_=[];this.currentKey_=0;this.resetAlarm_=null;for(var i=0;i<word.length;i++){this.members_.push(word.charCodeAt(i))}}
  614. CLB_Chord.MAX_DELAY=500;CLB_Chord.prototype.onComplete=function(){}
  615. ;CLB_Chord.prototype.start=function(){this.win_.addEventListener("keypress",this.handleKeyPress_,true)}
  616. ;CLB_Chord.prototype.stop=function(){this.win_.removeEventListener("keypress",this.handleKeyPress_,true)}
  617. ;CLB_Chord.prototype.handleKeyPress_=function(e){if(!(CLB_app.isMac()&&e.ctrlKey||e.altKey)){return}if(this.currentKey_>0){this.resetAlarm_.cancel()}if(this.members_[this.currentKey_]!=e.which){this.reset_();return}this.currentKey_++;if(this.currentKey_<this.members_.length){this.resetAlarm_=new G_Alarm(this.reset_,CLB_Chord.MAX_DELAY);return}e.preventDefault();this.onComplete()}
  618. ;CLB_Chord.prototype.reset_=function(){this.currentKey_=0}
  619. ;CLB_Chord.prototype.debugZone="CLB_Chord";CLB_BrowserOverlay.prototype.debugZone="CLB_BrowserOverlay";G_debugService.loggifier.loggify(CLB_BrowserOverlay.prototype);
  620. function CLB_ComponentSelector(root){this.root_=root;this.doc_=this.root_.ownerDocument;this.win_=this.doc_.defaultView}
  621. CLB_ComponentSelector.prototype.load=function(){this.learnMore_=this.doc_.getElementById("clb-componentselector-learnmore");this.learnMore_.onclick=this.showLearnMore.bind(this);this.list_=this.doc_.getElementById("clb-settings-list");var items=this.list_.getElementsByTagName("listitem");while(items.length>0){this.list_.removeChild(items[0])}var componentIterator=CLB_syncMan.getComponents();var components=[];var component;while(component=componentIterator.getNext()){if(component.QueryInterface){component.QueryInterface(
  622. Ci.GISyncComponent)}if(component.componentID==CLB_SettingsSyncer.CONTRACT_ID){continue}components.push(component)}components.sort(CLB_ComponentSelector.componentSort_);function lookupify(arr){var dict={};for(var i=0;i<arr.length;i++){dict[arr[i]]=true}return dict}
  623. var syncedComponents=lookupify(CLB_app.getListPref("syncedComponents"));var encryptedComponents=lookupify(CLB_app.getListPref("encryptedComponents"));for(var i=0;component=components[i];i++){this.list_.appendChild(this.createSettingsListItem_(component,syncedComponents[component.componentID],encryptedComponents[component.componentID]))}this.checkCheckboxState()}
  624. ;CLB_ComponentSelector.prototype.save=function(){var result=this.getChoices();CLB_app.setListPref("syncedComponents",result.syncedComponents);CLB_app.setListPref("encryptedComponents",result.encryptedComponents)}
  625. ;CLB_ComponentSelector.prototype.getChoices=function(){this.list_=this.doc_.getElementById("clb-settings-list");var item;var checkbox1;var checkbox2;var syncedComponents=[];var encryptedComponents=[];var items=this.list_.getElementsByTagName("listitem");for(var i=0;item=items[i];i++){checkbox1=item.getElementsByTagName("checkbox")[0];checkbox2=item.getElementsByTagName("checkbox")[1];if(checkbox1.checked){syncedComponents.push(item.__componentID);if(checkbox2.checked){encryptedComponents.push(item.__componentID)
  626. }}}return{syncedComponents:syncedComponents,encryptedComponents:encryptedComponents}}
  627. ;CLB_ComponentSelector.prototype.isValid=function(){var items=this.list_.getElementsByTagName("listitem");for(var i=0,item;item=items[i];i++){var checkbox1=item.getElementsByTagName("checkbox")[0];if(checkbox1.checked){G_Debug(this,"A check box was checked");return true}}G_Debug(this,"No checkboxes were checked");return false}
  628. ;CLB_ComponentSelector.prototype.checkCheckboxState=function(){this.settingsChanged(this.isValid())}
  629. ;CLB_ComponentSelector.prototype.settingsChanged=function(){}
  630. ;CLB_ComponentSelector.prototype.createSettingsListItem_=function(component,synced,encrypted){var item=this.doc_.createElement("listitem");item.setAttribute("allowevents","true");item.__componentID=component.componentID;var nameCell=this.doc_.createElement("listcell");nameCell.setAttribute("label",component.componentName);item.appendChild(nameCell);var enabledCell=this.doc_.createElement("listcell");var enabledCheckbox=this.doc_.createElement("checkbox");if(synced){enabledCheckbox.setAttribute("checked"
  631. ,"true")}enabledCell.appendChild(enabledCheckbox);enabledCheckbox.addEventListener("command",this.checkCheckboxState.bind(this),false);item.appendChild(enabledCell);var encryptionCell=this.doc_.createElement("listcell");var encryptionCheckbox=this.doc_.createElement("checkbox");var disabledEncryptionCheckbox=this.doc_.createElement("checkbox");encryptionCheckbox.checked_=encrypted;disabledEncryptionCheckbox.setAttribute("disabled",true);disabledEncryptionCheckbox.collapsed=true;var checkboxStateChangeHandler=
  632. (function(){G_Debug(this,"enabled checkbox changed. checked: {%s}".subs(enabledCheckbox.getAttribute("checked")));if(enabledCheckbox.getAttribute("checked")){if(component.encryptionRequired){encryptionCheckbox.setAttribute("checked",true);disabledEncryptionCheckbox.setAttribute("checked",true);disabledEncryptionCheckbox.setAttribute("label","(always)");disabledEncryptionCheckbox.setAttribute("class","labelled");disabledEncryptionCheckbox.collapsed=false;encryptionCheckbox.collapsed=true}else{encryptionCheckbox.setAttribute(
  633. "checked",encryptionCheckbox.checked_);encryptionCheckbox.collapsed=false;disabledEncryptionCheckbox.collapsed=true}}else{if(component.encryptionRequired){disabledEncryptionCheckbox.setAttribute("label","");disabledEncryptionCheckbox.setAttribute("class","")}encryptionCheckbox.collapsed=true;disabledEncryptionCheckbox.setAttribute("checked",false);disabledEncryptionCheckbox.collapsed=false;encryptionCheckbox.checked_=encryptionCheckbox.checked;encryptionCheckbox.setAttribute("checked",false)}}
  634. ).bind(this);enabledCheckbox.addEventListener("CheckboxStateChange",checkboxStateChangeHandler,false);encryptionCell.appendChild(encryptionCheckbox);encryptionCell.appendChild(disabledEncryptionCheckbox);item.appendChild(encryptionCell);checkboxStateChangeHandler();return item}
  635. ;CLB_ComponentSelector.prototype.showLearnMore=function(){var width=300;var height=300;var left=this.win_.screenX+(this.win_.outerWidth-width)/2;var top=this.win_.screenY+(this.win_.outerHeight-height)/2;this.win_.open("chrome://browserstate/content/learnmore2.html","learnmore","width=%s,height=%s,left=%s,top=%s,scrollbars=yes,chrome,dialog".subs(width,height,left,top))}
  636. ;CLB_ComponentSelector.prototype.debugZone="CLB_ComponentSelector";G_debugService.loggifier.loggify(CLB_ComponentSelector.prototype);CLB_ComponentSelector.componentSort_=function(a,b){a=Number(!a.encryptionRequired)+a.componentName.toLowerCase();b=Number(!b.encryptionRequired)+b.componentName.toLowerCase();if(a>b){return 1}else if(a<b){return-1}else{return 0}}
  637. ;
  638. CLB_Conflict.CONFLICT_VALUE_SEPARATOR=",";function CLB_Conflict(name,typeID,props){this.name=name;this.typeID=typeID;this.props_=props;this.conflictValues_={}}
  639. CLB_Conflict.prototype.cloneWithoutValues=function(){return new CLB_Conflict(this.name,this.typeID,this.props_)}
  640. ;CLB_Conflict.prototype.makeConflictValueString=function(item){if(item.isRemove){return""}if(this.typeID!=null&&(!isDef(item.typeID)||this.typeID!=item.typeID)){return""}var missingProp=false;var valueArray=[];for(var i=0;i<this.props_.length;i++){var prop=this.props_[i];if(!item.hasProperty(prop)){missingProp=true;G_Debug(this,"Warning: item "+item.itemID+" doesn't have prop "+prop+" needed for conflict resolution")}else{valueArray.push(item.getProperty(prop))}}if(missingProp&&parseInt(valueArray.length)
  641. >0){G_Debug(this,"Error: cannot create conflict string for item "+item.itemID+" because only some required fields are present.");return null}return valueArray.join(CLB_Conflict.CONFLICT_VALUE_SEPARATOR)}
  642. ;CLB_Conflict.prototype.addConflictValue=function(conflictValue,lookupKey){if(conflictValue==""||isNull(conflictValue)){return}if(isDef(this.conflictValues_[conflictValue])&&this.conflictValues_[conflictValue]!=lookupKey){G_Debug(this,"Error: same conflict value: "+conflictValue+" found for "+lookupKey+" and "+this.conflictValues_[conflictValue]);return}this.conflictValues_[conflictValue]=lookupKey}
  643. ;CLB_Conflict.prototype.removeConflictValue=function(conflictValue,lookupKey){if(conflictValue==""||isNull(conflictValue)){return}if(isDef(this.conflictValues_[conflictValue])&&this.conflictValues_[conflictValue]==lookupKey){delete this.conflictValues_[conflictValue]}else{G_Debug(this,"Warning: trying to delete a conflict value that does not exist for conflict "+this.name)}}
  644. ;CLB_Conflict.prototype.updateConflictValues=function(oldItem,newItem){var lookupKey=oldItem.makeLookupKey();var newLookupKey=newItem.makeLookupKey();if(lookupKey!=newLookupKey){G_Debug(this,"Error: cannot update conflict values for two different items: "+lookupKey+" and "+newLookupKey);return}var oldConflictValue=this.makeConflictValueString(oldItem);var conflictValue=this.makeConflictValueString(newItem);if(newItem.isRemove){this.removeConflictValue(oldConflictValue,lookupKey)}else{if(oldConflictValue!=
  645. conflictValue){this.removeConflictValue(oldConflictValue,lookupKey);this.addConflictValue(conflictValue,lookupKey)}}}
  646. ;CLB_Conflict.prototype.maybeDeleteConflictValues=function(oldItem,newUpdate){var conflictValue=this.makeConflictValueString(newUpdate);if(newUpdate.isRemove||!isNull(conflictValue)&&conflictValue!=""){var oldConflictValue=this.makeConflictValueString(oldItem);var lookupKey=oldItem.makeLookupKey();this.removeConflictValue(oldConflictValue,lookupKey);G_Debug(this,"New conflict value: "+conflictValue);G_Debug(this,"Removed conflict value: "+oldConflictValue)}}
  647. ;CLB_Conflict.prototype.hasConflictValue=function(conflictValue){return isDef(this.conflictValues_[conflictValue])}
  648. ;CLB_Conflict.prototype.getLookupKey=function(conflictValue){return this.conflictValues_[conflictValue]}
  649. ;
  650. function CLB_ConflictResolver(registeredConflicts,componentsHash,sendToServerQueue,applyLocallyQueue){this.initializeRegisteredConflicts(registeredConflicts);this.componentsHash_=componentsHash;this.sendToServerQueue_=sendToServerQueue;this.applyLocallyQueue_=applyLocallyQueue}
  651. CLB_ConflictResolver.prototype.initializeRegisteredConflicts=function(registeredConflicts){this.registeredConflicts_={};for(var componentID in registeredConflicts){var conflicts=registeredConflicts[componentID];var clonedConflicts=[];conflicts.forEach(function(conflict){clonedConflicts.push(conflict.cloneWithoutValues())}
  652. ,this);this.registeredConflicts_[componentID]=clonedConflicts}}
  653. ;CLB_ConflictResolver.prototype.addToConflictMaps=function(item){if(item.isRemove){return}var conflicts=this.registeredConflicts_[item.componentID];if(isDef(conflicts)){conflicts.forEach(function(conflict){var conflictValue=conflict.makeConflictValueString(item);if(conflictValue==null){G_Debug(this,"Error: Cannot perform conflict resolution on item "+item.itemID+" because a partial update contains only some of the properties required for conflict"+conflict.name)}else{var lookupKey=item.makeLookupKey(
  654. );conflict.addConflictValue(conflictValue,lookupKey);G_Debug(this,"Adding value for conflict type: "+conflict.name)}}
  655. ,this)}}
  656. ;CLB_ConflictResolver.prototype.updateConflictMaps=function(items,isUpdate){items.forEach(function(item){var conflicts=this.registeredConflicts_[item.componentID];if(isDef(conflicts)){var lookupKey=item.makeLookupKey();var oldItem=this.findInLocalOrServerQueue(lookupKey);if(!oldItem||oldItem.isRemove){this.addToConflictMaps(item)}else{var newItem;if(isUpdate){newItem=oldItem.clone();CLB_UpdateQueue.smooshItems(newItem,item)}else{newItem=item}conflicts.forEach(function(conflict){conflict.updateConflictValues(
  657. oldItem,newItem)}
  658. ,this)}}}
  659. ,this)}
  660. ;CLB_ConflictResolver.prototype.maybeDeleteConflictValues=function(oldItem,update){var conflicts=this.registeredConflicts_[oldItem.componentID];if(conflicts){conflicts.forEach(function(conflict){conflict.maybeDeleteConflictValues(oldItem,update)}
  661. ,this)}}
  662. ;CLB_ConflictResolver.prototype.findInLocalOrServerQueue=function(lookupKey){var item=this.applyLocallyQueue_.getItemByLookupKey(lookupKey);if(item==null){item=this.sendToServerQueue_.getItemByLookupKey(lookupKey)}return item}
  663. ;CLB_ConflictResolver.prototype.smooshWithOffline=function(syncedItem){var itemsEqual=false;var syncedLookupKey=syncedItem.makeLookupKey();G_Debug(this,"Synced item lookup key: "+syncedLookupKey);var offlineItem=this.sendToServerQueue_.getItemByLookupKey(syncedLookupKey);if(offlineItem!=null){G_Debug(this,"Found offline item, smooshing");if(syncedItem.isRemove&&!offlineItem.isRemove){var comp=this.componentsHash_[offlineItem.componentID];var compItem=comp.getItemByID(offlineItem.itemID,offlineItem.typeID)
  664. ;if(!compItem){G_Debug(this,"Warning - component returned null for getItemByID, continuing with an item that might be a partial update")}else{if(compItem.itemID!=offlineItem.itemID||compItem.typeID!=offlineItem.typeID){G_Debug(this,"Error, component returned an item with a different  id or typeID, continuing with an item that might be  a partial update")}else{offlineItem=compItem;this.updateConflictMaps([offlineItem],false);this.sendToServerQueue_.replaceItem(offlineItem)}}}var changed=CLB_UpdateQueue.smooshItems(
  665. syncedItem,offlineItem);if(!changed){this.sendToServerQueue_.deleteItemByLookupKey(syncedLookupKey);if(syncedItem.equals(offlineItem)){itemsEqual=true}}}return itemsEqual}
  666. ;CLB_ConflictResolver.prototype.resolveItemConflicts=function(syncedItem,conflict,resolvedItems){var syncedLookupKey=syncedItem.makeLookupKey();var conflictValue=conflict.makeConflictValueString(syncedItem);G_Debug(this,"Conflict: "+conflict.name+" value: "+conflictValue);if(conflictValue==""||!conflict.hasConflictValue(conflictValue)){return false}if(conflictValue==null){G_Debug(this,"Error: Cannot perform conflict resolution on item "+syncedItem.itemID+" because a partial update contains only some of the properties required for conflict"
  667. +conflict.name);return false}var conflictLookupKey=conflict.getLookupKey(conflictValue);if(conflictLookupKey==syncedLookupKey){G_Debug(this,"Skipping conflict on value: "+conflictValue+" because items have the same lookupID: "+syncedLookupKey);return false}var conflictItem=this.findInLocalOrServerQueue(conflictLookupKey);if(!conflictItem){G_Debug(this,"Error: Could not find item in updateQueue and syncQueue for lookup key: "+conflictLookupKey);return false}var comp=this.componentsHash_[syncedItem.componentID]
  668. ;var resolvedEnum=comp.onItemConflict(conflict.name,syncedItem,conflictItem.clone());var newLookup=syncedItem.makeLookupKey();if(newLookup!=syncedLookupKey){G_Debug(this,"Error, component changed syncItem lookup value. This should never happen - instead, component should  return the item with a different ID in the enumerator")}while(resolvedEnum.hasMoreElements()){var resolved=resolvedEnum.getNext();if(resolved.itemID==syncedItem.itemID){G_Debug(this,"Error: component should not return an update to the  synced item - it should modify the item directly"
  669. )}else{resolvedItems.push(resolved)}}G_Debug(this,"Total items returned for conflict resolution: "+resolvedItems.length);return true}
  670. ;CLB_ConflictResolver.prototype.resolveConflicts=function(syncedItem,isDownloaded){var shouldUploadItem=!isDownloaded;var syncedLookupKey=syncedItem.makeLookupKey();G_Debug(this,"Synced item lookup key: "+syncedLookupKey);if(!isDownloaded){var previousUpdate=this.findInLocalOrServerQueue(syncedLookupKey);if(previousUpdate!=null){G_Debug(this,"Found previous update, smooshing");var tmp=previousUpdate.clone();CLB_UpdateQueue.smooshItems(tmp,syncedItem);syncedItem.updateFrom(tmp)}}var resolvedItems=
  671. [];var conflicts=this.registeredConflicts_[syncedItem.componentID];if(isDef(conflicts)){conflicts.forEach(function(conflict){var foundConflict=this.resolveItemConflicts(syncedItem,conflict,resolvedItems);shouldUploadItem=shouldUploadItem||foundConflict}
  672. ,this)}resolvedItems.forEach(function(itemUpdate){var lookupKey=itemUpdate.makeLookupKey();var previousUpdate=this.findInLocalOrServerQueue(lookupKey);if(!isNull(previousUpdate)){this.maybeDeleteConflictValues(previousUpdate,itemUpdate)}}
  673. ,this);this.updateConflictMaps([syncedItem],false);if(shouldUploadItem){G_Debug(this,"Uploading the synced item to the server, since it changed");this.sendToServerQueue_.replaceItem(syncedItem)}G_Debug(this,"Returning "+resolvedItems.length+" extra items");return resolvedItems}
  674. ;CLB_ConflictResolver.prototype.debugZone="CLB_ConflictResolver";G_debugService.loggifier.loggify(CLB_ConflictResolver.prototype);
  675. function CLB_CookieEnumerator(){var cm=Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);this.e_=cm.enumerator;this.advanceToNext_()}
  676. CLB_CookieEnumerator.prototype.QueryInterface=function(iid){if(iid.equals(Ci.nsISupports)||iid.equals(Ci.nsISimpleEnumerator)){return this}else{throw Components.results.NS_ERROR_NO_INTERFACE;}}
  677. ;CLB_CookieEnumerator.prototype.hasMoreElements=function(){return this.next_!=null}
  678. ;CLB_CookieEnumerator.prototype.getNext=function(){var retVal=this.next_;this.advanceToNext_();return retVal}
  679. ;CLB_CookieEnumerator.prototype.advanceToNext_=function(){this.next_=null;while(this.next_==null&&this.e_.hasMoreElements()){var cookie=this.e_.getNext();cookie.QueryInterface(Ci.nsICookie);this.next_=CLB_CookieSyncer.createSyncItem(cookie)}}
  680. ;CLB_CookieEnumerator.prototype.debugZone="CLB_CookieEnumerator";G_debugService.loggifier.loggify(CLB_CookieEnumerator.prototype);
  681. function CLB_CookieSyncer(){this.observersSetup_=false;this.lastSyncedCookies_=null;this.talkingToServer_=false;this.prefs=new G_Preferences("network.cookie.");this.cookiesEnabled=this.prefs.getPref("cookieBehaviour",0)==0;this.cookieSvc_=Cc["@mozilla.org/cookieService;1"].getService(Ci.nsICookieService);this.cookieMan_=Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);this.obsSvc_=Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);this.ioSvc_=Cc["@mozilla.org/network/io-service;1"
  682. ].getService(Ci.nsIIOService)}
  683. CLB_CookieSyncer.prototype.componentID="@google.com/browserstate/cookie-syncer;1";CLB_CookieSyncer.prototype.syncBehavior=Ci.GISyncComponent.SYNC_SINCE_LAST_UPDATE;CLB_CookieSyncer.prototype.componentName="Cookies";CLB_CookieSyncer.prototype.encryptionRequired=true;CLB_CookieSyncer.prototype.syncOfflineChanges=true;CLB_CookieSyncer.prototype.updateStart=(CLB_CookieSyncer.prototype.syncStart=function(){this.talkingToServer_=true;G_Debug(this,"Set talkingToServer to true")}
  684. );CLB_CookieSyncer.prototype.updateComplete=(CLB_CookieSyncer.prototype.updateFailure=(CLB_CookieSyncer.prototype.syncComplete=(CLB_CookieSyncer.prototype.syncFailure=function(){this.talkingToServer_=false;G_Debug(this,"Set talkingToServer to false")}
  685. )));CLB_CookieSyncer.prototype.syncProgress=(CLB_CookieSyncer.prototype.updateProgress=function(){}
  686. );CLB_CookieSyncer.prototype.start=function(){if(!this.observersSetup_){this.obsSvc_.addObserver(this,"cookie-changed",false);CLB_syncMan.addObserver(this);this.observersSetup_=true}this.initLastSyncedCookies_()}
  687. ;CLB_CookieSyncer.prototype.stop=function(){if(this.observersSetup_){this.obsSvc_.removeObserver(this,"cookie-changed");this.observersSetup_=false}}
  688. ;CLB_CookieSyncer.prototype.initLastSyncedCookies_=function(){if(!isNull(this.lastSyncedCookies_)){G_Debug(this,"lastSyncedCookies_ already initialized. Skipping.");return}G_Debug(this,"Initializing lastSyncedCookies");this.lastSyncedCookies_={};var cookies=new CLB_CookieEnumerator;while(cookies.hasMoreElements()){var cookie=cookies.getNext();this.lastSyncedCookies_[cookie.itemID]=cookie}}
  689. ;CLB_CookieSyncer.prototype.observe=function(cookie,topic,data){G_Debug(this,"caught topic/data {%s/%s}".subs(topic,data));if(topic!="cookie-changed"){G_Debug(this,"Skipping unexpected topic {%s}".subs(topic));return}if(data=="cleared"){G_Debug(this,"Sending removes for {%s} known cookies".subs(this.lastSyncedCookies_.__count__));for(var itemID in this.lastSyncedCookies_){CLB_syncMan.update(new CLB_SyncItem({itemID:itemID,componentID:this.componentID,isRemove:true}))}this.lastSyncedCookies_={};return}
  690. cookie.QueryInterface(Ci.nsICookie);var syncItem;if(this.talkingToServer_&&cookie.host==".google.com"&&cookie.name=="PREF"){G_Debug(this,"Skipping google PREF cookie during update");return}if(data=="deleted"){syncItem=CLB_CookieSyncer.createBlankSyncItem(cookie);syncItem.isRemove=true;if(syncItem){G_Debug(this,"Sending delete: "+syncItem);CLB_syncMan.update(syncItem);delete this.lastSyncedCookies_[syncItem.itemID]}return}if(data=="added"||data=="changed"){syncItem=CLB_CookieSyncer.createSyncItem(
  691. cookie);if(syncItem){G_Debug(this,"Sending update: "+syncItem);CLB_syncMan.update(syncItem);this.lastSyncedCookies_[syncItem.itemID]=syncItem.clone()}return}G_DebugL(this,"ERROR: Unexpected value for data parameter {%s}".subs(data))}
  692. ;CLB_CookieSyncer.prototype.onItemDownloaded=function(item){}
  693. ;CLB_CookieSyncer.prototype.onBeforeResolveConflict=function(item){}
  694. ;CLB_CookieSyncer.prototype.onItemConflict=function(conflict,oldItem,newItem){}
  695. ;CLB_CookieSyncer.prototype.getItemByID=function(id,typeID){return null}
  696. ;CLB_CookieSyncer.prototype.onItemAvailable=function(syncItem){G_Debug(this,"CLB_CookieSyncer onItemAvailable: "+syncItem);if(syncItem.isRemove){this.removeCookie(syncItem)}else{this.setCookie(syncItem)}}
  697. ;CLB_CookieSyncer.prototype.getCurrentItems=function(){return new CLB_CookieEnumerator}
  698. ;CLB_CookieSyncer.prototype.beforeUpdate=function(){}
  699. ;CLB_CookieSyncer.prototype.resolveConflict=function(conflict,oldItem,newItem){}
  700. ;CLB_CookieSyncer.prototype.setCookie=function(syncItem){if(!syncItem.hasProperty("host")||!syncItem.hasProperty("isSecure")||!syncItem.hasProperty("name")||!syncItem.hasProperty("isDomain")||!syncItem.hasProperty("path")||!syncItem.hasProperty("value")){G_DebugL(this,"ERROR: Received invalid cookie syncItem {%s}".subs(syncItem));return}this.initLastSyncedCookies_();var host=syncItem.getProperty("host").replace(/^\./,"");var protocol=syncItem.getProperty("isSecure")=="true"?"https":"http";var sUri=
  701. protocol+"://"+host+"/";var uri=this.ioSvc_.newURI(sUri,null,null);var cookie=this.getCookieString_(syncItem);G_Debug(this,"setCookie - sUri: "+sUri);G_Debug(this,"setCookie - cookie: "+cookie);this.cookieSvc_.setCookieString(uri,null,cookie,null);this.lastSyncedCookies_[syncItem.itemID]=syncItem.clone()}
  702. ;CLB_CookieSyncer.prototype.removeCookie=function(syncItem){G_Debug(this,"Removing cookie: "+syncItem);this.initLastSyncedCookies_();var candidate=this.lastSyncedCookies_[syncItem.itemID];if(!candidate){G_DebugL(this,"WARNING: Could not find cookie. Ignoring.");return}if(!candidate.hasProperty("host")||!candidate.hasProperty("name")||!candidate.hasProperty("path")){G_Debug(this,"ERROR: Incomplete candidate returned from cookie "+"enumerator. Ignoring. Item returned: {%s}".subs(candidate));return}
  703. this.cookieMan_.remove(candidate.getProperty("host"),candidate.getProperty("name"),candidate.getProperty("path"),false);G_Debug(this,"Found and removed cookie.");delete this.lastSyncedCookies_[syncItem.itemID]}
  704. ;CLB_CookieSyncer.prototype.removeAllCookies=function(){this.cookieMan_.removeAll()}
  705. ;CLB_CookieSyncer.prototype.getCookieString_=function(syncItem){var s=syncItem.getProperty("name")+"="+syncItem.getProperty("value");if(syncItem.hasProperty("expires")&&syncItem.getProperty("expires")!="0"){var expires=Number(syncItem.getProperty("expires"));var d=new Date(expires*1000);s+="; expires="+d.toUTCString()}if(syncItem.getProperty("isDomain")=="true"){s+="; domain="+syncItem.getProperty("host").substring(1)}if(syncItem.hasProperty("path")){s+="; path="+syncItem.getProperty("path")}if(syncItem.getProperty(
  706. "isSecure")=="true"){s+="; secure"}return s}
  707. ;CLB_CookieSyncer.createSyncItem=function(cookie){if(cookie.expires==0){G_Debug(this,"Skipping session cookie: {%s %s %s}".subs(cookie.host,cookie.path,cookie.name));return null}var item=CLB_CookieSyncer.createBlankSyncItem(cookie);var fields=["name","value","host","isDomain","path","isSecure","expires"];for(var i=0,field;field=fields[i];i++){field=fields[i];item.setProperty(field,cookie[field])}return item}
  708. ;CLB_CookieSyncer.createBlankSyncItem=function(cookie){return new CLB_SyncItem({componentID:CLB_CookieSyncer.prototype.componentID,itemID:CLB_CookieSyncer.createItemId_(cookie)})}
  709. ;CLB_CookieSyncer.createItemId_=function(cookie){return[cookie.name,cookie.host,cookie.path,String(Number(cookie.isSecure))].join("\t")}
  710. ;CLB_CookieSyncer.prototype.debugZone="CLB_CookieSyncer";G_debugService.loggifier.loggify(CLB_CookieSyncer.prototype);
  711. var CLB_Crypter={};CLB_Crypter.uniqueCount_=0;CLB_Crypter.startDate_=null;CLB_Crypter.cache_={};CLB_Crypter.debugZone="CLB_Crypter";CLB_Crypter.DELIMITER="|";CLB_Crypter.VERSION_DELIMITER="*";CLB_Crypter.unicodeConverter=Cc["@mozilla.org/intl/scriptableunicodeconverter"].getService(Ci.nsIScriptableUnicodeConverter);CLB_Crypter.unicodeConverter.charset="UTF-8";CLB_Crypter.toByteArray=function(str){return this.unicodeConverter.convertToByteArray(str,{})}
  712. ;CLB_Crypter.fromByteArray=function(bytes){return this.unicodeConverter.convertFromByteArray(bytes,bytes.length)}
  713. ;CLB_Crypter.decryptString=function(str,key){if(!isString(str)){G_Debug(this,"Error: decryptString expected a string");return""}var versionSplit=str.split(CLB_Crypter.VERSION_DELIMITER);str=versionSplit[0];if(versionSplit.length==1||versionSplit[1]=="1"){var crypter=new ARC4;var split=str.split(CLB_Crypter.DELIMITER);var salt=split[1];str=split[0];if(salt){key+=salt}if(str.length%4!=0){G_Debug(this,"ERROR: String '%s' was not of correct length".subs(str));throw new Error("Length of encoded data must be zero mod four"
  714. );}if(!salt&&CLB_Crypter.cache_[str]){return CLB_Crypter.cache_[str]}var strArr=CLB_app.base64r.decodeString(str);crypter.setKey(CLB_app.base64r.arrayifyString(key));crypter.discard(CLB_app.CRYPT_DISCARD_BYTES);crypter.crypt(strArr);var result=CLB_app.base64r.stringifyArray(strArr);if(!salt){CLB_Crypter.cache_[str]=result}return result}else if(versionSplit[1]=="2"){var crypter=new ARC4;var split=str.split(CLB_Crypter.DELIMITER);var salt=split[1];str=split[0];if(salt){key+=salt}if(str.length%4!=0)
  715. {G_Debug(this,"ERROR: String '%s' was not of correct length".subs(str));throw new Error("Length of encoded data must be zero mod four");}if(!salt&&CLB_Crypter.cache_[str]){return CLB_Crypter.cache_[str]}var strArr=CLB_app.base64r.decodeString(str);crypter.setKey(CLB_Crypter.toByteArray(key));crypter.discard(CLB_app.CRYPT_DISCARD_BYTES);crypter.crypt(strArr);var result=CLB_Crypter.fromByteArray(strArr);if(!salt){CLB_Crypter.cache_[str]=result}return result}else{G_DebugL(this,"Error: unknown encryption version encountered"
  716. );throw new Error("Unknown encryption version encountered");}}
  717. ;CLB_Crypter.encryptString=function(str,key,opt_salt){if(typeof str=="number"){str=String(str)}else if(!isString(str)){G_Debug(this,"Error: encryptString expected a string");return""}if(!str){return""}if(!opt_salt&&CLB_Crypter.cache_[str]){return CLB_Crypter.cache_[str]}var strArr=this.toByteArray(str);if(opt_salt){var salt=[];if(isNull(CLB_Crypter.startDate_)){var quotient=(new Date).getTime();var res=[];while(quotient!=0){var remainder=quotient%64;quotient=Math.floor(quotient/64);res.push(G_Base64.ENCODED_VALS.charAt(
  718. remainder))}CLB_Crypter.startDate_=res.join("")}salt.push(CLB_Crypter.startDate_);salt.push(CLB_Crypter.uniqueCount_++);for(var i=0;i<5;i++){salt.push(G_Base64.ENCODED_VALS.charAt(Math.floor(Math.random()*(G_Base64.ENCODED_VALS.length-1))))}salt=salt.join("");key+=salt}var crypter=new ARC4;crypter.setKey(CLB_Crypter.toByteArray(key));crypter.discard(CLB_app.CRYPT_DISCARD_BYTES);crypter.crypt(strArr);var output=CLB_app.base64r.encodeByteArray(strArr);if(opt_salt){output+=CLB_Crypter.DELIMITER+salt+
  719. CLB_Crypter.VERSION_DELIMITER+"2"}else{output+=CLB_Crypter.VERSION_DELIMITER+"2";CLB_Crypter.cache_[str]=output}return output}
  720. ;bindMethods(CLB_Crypter);
  721. function CLB_Downloader(componentsHash,componentsToSync,registeredConflicts,newUpdates,prevLastUpdate,prevLastSync,onSuccess,onFailure,onProgress){bindMethods(this);this.componentsHash=componentsHash;this.componentsToSync={};if(componentsToSync){for(var i=0;i<componentsToSync.length;i++){this.componentsToSync[componentsToSync[i]]=true}}this.prevLastUpdate=prevLastUpdate;this.prevLastSync=prevLastSync;this.newTimestamp=null;this.onProgress=onProgress;this.onSuccess=onSuccess;this.onFailure=onFailure;
  722. this.reqs=[];this.downloadedItems=[];this.parsedSyncItems=new CLB_UpdateQueue;this.applyLocallyQueue=new CLB_UpdateQueue;this.localIndex=0;this.sendToServerQueue=new CLB_UpdateQueue;this.serverQueueIndex=0;this.conflictResolver=new CLB_ConflictResolver(registeredConflicts,this.componentsHash,this.sendToServerQueue,this.applyLocallyQueue);this.funQueue=new G_WorkQueue;this.funQueue.onError=this.handleWorkQueueError;if(newUpdates!=null){G_Debug(this,"newUpdates specified. Parsing offline changes.")
  723. ;this.newUpdates=newUpdates;this.funQueue.addJob(this.parseOfflineItems)}else{G_Debug(this,"Warning: Not initializing updater - download only mode");this.funQueue.addJob(this.sendSyncReqs)}}
  724. CLB_Downloader.prototype.parseOfflineItems=function(){G_Debug(this,"Parsing offline file");if(!CLB_Updater.hasOfflineData()){G_Debug(this,"No offline data to parse, skipping to addNewUpdates");this.onProgress(CLB_Application.PROGRESS_UNOFFLINING,1);this.addNewUpdatesToServerQueue();return}var doc=G_FirefoxXMLUtils.loadXML(CLB_Updater.getOfflineFile());var items=doc.getElementsByTagName("item");var numItems=items.length;var index=0;var cleared=doc.getElementsByTagName("clearedComponents");for(var i=
  725. 0;i<cleared.length;i++){var xmlItem=cleared[i];var child=null;for(var u=0;child=xmlItem.childNodes[u];u++){if(child.localName!="component"){G_Debug(this,"WARNING: item within a <clearedComponents> block was not a <component>");continue}var syncItem=new CLB_SyncItem({isRemoveAll:true});syncItem.componentID=child.textContent;this.sendToServerQueue.addItem(syncItem)}}var parseNext=bind(function(){this.onProgress(CLB_Application.PROGRESS_UNOFFLINING,index/numItems);if(index==numItems){G_Debug(this,"Done parsing offline items. Next up: add new updates to serverqueue."
  726. );this.addNewUpdatesToServerQueue();return}G_Debug(this,"Parsing offline item #{%s}".subs(index));var item=this.parseItem(items[index++]);if(item){var comp=CLB_syncMan.getComponent(item.componentID);if(!comp){G_Debug(this,"WARNING: Skipping offline item for unregistered component. Item: "+item)}else if(!comp.syncOfflineChanges){G_Debug(this,"WARNING: Skipping offline item for component which doesn't sync offine changes. Item: "+item)}else{this.sendToServerQueue.addItem(item)}}this.funQueue.addJob(
  727. parseNext)}
  728. ,this);G_Debug(this,"There are {%s} offline items to parse".subs(numItems));parseNext()}
  729. ;CLB_Downloader.prototype.addNewUpdatesToServerQueue=function(){G_Debug(this,"Adding new updates to server queue...");var index=0;var addNext=bind(function(){if(index==this.newUpdates.length){G_Debug(this,"Done adding new updates. Next up: build conflict maps.");this.onProgress(CLB_Application.PROGRESS_GATHERING,1);this.addPendingToConflictResolver();return}G_Debug(this,"Adding item #{%s} to sendToServerQueue".subs(index));var item=this.newUpdates[index];if(jsInstanceOf(item,Ci.nsISimpleEnumerator)
  730. ){G_Debug(this,"Item is an enumerator... adding child...");if(item.hasMoreElements()){this.sendToServerQueue.addItem(item.getNext())}else{index++}}else{this.sendToServerQueue.addItem(item);index++}this.funQueue.addJob(addNext)}
  731. ,this);G_Debug(this,"There are {%s} updates to add".subs(this.newUpdates.length));addNext()}
  732. ;CLB_Downloader.prototype.addPendingToConflictResolver=function(){G_Debug(this,"Adding pending items to conflict maps");var index=0;var items=this.sendToServerQueue.getPending();var addNext=bind(function(){this.onProgress(CLB_Application.PROGRESS_INDEXING,index/items.length);if(index==items.length){G_Debug(this,"Done adding items to conflict maps. Next up: send sync reqs");this.sendSyncReqs();return}G_Debug(this,"Adding item #{%s} to conflict map".subs(index));this.conflictResolver.addToConflictMaps(
  733. items[index++]);this.funQueue.addJob(addNext)}
  734. ,this);G_Debug(this,"There are {%s} items to add".subs(items.length));addNext()}
  735. ;CLB_Downloader.prototype.sendSyncReqs=function(){G_Debug(this,"Sending sync requests");this.onProgress(CLB_Application.PROGRESS_DOWNLOADING,0);var lastSyncComponents=[];var lastUpdateComponents=[];var everythingComponents=[];for(var component in this.componentsHash){if(this.componentsToSync[component]){everythingComponents.push(this.componentsHash[component].componentID)}else if(this.componentsHash[component].syncBehavior==Ci.GISyncComponent.SYNC_SINCE_LAST_SYNC){lastSyncComponents.push(this.componentsHash[
  736. component].componentID)}else{lastUpdateComponents.push(this.componentsHash[component].componentID)}}if(everythingComponents.length>0){G_Debug(this,"Sending a request for everything from components: "+everythingComponents.join(","));this.sendSyncReq(everythingComponents,(new Date(0)).toISO8601String())}if(lastSyncComponents.length>0){G_Debug(this,"Sending a request for deltas since last sync from components: "+lastSyncComponents.join(","));this.sendSyncReq(lastSyncComponents,this.prevLastSync)}if(
  737. lastUpdateComponents.length>0){G_Debug(this,"Sending a request for deltas since last update from components: "+lastUpdateComponents.join(","));this.sendSyncReq(lastUpdateComponents,this.prevLastUpdate)}if(!lastUpdateComponents.length&&!lastSyncComponents.length&&!everythingComponents.length){G_Debug(this,"No components to be sent");this.resolveConflicts()}}
  738. ;CLB_Downloader.prototype.sendSyncReq=function(components,timestamp){var doc=CLB_XMLUtils.getDoc("SyncRequest",{uid:CLB_app.getSID(),mid:CLB_app.getMID(),key:CLB_app.getEncryptedKey()});CLB_XMLUtils.addElm(doc.documentElement,"timestamp",timestamp);var componentsElm=doc.createElement("components");doc.documentElement.appendChild(componentsElm);for(var i=0;i<components.length;i++){CLB_XMLUtils.addElm(componentsElm,"component",components[i])}G_Debug(this,"Sending sync request with document:\n"+G_FirefoxXMLUtils.getXMLString(
  739. doc));var req=CLB_RequestFactory.getRequest(CLB_RequestFactory.SYNC,null,this.onLoad,this.onError);req.send(doc);this.reqs.push(req)}
  740. ;CLB_Downloader.prototype.onError=function(code,status,message){G_Debug(this,"Got error during download. Code: %s, status: %s, message: %s".subs(code,status,message));this.abort();this.onFailure(code,status,message)}
  741. ;CLB_Downloader.prototype.onLoad=function(req){try{if(CLB_app.prefs.getPref("log-xml",false)){var file=CLB_app.getUniqueTempFile("download","xml");G_FileWriter.writeAll(file,req.responseText);G_Debug(this,"logged download in file: "+file.path)}var items=req.responseXML.getElementsByTagName("item");G_Debug(this,"Number of items downloaded: {%s}".subs(items.length));this.newTimestamp=CLB_XMLUtils.getTimestamp(req.responseXML);for(var i=0;i<items.length;i++){this.downloadedItems.push(items[i])}this.reqs.splice(
  742. this.reqs.indexOf(req),1);if(this.reqs.length>0){return}this.onProgress(CLB_Application.PROGRESS_DOWNLOADING,1);G_Debug(this,"Total number of items downloaded: {%s}".subs(this.downloadedItems.length));this.parseDownloadedItems()}catch(e){this.onFailure(-1,"Unexpected error",e.toString());throw e;}}
  743. ;CLB_Downloader.prototype.parseDownloadedItems=function(){G_Debug(this,"Parsing downloaded items");var index=0;var parseNext=bind(function(){this.onProgress(CLB_Application.PROGRESS_PARSING,index/this.downloadedItems.length);if(index==this.downloadedItems.length){G_Debug(this,"Done parsing items. Next up: resolve conflicts");this.smooshDownloadedWithOffline();return}G_Debug(this,"Parsing item #{%s}".subs(index));var syncItem=this.parseItem(this.downloadedItems[index++]);if(syncItem){var comp=CLB_syncMan.getComponent(
  744. syncItem.componentID);if(!comp){G_DebugL(this,"ERROR: Could not find component with ID: {"+syncItem.componentID+"} for item {"+syncItem.itemID+"} . Dropping.")}else{var lookupKey=syncItem.makeLookupKey();var prevItem=this.parsedSyncItems.getItemByLookupKey(lookupKey);var compIsEncrypted=CLB_syncMan.isEncryptedComponent(comp.componentID);if(prevItem&&prevItem.originallyEncrypted==compIsEncrypted){G_Debug(this,"Smooshing previous item on top of synced item because there are two items with the same ID and the previous one is in the correct encryption state."
  745. );CLB_UpdateQueue.smooshItems(syncItem,prevItem);this.parsedSyncItems.deleteItemByLookupKey(lookupKey)}this.parsedSyncItems.addItem(syncItem)}}this.funQueue.addJob(parseNext)}
  746. ,this);G_Debug(this,"There are {%s} items to parse".subs(this.downloadedItems.length));parseNext()}
  747. ;CLB_Downloader.prototype.smooshDownloadedWithOffline=function(){G_Debug(this,"Smooshing downloaded items with offline items.");var index=0;var items=this.parsedSyncItems.getPending();var smooshNext=bind(function(){if(index==items.length){G_Debug(this,"Done smooshing downloaded items with offline items. Next up: resolve conflicts.");this.resolveConflicts();return}G_Debug(this,"Smooshing item #{%s}".subs(index));var syncItem=items[index++];var itemsEqual=this.conflictResolver.smooshWithOffline(syncItem)
  748. ;if(itemsEqual){this.parsedSyncItems.deleteItemByLookupKey(syncItem.makeLookupKey())}else{CLB_syncMan.getComponent(syncItem.componentID).onBeforeResolveConflict(syncItem.clone())}this.funQueue.addJob(smooshNext)}
  749. ,this);G_Debug(this,"There are {%s} items to smoosh".subs(items.length));smooshNext()}
  750. ;CLB_Downloader.prototype.resolveConflicts=function(){G_Debug(this,"Resolving conflicts");var index=0;var resolveNext=bind(function(){this.onProgress(CLB_Application.PROGRESS_RESOLVING,index/this.parsedSyncItems.pendingSize());if(this.parsedSyncItems.pendingSize()==0){G_Debug(this,"Done resolving conflicts. Next up: update server");this.startUpdate();return}G_Debug(this,"Checking item #{%s} for conflicts".subs(index));index++;var syncItem=this.parsedSyncItems.popNextItem();var isDownloaded=!syncItem.includesConflictResolution;
  751. G_Debug(this,"Item downloaded: "+isDownloaded);var moreItems=this.conflictResolver.resolveConflicts(syncItem,isDownloaded);for(var i=0;i<moreItems.length;i++){this.parsedSyncItems.addItem(moreItems[i]);var lookupKey=moreItems[i].makeLookupKey();this.parsedSyncItems.getItemByLookupKey(lookupKey).includesConflictResolution=true}this.applyLocallyQueue.replaceItem(syncItem);this.funQueue.addJob(resolveNext)}
  752. ,this);G_Debug(this,"There are {%s} items to check for conflicts".subs(this.parsedSyncItems.pendingSize()));resolveNext()}
  753. ;CLB_Downloader.prototype.startUpdate=function(){if(this.sendToServerQueue.pendingSize()>0){G_Debug(this,"Sending {%s} items to the server".subs(this.sendToServerQueue.pendingSize()));this.updater=new CLB_Updater;this.updater.start(this.sendToServerQueue.getPending(),false,this.updateComplete,this.onFailure,this.onProgress,true,false)}else{G_Debug(this,"There are zero updates to send.");this.updateComplete()}}
  754. ;CLB_Downloader.prototype.updateComplete=function(opt_newLastUpdate){G_Debug(this,"Update successful. Next up: apply local changes");if(opt_newLastUpdate){this.newTimestamp=opt_newLastUpdate}this.applyLocalChanges()}
  755. ;CLB_Downloader.prototype.applyLocalChanges=function(){G_Debug(this,"Applying local changes");var index=0;var items=this.applyLocallyQueue.getPending();var applyNext=bind(function(){if(index==items.length){G_Debug(this,"Done applying local changes. Firing success handler!");this.onSuccess(this.newTimestamp);return}G_Debug(this,"Apply local change #{%s}".subs(index));this.onProgress(CLB_Application.PROGRESS_APPLYING,index/items.length);var syncItem=items[index++];var comp=CLB_syncMan.getComponent(
  756. syncItem.componentID);comp.onItemAvailable(syncItem);this.funQueue.addJob(applyNext)}
  757. ,this);G_Debug(this,"There are {%s} local changes to apply".subs(items.length));applyNext()}
  758. ;CLB_Downloader.prototype.abort=function(){this.reqs.forEach(function(req){req.abort()}
  759. );if(this.updater){this.updater.cancel();this.updater=null}if(this.funQueue){this.funQueue.cancel();this.funQueue=null}}
  760. ;CLB_Downloader.prototype.parseItem=function(xmlItem){var syncItem=CLB_SyncItem.parseFromXML(xmlItem);if(!syncItem){return null}if(syncItem.isEncrypted){G_Debug(this,"Decrypting item");syncItem.decrypt();syncItem.originallyEncrypted=true}else{syncItem.originallyEncrypted=false}return syncItem}
  761. ;CLB_Downloader.prototype.handleWorkQueueError=function(job,e){G_DebugL(this,"Error during downloader workqueue job.\n"+"%s\n%s:%s".subs(e.message,e.fileName,e.lineNumber));this.onFailure(-1,"Unexpected error",e.toString())}
  762. ;CLB_Downloader.prototype.debugZone="CLB_Downloader";G_debugService.loggifier.loggify(CLB_Downloader.prototype);
  763. function CLB_HistoryEnumerator(histEnumerator){this.histEnumerator_=histEnumerator;this.nextHistoryItem_=null;this.advanceHistoryItem_()}
  764. CLB_HistoryEnumerator.prototype.debugZone="CLB_HistoryEnumerator";CLB_HistoryEnumerator.prototype.QueryInterface=function(iid){if(iid.equals(Ci.nsISupports)||iid.equals(Ci.nsISimpleEnumerator)){return this}else{throw Components.results.NS_ERROR_NO_INTERFACE;}}
  765. ;CLB_HistoryEnumerator.prototype.hasMoreElements=function(){return this.nextHistoryItem_!=null}
  766. ;CLB_HistoryEnumerator.prototype.getNext=function(){var next=this.nextHistoryItem_;this.advanceHistoryItem_();return next}
  767. ;CLB_HistoryEnumerator.prototype.advanceHistoryItem_=function(){this.nextHistoryItem_=null;while(this.nextHistoryItem_==null&&this.histEnumerator_.hasMoreElements()){var candidate=this.histEnumerator_.getNext();if(!(candidate instanceof Ci.nsIRDFResource)){G_Debug(this,"Failed to cast a resource to nsIRDFResource");continue}var root=CLB_app.historySyncer.histRdfServ_.GetResource(CLB_HistorySyncer.rootRdfStr);var childArc=CLB_app.historySyncer.histRdfServ_.GetResource(CLB_HistorySyncer.childRdfStr)
  768. ;var candidateValue=CLB_rdf.getValueFromNode(candidate);var item=CLB_app.historySyncer.getUpdateItem_(root,childArc,candidateValue);this.nextHistoryItem_=item}}
  769. ;G_debugService.loggifier.loggify(CLB_HistoryEnumerator.prototype);
  770. function CLB_HistorySyncer(){this.hist_=Cc["@mozilla.org/browser/global-history;2"].getService(Ci.nsIGlobalHistory2).QueryInterface(Ci.nsIBrowserHistory);this.histDS_=Cc["@mozilla.org/rdf/datasource;1?name=history"].getService(Ci.nsIRDFDataSource);this.histRdfServ_=Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService);this.ioSvc_=Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);this.obsSvc_=Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);this.updateBatchData_=
  771. {};this.started_=false;this.inShutdown_=false;this.propertiesToCollect_=new G_DoubleDictionary;this.propertiesToCollect_.addMultiple({name:CLB_HistorySyncer.nameRdfStr,date:CLB_HistorySyncer.dateRdfStr,firstDate:CLB_HistorySyncer.firstDateRdfStr,visitCount:CLB_HistorySyncer.visitCountRdfStr})}
  772. CLB_HistorySyncer.rootRdfStr="NC:HistoryRoot";CLB_HistorySyncer.rdfPrefix="http://home.netscape.com/NC-rdf#";CLB_HistorySyncer.nameRdfStr=CLB_HistorySyncer.rdfPrefix+"Name";CLB_HistorySyncer.dateRdfStr=CLB_HistorySyncer.rdfPrefix+"Date";CLB_HistorySyncer.firstDateRdfStr=CLB_HistorySyncer.rdfPrefix+"FirstVisitDate";CLB_HistorySyncer.visitCountRdfStr=CLB_HistorySyncer.rdfPrefix+"VisitCount";CLB_HistorySyncer.childRdfStr=CLB_HistorySyncer.rdfPrefix+"child";CLB_HistorySyncer.prototype.debugZone="CLB_HistorySyncer"
  773. ;CLB_HistorySyncer.prototype.QueryInterface=function(aIID){if(!aIID.equals(Ci.nsISupports)&&!aIID.equals(Ci.GISyncComponent)&&!aIID.equals(Ci.nsIRDFObserver))throw Components.results.NS_ERROR_NO_INTERFACE;return this}
  774. ;CLB_HistorySyncer.prototype.observe=function(subject,topic,data){if(topic=="quit-application"){this.inShutdown_=true;this.obsSvc_.removeObserver(this,"quit-application")}}
  775. ;CLB_HistorySyncer.prototype.componentID="@google.com/browserstate/history-syncer;1";CLB_HistorySyncer.prototype.componentName="History";CLB_HistorySyncer.prototype.encryptionRequred=false;CLB_HistorySyncer.prototype.syncOfflineChanges=true;CLB_HistorySyncer.prototype.syncBehavior=Ci.GISyncComponent.SYNC_SINCE_LAST_UPDATE;CLB_HistorySyncer.prototype.start=function(){G_Debug(this,"Starting history syncer");if(!this.started_){this.histDS_.AddObserver(this);this.obsSvc_.addObserver(this,"quit-application"
  776. ,false);new G_Alarm((function(){if(!this.hasHistoryExpirationFile_()){return}var file=this.getHistoryExpirationFile_();var urls=G_FileReader.readAll(file).split(G_File.LINE_END_CHAR);urls.forEach(function(url){if(url){var item=this.getHistoryDeleteItem_(url);CLB_syncMan.update(item);G_Debug(this,"Sending expired history item "+item)}}
  777. ,this);file.remove(false)}
  778. ).bind(this),0);this.started_=true}}
  779. ;CLB_HistorySyncer.prototype.stop=function(){G_Debug(this,"Stopping history syncer");if(this.started_){this.histDS_.RemoveObserver(this);this.obsSvc_.removeObserver(this,"quit-application");this.started_=false}}
  780. ;CLB_HistorySyncer.prototype.onBeforeResolveConflict=function(item){}
  781. ;CLB_HistorySyncer.prototype.onItemConflict=function(conflict,oldItem,newItem){}
  782. ;CLB_HistorySyncer.prototype.onItemAvailable=function(item){if(this.started_){G_Debug(this,"Error: onItemAvailable called while component is started");return}this.initializeHistory_();this.addHistoryItem_(item)}
  783. ;CLB_HistorySyncer.prototype.getItemByID=function(id,typeid){this.initializeHistory_();var root=this.histRdfServ_.GetResource(CLB_HistorySyncer.rootRdfStr);var childArc=this.histRdfServ_.GetResource(CLB_HistorySyncer.childRdfStr);return this.getUpdateItem_(root,childArc,id)}
  784. ;CLB_HistorySyncer.prototype.getCurrentItems=function(){this.initializeHistory_();var e=this.histDS_.GetAllResources();return new CLB_HistoryEnumerator(e)}
  785. ;CLB_HistorySyncer.prototype.beforeUpdate=function(){}
  786. ;CLB_HistorySyncer.prototype.onChange=function(aDataSource,aSource,aProperty,aOldTarget,aNewTarget){var newValue=CLB_rdf.getValueFromNode(aNewTarget);if(!newValue){G_Debug(this,"Could not extract value from target, skipping");return}G_Debug(this,"onChange: "+aSource.Value+" "+aProperty.Value+" changed to "+newValue+"\n\n");var item=this.getUpdateItem_(aSource,aProperty,newValue,false);if(item){CLB_syncMan.update(item)}}
  787. ;CLB_HistorySyncer.prototype.onAssert=function(aDataSource,aSource,aProperty,aTarget){var value=CLB_rdf.getValueFromNode(aTarget);if(!value){G_Debug(this,"Could not extract value from target, skipping");return}G_Debug(this,"onAssert: "+aSource.Value+" "+aProperty.Value+" "+value+"\n\n");var item=this.getUpdateItem_(aSource,aProperty,value,false);if(item){CLB_syncMan.update(item)}}
  788. ;CLB_HistorySyncer.prototype.onUnassert=function(aDataSource,aSource,aProperty,aTarget){var value=CLB_rdf.getValueFromNode(aTarget);if(!value){G_Debug(this,"Could not extract value from target, skipping");return}G_Debug(this,"onUnassert: "+aSource.Value+" "+aProperty.Value+" "+value+"\n\n");var item=this.getUpdateItem_(aSource,aProperty,value,true);if(item){CLB_syncMan.update(item)}}
  789. ;CLB_HistorySyncer.prototype.onMove=function(aDataSource,aOldSource,aNewSource,aProperty,aTarget){G_Debug(this,"onMove: "+aOldSource.Value+" "+aNewSource.Value+" "+aProperty.Value+" "+aTarget.value+"\n\n");G_Debug(this,"WARNING: unexpected move from history component")}
  790. ;CLB_HistorySyncer.prototype.onBeginUpdateBatch=function(aDataSource){G_Debug(this,"onBeginUpdateBatch!!");this.updateBatchData_={};var root=this.histRdfServ_.GetResource(CLB_HistorySyncer.rootRdfStr);var childArc=this.histRdfServ_.GetResource(CLB_HistorySyncer.childRdfStr);var targets=this.histDS_.GetTargets(root,childArc,true);while(targets.hasMoreElements()){var tar=targets.getNext();var url=CLB_rdf.getValueFromNode(tar);this.updateBatchData_[url]=1}}
  791. ;CLB_HistorySyncer.prototype.onEndUpdateBatch=function(aDataSource){G_Debug(this,"onEndUpdateBatch!!");var root=this.histRdfServ_.GetResource(CLB_HistorySyncer.rootRdfStr);var childArc=this.histRdfServ_.GetResource(CLB_HistorySyncer.childRdfStr);var targets=this.histDS_.GetTargets(root,childArc,true);while(targets.hasMoreElements()){var tar=targets.getNext();var url=CLB_rdf.getValueFromNode(tar);if(this.updateBatchData_[url]){delete this.updateBatchData_[url]}else{G_Debug(this,"Warning - something was added during the batch update: "
  792. +url)}}if(this.inShutdown_){this.inShutdown_=false;var urlsToFlush=[];for(var hist in this.updateBatchData_){urlsToFlush.push(hist)}if(urlsToFlush.length>0){var expiredFile=this.getHistoryExpirationFile_();G_FileWriter.writeAll(expiredFile,urlsToFlush.join(G_File.LINE_END_CHAR));G_Debug(this,"Wrote history expiration file with "+urlsToFlush.length+"urls")}}else{for(var hist in this.updateBatchData_){var item=this.getHistoryDeleteItem_(hist);CLB_syncMan.update(item)}}this.updateBatchData_={}}
  793. ;CLB_HistorySyncer.prototype.initializeHistory_=function(){var initialized=this.hist_.lastPageVisited;G_Debug(this,"lastPage: "+initialized)}
  794. ;CLB_HistorySyncer.prototype.getHistoryExpirationFile_=function(){return G_File.getProfileFile("browserstate-expiredHistory.txt")}
  795. ;CLB_HistorySyncer.prototype.hasHistoryExpirationFile_=function(){var file=this.getHistoryExpirationFile_();return file.exists()}
  796. ;CLB_HistorySyncer.prototype.getAllHistoryItems_=function(){var currentItems=[];var root=this.histRdfServ_.GetResource(CLB_HistorySyncer.rootRdfStr);var childArc=this.histRdfServ_.GetResource(CLB_HistorySyncer.childRdfStr);var targets=this.histDS_.GetTargets(root,childArc,true);while(targets.hasMoreElements()){var tar=targets.getNext();var tarValue=CLB_rdf.getValueFromNode(tar);var item=this.getUpdateItem_(root,childArc,tarValue,false);if(item!=null){currentItems[currentItems.length]=item}}return currentItems}
  797.  
  798. ;CLB_HistorySyncer.prototype.getHistoryDeleteItem_=function(url){var item=new CLB_SyncItem;this.setRequiredFields_(item,url);item.isRemove=true;return item}
  799. ;CLB_HistorySyncer.prototype.addHistoryItem_=function(item){G_Debug(this,"About to add history with syncitem: "+item.toStringVerbose()+"\n");if(!isDef(item.itemID)){G_Debug(this,"Warning: itemID is null, skipping!!\n");return}var uri=this.ioSvc_.newURI(item.itemID,null,null);if(item.isRemove){this.hist_.removePage(uri);return}var name=item.getProperty(this.propertiesToCollect_.getKey(CLB_HistorySyncer.nameRdfStr));var firstDate=item.getProperty(this.propertiesToCollect_.getKey(CLB_HistorySyncer.firstDateRdfStr)
  800. );var date=item.getProperty(this.propertiesToCollect_.getKey(CLB_HistorySyncer.dateRdfStr));var visitCount=item.getProperty(this.propertiesToCollect_.getKey(CLB_HistorySyncer.visitCountRdfStr));if(!isDef(name)||!isDef(firstDate)||!isDef(date)||!isDef(visitCount)){G_Debug(this,"Warning: some fields are undefined, skipping history item");return}if(!this.hist_.isVisited(uri)){this.hist_.addPageWithDetails(uri,name,firstDate)}var urlNode=this.histRdfServ_.GetResource(item.itemID);var currentCount=this.getVisitCount_(
  801. urlNode);if(currentCount==0){G_Debug(this,"WARNING: failed to retrieve current visit count. Skipping history item "+item.itemID);return}while(currentCount<visitCount){this.hist_.addPageWithDetails(uri,name,date);currentCount++}}
  802. ;CLB_HistorySyncer.prototype.getVisitCount_=function(node){var arc=this.histRdfServ_.GetResource(CLB_HistorySyncer.visitCountRdfStr);var target=this.histDS_.GetTarget(node,arc,true);if(!target){return 0}var targetValue=CLB_rdf.getValueFromNode(target);return targetValue}
  803. ;CLB_HistorySyncer.prototype.shouldUpdate_=function(srcValue,targetValue){if(srcValue.toString().startsWith("find:")||targetValue.toString().startsWith("find:")){return false}return true}
  804. ;CLB_HistorySyncer.prototype.fillHistoryItemDetails_=function(item,node){var arcs=this.histDS_.ArcLabelsOut(node);while(arcs.hasMoreElements()){var arc=arcs.getNext();var arcValue=CLB_rdf.getValueFromNode(arc);G_Debug(this,"Found arc "+arcValue+"\n");if(!this.propertiesToCollect_.hasValue(arcValue)){continue}try{var target=this.histDS_.GetTarget(node,arc,true);if(target){var targetValue=CLB_rdf.getValueFromNode(target);if(!targetValue){continue}G_Debug(this,"Found child "+node.Value+", "+arcValue+
  805. ", "+targetValue+"\n");if(!item.hasProperty(this.propertiesToCollect_.getKey(arcValue))){item.setProperty(this.propertiesToCollect_.getKey(arcValue),targetValue)}}}catch(e){}}}
  806. ;CLB_HistorySyncer.prototype.getUpdateItem_=function(aSource,aProperty,value,isRemove){var srcValue=CLB_rdf.getValueFromNode(aSource);var propValue=CLB_rdf.getValueFromNode(aProperty);var valueNode=this.histRdfServ_.GetResource(value);if(!this.shouldUpdate_(srcValue,value)){return null}var item=new CLB_SyncItem;G_Debug(this,"src: "+srcValue+" prop: "+propValue+"\n");if(srcValue==CLB_HistorySyncer.rootRdfStr&&propValue==CLB_HistorySyncer.childRdfStr){this.setRequiredFields_(item,value);if(isRemove)
  807. {item.isRemove=true;return item}this.fillHistoryItemDetails_(item,valueNode);return item}if(this.propertiesToCollect_.hasValue(propValue)){if(isRemove){G_Debug(this,"WARNING: unassert called on something other than url");return null}this.setRequiredFields_(item,srcValue);this.fillHistoryItemDetails_(item,aSource);item.isRemove=false;return item}G_Debug(this,"Error, cannot make update out of unexpected assertion, returning null");return null}
  808. ;CLB_HistorySyncer.prototype.setRequiredFields_=function(item,url){item.componentID=this.componentID;item.itemID=url}
  809. ;G_debugService.loggifier.loggify(CLB_HistorySyncer.prototype);
  810. function CLB_InfoBubble(root,tabbedBrowserWatcher,width){bindMethods(this);this.hidden=true;this.root_=root;this.inner_=root.firstChild;this.head_=root.previousSibling;this.tail_=root.nextSibling;this.parts_=[this.head_,this.root_,this.tail_];this.repaintAlarm_=null;this.width_=width;this.root_.style.width=width+"px";this.inner_.style.width=width-CLB_InfoBubble.INNER_BUBBLE_DIFFERENCE+"px";this.doc_=this.root_.ownerDocument;this.win_=this.doc_.defaultView;this.tabbedBrowserWatcher_=tabbedBrowserWatcher;
  811. var elms=this.root_.getElementsByTagName("*");for(var i=0,elm=null;elm=elms[i];i++){switch(elm.className){case "clb-infobubble-desc":this.desc_=elm;break;case "clb-infobubble-buttons":this.buttonsContainer_=elm;break;case "clb-infobubble-close":this.closeButton_=elm;break}}this.tabbedBrowserWatcher_.registerListener("tabswitch",this.handleTabSwitch_);this.win_.addEventListener("unload",this.handleUnload_,false);this.win_.addEventListener("resize",this.handleResize_,false);CLB_InfoBubble.nextInstanceId_++
  812. ;this.instanceId_=CLB_InfoBubble.nextInstanceId_;CLB_InfoBubble.instances_[this.instanceId_]=this}
  813. CLB_InfoBubble.ARROW_WIDTH=20;CLB_InfoBubble.ARROW_HEIGHT=20;CLB_InfoBubble.ROOT_OFFSET=50;CLB_InfoBubble.ARROW_OFFSET=16;CLB_InfoBubble.ROOT_MIN_RIGHT=25;CLB_InfoBubble.ROOT_MIN_LEFT=4;CLB_InfoBubble.INNER_BUBBLE_DIFFERENCE=16;CLB_InfoBubble.HIDE_DELAY_MILLISECONDS=10000;CLB_InfoBubble.instances_={};CLB_InfoBubble.nextInstanceId_=1;CLB_InfoBubble.allHidden=false;CLB_InfoBubble.hideAll=function(){G_Debug("CLB_InfoBubble","hiding all");for(var bubble in this.instances_){G_Debug("CLB_InfoBubble",bubble)
  814. ;this.instances_[bubble].hide()}G_Debug("CLB_InfoBubble","done");this.allHidden=true}
  815. ;CLB_InfoBubble.repositionAll=function(anchor){G_Debug("CLB_InfoBubble","reshowing all");for(var bubble in this.instances_){G_Debug("CLB_InfoBubble",bubble);if(!this.instances_[bubble].hidden){this.instances_[bubble].show(anchor)}}G_Debug("CLB_InfoBubble","done")}
  816. ;CLB_InfoBubble.repaintAll_=function(){var anyVisible=false;for(var id in this.instances_){if(!this.instances_[id].hidden){anyVisible=true;this.instances_[id].repaint_()}}if(!anyVisible){if(this.repaintAlarm_){this.repaintAlarm_.cancel();this.repaintAlarm_=null}}}
  817. ;CLB_InfoBubble.prototype.show=function(toolbarItem){G_Debug(this,"Showing info bubble");this.toolbarItem_=toolbarItem;this.repaint_();this.hidden=false;CLB_InfoBubble.allHidden=false;if(!CLB_InfoBubble.repaintAlarm_){CLB_InfoBubble.repaintAlarm_=new G_Alarm(CLB_InfoBubble.repaintAll_.bind(CLB_InfoBubble),2000,true)}this.startTimer_()}
  818. ;CLB_InfoBubble.prototype.startTimer_=function(){G_Debug(this,"Starting timer to wait before hooking up onLocationChange");if(this.hideAlarm_){G_Debug(this,"cancelling existing hide alarm...");this.hideAlarm_.cancel()}this.hideAlarm_=new G_Alarm(this.waitForLocationChange_,CLB_InfoBubble.HIDE_DELAY_MILLISECONDS)}
  819. ;CLB_InfoBubble.prototype.waitForLocationChange_=function(){G_Debug(this,"Timer elapsed. Waiting for location change.");this.hideAlarm_=null;this.tabbedBrowserWatcher_.registerListener("locationchange",this.handleLocationChange_)}
  820. ;CLB_InfoBubble.prototype.handleLocationChange_=function(){G_Debug(this,"Got location change. Hiding all info bubbles.");this.tabbedBrowserWatcher_.removeListener("locationchange",this.handleLocationChange_);CLB_InfoBubble.hideAll()}
  821. ;CLB_InfoBubble.prototype.hide=function(){G_Debug(this,"numparts: %s".subs(this.parts_.length));this.parts_.forEach(function(part){part.hidden=true;part.style.top="";part.style.bottom="";part.style.left="";part.style.right=""}
  822. );this.hidden=true}
  823. ;CLB_InfoBubble.prototype.repaint_=function(){try{var x=this.toolbarItem_.boxObject}catch(e){this.toolbarItem_=null;return}if(this.toolbarItem_.ownerDocument==this.root_.ownerDocument){if(x<this.win_.innerWidth/2){this.paintLeft_()}else{this.paintRight_()}}else{this.paintAlone_()}}
  824. ;CLB_InfoBubble.prototype.paintLeft_=function(){var arrowTop=this.toolbarItem_.boxObject.y+Math.round(this.toolbarItem_.boxObject.height*0.75);var rootTop=arrowTop+CLB_InfoBubble.ARROW_HEIGHT;var arrowLeft=this.toolbarItem_.boxObject.x+CLB_InfoBubble.ARROW_OFFSET;var rootLeft=arrowLeft-CLB_InfoBubble.ROOT_OFFSET;if(rootLeft<CLB_InfoBubble.ROOT_MIN_LEFT){rootLeft=CLB_InfoBubble.ROOT_MIN_LEFT}this.head_.style.top=arrowTop+"px";this.head_.style.bottom="";this.root_.style.top=rootTop+"px";this.root_.style.bottom=
  825. "";this.root_.style.left=rootLeft+"px";this.root_.style.right="";this.head_.style.left=arrowLeft+"px";this.head_.style.right="";this.head_.firstChild.src="chrome://browserstate/content/head-left.png";this.head_.hidden=false;this.root_.hidden=false}
  826. ;CLB_InfoBubble.prototype.paintRight_=function(){var arrowTop=this.toolbarItem_.boxObject.y+Math.round(this.toolbarItem_.boxObject.height*0.5);var rootTop=arrowTop+CLB_InfoBubble.ARROW_HEIGHT;var arrowRight=this.win_.innerWidth-this.toolbarItem_.boxObject.x-CLB_InfoBubble.ARROW_OFFSET;var rootRight=arrowRight-this.width_+CLB_InfoBubble.ROOT_OFFSET;if(rootRight<CLB_InfoBubble.ROOT_MIN_RIGHT){rootRight=CLB_InfoBubble.ROOT_MIN_RIGHT}this.head_.style.top=arrowTop+"px";this.head_.style.bottom="";this.root_.style.top=
  827. rootTop+"px";this.root_.style.bottom="";this.root_.style.right=rootRight+"px";this.root_.style.left="";this.head_.style.right=arrowRight+"px";this.head_.style.left="";this.head_.firstChild.src="chrome://browserstate/content/head-right.png";this.head_.hidden=false;this.root_.hidden=false}
  828. ;CLB_InfoBubble.prototype.paintAlone_=function(){this.root_.style.top=this.doc_.getElementById("content").boxObject.y+8+"px";this.root_.style.bottom="";this.root_.style.right="8px";this.root_.style.left="";this.root_.hidden=false;this.head_.hidden=true}
  829. ;CLB_InfoBubble.prototype.clear=function(){if(this.desc_.firstChild){this.desc_.removeChild(this.desc_.firstChild)}while(this.buttonsContainer_.firstChild){this.buttonsContainer_.removeChild(this.buttonsContainer_.firstChild)}}
  830. ;CLB_InfoBubble.prototype.setMessage=function(txt){this.desc_.appendChild(this.doc_.createTextNode(txt))}
  831. ;CLB_InfoBubble.prototype.addButton=function(text,callback){var button=this.doc_.createElement("button");button.setAttribute("label",text);button._command=callback;button.setAttribute("oncommand","this._command()");this.buttonsContainer_.appendChild(button)}
  832. ;CLB_InfoBubble.prototype.handleTabSwitch_=function(){G_Debug(this,"Heard tabswitch. Reparenting {%s} parts.".subs(this.parts_.length));for(var i=0;i<this.parts_.length;i++){this.reparent_(this.parts_[i])}}
  833. ;CLB_InfoBubble.prototype.reparent_=function(elm){var z=this.win_.document.defaultView.getComputedStyle(elm,"").getPropertyValue("z-index");var marker=elm.nextSibling;var parent=elm.parentNode;parent.removeChild(elm);parent.insertBefore(elm,marker);elm.style.zIndex=parseInt(z)+1}
  834. ;CLB_InfoBubble.prototype.handleUnload_=function(){delete CLB_InfoBubble.instances_[this.instanceId_]}
  835. ;CLB_InfoBubble.prototype.handleResize_=function(){if(!this.hidden){this.repaint_()}}
  836. ;CLB_InfoBubble.prototype.debugZone="CLB_InfoBubble";G_debugService.loggifier.loggify(CLB_InfoBubble.prototype);
  837. function CLB_ListDictionary(){this.index_={};this.items_=[]}
  838. CLB_ListDictionary.ITEM_EXISTS_ERROR=new Error("The specified key already exists.");CLB_ListDictionary.prototype.debugZone="CLB_ListDictionary";CLB_ListDictionary.prototype.addItem=function(key,val){if(isDef(this.index_[key])){throw CLB_ListDictionary.ITEM_EXISTS_ERROR;}this.index_[key]=this.items_.push({key:key,val:val})-1}
  839. ;CLB_ListDictionary.prototype.addOrReplaceItem=function(key,val){var idx=this.index_[key];if(!isDef(idx)){this.addItem(key,val)}else{this.items_[idx]={key:key,val:val}}}
  840. ;CLB_ListDictionary.prototype.getItem=function(key){if(isDef(this.index_[key])){return this.items_[this.index_[key]].val}}
  841. ;CLB_ListDictionary.prototype.getList=function(){return this.items_}
  842. ;CLB_ListDictionary.prototype.deleteItem=function(key){var idx=this.index_[key];if(isDef(idx)){delete this.index_[key];this.items_.splice(idx,1);for(var i=idx;i<this.items_.length;i++){this.index_[this.items_[i].key]--}}}
  843. ;
  844. function CLB_LoginUtil(){}
  845. CLB_LoginUtil.prototype.startRequest=function(username,password,onSuccess,onFailure){var req=CLB_RequestFactory.getRequest(CLB_RequestFactory.AUTHENTICATE,null,onSuccess,onFailure);req.setRequestHeader("Content-type","application/x-www-form-urlencoded");req.send(this.encodeParams_({Email:username,Passwd:password,PersistentCookie:true,source:"browserstate"}));return req}
  846. ;CLB_LoginUtil.prototype.parseResponse=function(responseString){var lines=responseString.split(/\n/);var details={};var line;for(var i=0;line=lines[i];i++){line=line.split("=");details[line.shift()]=line.join("=")}return details}
  847. ;CLB_LoginUtil.prototype.isAuthError=function(responseString){return this.parseResponse(responseString)["Error"]=="badauth"}
  848. ;CLB_LoginUtil.prototype.showErrorMessage=function(parentWin,responseString){var resp=this.parseResponse(responseString);var code=resp["Error"];if(code=="cr"){parentWin.alert("The specified Google account has been temporarily locked. Please verify your account and then reconnect to Google Browser Sync.");CLB_app.setStatus(CLB_Application.STATUS_NEEDS_CAPTCHA);CLB_app.errorURL=resp["Url"];return false}var msg={badauth:"Incorrect username or password. Please try again.",adel:"The specified Google account has been deleted."
  849. ,adis:"The specified Google account has been disabled.",nv:"The specified Google account's email address has not been verified.",tna:"The specified Google user has not agreed to the terms of service.",ire:"Authentication server temporarily unavailable. Please try again later.",unknown:"Unknown authentication server error. Please try again later."}[code];if(!msg){msg="Unknown server error. Please try again later."}parentWin.alert(msg);return true}
  850. ;CLB_LoginUtil.prototype.encodeParams_=function(params){var s=[];for(var p in params){s.push(encodeURIComponent(p));s.push("=");s.push(encodeURIComponent(params[p]));s.push("&")}return s.join("")}
  851. ;CLB_LoginUtil.prototype.debugZone="CLB_LoginUtil";G_debugService.loggifier.loggify(CLB_LoginUtil.prototype,"startRequest");
  852. function CLB_PasswordForm(win){this.win_=win;this.args_=this.win_.arguments[0].QueryInterface(Ci.nsIWritablePropertyBag);this.args_.setProperty("success",false);this.args_.setProperty("password","")}
  853. CLB_PasswordForm.DIALOG_WIDTH=350;CLB_PasswordForm.DIALOG_HEIGHT=130;CLB_PasswordForm.show=function(parent){var result=Cc["@mozilla.org/hash-property-bag;1"].createInstance(Ci.nsIWritablePropertyBag);var left=(parent.outerWidth-this.DIALOG_WIDTH)/2+parent.screenX;var top=(parent.outerHeight-this.DIALOG_HEIGHT)/2+parent.screenY;var features="modal,dialog,left=%s,top=%s".subs(left,top);Cc["@mozilla.org/embedcomp/window-watcher;1"].getService(Ci.nsIWindowWatcher).openWindow(null,"chrome://browserstate/content/password.xul"
  854. ,"password",features,result);return result}
  855. ;CLB_PasswordForm.prototype.handleDialogLoad=function(){this.doc_=this.win_.document;this.dialog_=this.doc_.documentElement;this.usernameField_=this.doc_.getElementById("clb-username");this.passwordField_=this.doc_.getElementById("clb-password");this.usernameField_.value=CLB_app.prefs.getPref("username");this.dialog_.setAttribute("width",CLB_PasswordForm.DIALOG_WIDTH);this.win_.sizeToContent()}
  856. ;CLB_PasswordForm.prototype.handleDialogAccept=function(){this.args_.setProperty("success",true);this.args_.setProperty("password",this.passwordField_.value)}
  857. ;CLB_PasswordForm.prototype.debugZone="CLB_PasswordForm";G_debugService.loggifier.loggify(CLB_PasswordForm.prototype,"CLB_PasswordForm");
  858. function CLB_PasswordSyncer(){this.passMan_=null;this.lastSyncedState_={};this.lastModified_=null;this.signonsFile_=null;this.enabled_=null;this.knownMasterPassword_="";this.promptSvc_=Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService)}
  859. CLB_PasswordSyncer.CONTRACT_ID="@google.com/browserstate/password-syncer;1";CLB_PasswordSyncer.prototype.encryptionRequired=true;CLB_PasswordSyncer.prototype.syncOfflineChanges=true;CLB_PasswordSyncer.prototype.componentName="Saved Passwords";CLB_PasswordSyncer.TYPE_PASSWORD="password";CLB_PasswordSyncer.TYPE_REJECT="reject";CLB_PasswordSyncer.prototype.componentID="@google.com/browserstate/password-syncer;1";CLB_PasswordSyncer.prototype.syncBehavior=Ci.GISyncComponent.SYNC_SINCE_LAST_UPDATE;CLB_PasswordSyncer.prototype.initPassMan_=
  860. function(){if(!this.passMan_){this.passMan_=Cc["@mozilla.org/passwordmanager;1"].getService();this.passMan_.QueryInterface(Ci.nsIPasswordManager);this.passMan_.QueryInterface(Ci.nsIPasswordManagerInternal)}this.unlockPasswordStore();G_Debug(this,"Password Syncer is %s".subs(this.enabled_?"enabled":"disabled"));if(!this.signonsFile_){this.signonsFile_=G_File.getProfileFile("signons.txt");if(this.signonsFile_.exists()){this.lastModified_=this.signonsFile_.lastModifiedTime;this.lastSyncedState_=this.getCurrentItems_(
  861. )}else{G_Debug(this,"Passwords file did not exist")}}}
  862. ;CLB_PasswordSyncer.prototype.checkMasterPassword_=function(){var token=Cc["@mozilla.org/security/pk11tokendb;1"].createInstance(Ci.nsIPK11TokenDB).getInternalKeyToken();var valid=false;try{valid=token.checkPassword("");if(!valid&&this.knownMasterPassword_){valid=token.checkPassword(this.knownMasterPassword_)}}catch(e){valid=true}while(!valid){var password={value:""};if(this.promptSvc_.promptPassword(null,"Google Browser Sync needs your Master Password","Google Browser Sync needs your Firefox Master Password in order to sync your passwords, please enter it below."
  863. ,password,null,{})){valid=token.checkPassword(password.value);if(valid){G_Debug(this,"User's password was valid.");this.knownMasterPassword_=password.value}else{G_Debug(this,"User's password was not valid.")}}else{G_Debug(this,"User pressed cancel, giving up.");return false}}return valid}
  864. ;CLB_PasswordSyncer.prototype.unlockPasswordStore=function(){if(isNull(this.enabled_)){this.enabled_=this.checkMasterPassword_()}return this.enabled_}
  865. ;CLB_PasswordSyncer.prototype.start=function(){G_Debug(this,"Password Syncer Start");this.initPassMan_();CLB_app.prefs.setPref("reimportPasswords",!this.enabled_)}
  866. ;CLB_PasswordSyncer.prototype.stop=function(){G_Debug(this,"Password Syncer Stop")}
  867. ;CLB_PasswordSyncer.prototype.onFirstSync=function(){}
  868. ;CLB_PasswordSyncer.prototype.onBeforeResolveConflict=function(item){}
  869. ;CLB_PasswordSyncer.prototype.getItemByID=function(id,typeID){return null}
  870. ;CLB_PasswordSyncer.prototype.onItemConflict=function(name,oldItem,newItem){return new CLB_ArrayEnumerator([])}
  871. ;CLB_PasswordSyncer.prototype.onItemAvailable=function(item){this.initPassMan_();if(!this.enabled_){return}G_Debug(this,"Item %s available".subs(item));if(item.isRemove){if(!isDef(item.itemID)){G_DebugL(this,"ERROR: received item does not have an itemID.");return}if(!this.lastSyncedState_[item.itemID]){G_DebugL(this,"ERROR: Could not find entry in lastSyncedState_ "+"corresponding to itemID {%s}".subs(item.itemID));return}this.removeFromPassMan_(this.lastSyncedState_[item.itemID]);delete this.lastSyncedState_[
  872. item.itemID]}else{if(item.typeID==CLB_PasswordSyncer.TYPE_REJECT){if(!item.hasProperty("host")){G_DebugL(this,"ERROR: Received reject does not has a host property");return}this.passMan_.addReject(item.getProperty("host"))}else{if(!item.hasProperty("host")||!item.hasProperty("user")||!item.hasProperty("password")){G_DebugL(this,"ERROR: Received password does not have required properties.");return}this.passMan_.addUserFull(item.getProperty("host"),item.getProperty("user"),item.getProperty("password"
  873. ),item.getProperty("userFieldName"),item.getProperty("passFieldName"))}this.lastSyncedState_[item.itemID]=item.clone()}}
  874. ;CLB_PasswordSyncer.prototype.getCurrentItems=function(){this.initPassMan_();if(!this.enabled_){return new CLB_ArrayEnumerator([])}var arr=[];var currentItems=this.getCurrentItems_();for(var itemID in currentItems){arr.push(currentItems[itemID])}return new CLB_ArrayEnumerator(arr)}
  875. ;CLB_PasswordSyncer.prototype.beforeUpdate=function(){G_Debug(this,"Password Syncer beforeUpdate");var signonsFileExisted=Boolean(this.signonsFile_);this.initPassMan_();if(!this.enabled_){return}this.signonsFile_=G_File.getProfileFile("signons.txt");if(this.signonsFile_.exists()){if(signonsFileExisted&&this.lastModified_==this.signonsFile_.lastModifiedTime){G_Debug(this,"Passwords have NOT been modified");return}}else{G_Debug(this,"Password file did not exist");return}G_Debug(this,"Passwords have been modified"
  876. );if(!signonsFileExisted){this.lastSyncedState_={}}var currentItems=this.getCurrentItems_();for(var itemID in currentItems){var item=currentItems[itemID];if(isDef(item.itemID)&&!isDef(this.lastSyncedState_[item.itemID])){G_Debug(this,"Sending addition {%s} to syncman".subs(item));CLB_syncMan.update(item.clone())}}for(var itemID in this.lastSyncedState_){var item=this.lastSyncedState_[itemID];if(isDef(item.itemID)&&!isDef(currentItems[item.itemID])){item=item.clone();item.clearProperties();item.isRemove=
  877. true;G_Debug(this,"Sending deletion {%s} to syncman".subs(item));CLB_syncMan.update(item)}}this.lastModified_=this.signonsFile_.lastModifiedTime;this.lastSyncedState_=currentItems}
  878. ;CLB_PasswordSyncer.prototype.getCurrentItems_=function(){this.initPassMan_();if(!this.enabled_){return{}}var passEnumerator=this.passMan_.enumerator;var rejectEnumerator=this.passMan_.rejectEnumerator;var result={};var passObj;while(passEnumerator.hasMoreElements()){passObj=passEnumerator.getNext().QueryInterface(Ci.nsIPasswordInternal);var syncItem=null;try{syncItem=this.createSyncItem_(passObj,false)}catch(e){if(e.message=="PASSWORD INACCESSIBLE"){G_Debug(this,"ERROR: Password was inaccessible, probably due to encryption, disabling PW syncer and skipping remaining items"
  879. );this.enabled_=false;return result}else{throw e;}}if(syncItem){result[syncItem.itemID]=syncItem}}while(rejectEnumerator.hasMoreElements()){passObj=rejectEnumerator.getNext().QueryInterface(Ci.nsIPasswordInternal);var syncItem=null;try{syncItem=this.createSyncItem_(passObj,true)}catch(e){if(e.message=="PASSWORD INACCESSIBLE"){G_Debug(this,"ERROR: Password was inaccessible, probably due to encryption, disabling PW syncer and skipping remaining items");this.enabled_=false;return result}else{throw e;
  880. }}if(syncItem){result[syncItem.itemID]=syncItem}}return result}
  881. ;CLB_PasswordSyncer.prototype.removeFromPassMan_=function(item){var host=item.getProperty("host");var user=item.getProperty("user");if(item.typeID==CLB_PasswordSyncer.TYPE_REJECT){try{this.passMan_.removeReject(host)}catch(e){G_DebugL(this,"ERROR: Failed to remove reject '%s' with error '%s'".subs(host,e))}}else{try{this.passMan_.removeUser(host,user)}catch(e){G_DebugL(this,"Failed to remove user from host '%s' with error '%s'".subs(host,e))}}}
  882. ;CLB_PasswordSyncer.prototype.createSyncItem_=function(passObject,isReject){var syncItem=new CLB_SyncItem;syncItem.componentID=this.componentID;try{var test=passObject.user+passObject.password;G_Debug(this,"Got password object: "+isDef(test))}catch(e){G_Debug(this,"Password was not accessible, perhaps due to master "+"password blocking. Error: %s".subs(e));throw new Error("PASSWORD INACCESSIBLE");}if(isReject){syncItem.typeID=CLB_PasswordSyncer.TYPE_REJECT;syncItem.setProperty("host",passObject.host)
  883. }else{syncItem.typeID=CLB_PasswordSyncer.TYPE_PASSWORD;syncItem.setProperty("host",passObject.host);syncItem.setProperty("user",passObject.user);syncItem.setProperty("password",passObject.password);syncItem.setProperty("userFieldName",passObject.userFieldName);syncItem.setProperty("passFieldName",passObject.passwordFieldName)}this.initItemID_(syncItem);return syncItem}
  884. ;CLB_PasswordSyncer.prototype.initItemID_=function(item){var hasher=new G_CryptoHasher;hasher.init(G_CryptoHasher.algorithms.SHA1);hasher.updateFromString(item.getProperty("host"));if(item.typeID==CLB_PasswordSyncer.TYPE_REJECT){hasher.updateFromString("false")}else{hasher.updateFromString("true");hasher.updateFromString(item.getProperty("user"));hasher.updateFromString(item.getProperty("password"));hasher.updateFromString(item.getProperty("userFieldName"));hasher.updateFromString(item.getProperty(
  885. "passFieldName"))}item.itemID=hasher.digestBase64()}
  886. ;CLB_PasswordSyncer.prototype.debugZone="CLB_PasswordSyncer";G_debugService.loggifier.loggify(CLB_PasswordSyncer.prototype);
  887. function CLB_PreferencesSyncer(componentID,componentName,debugZone,prefNames,opt_encryptionRequired){bindMethods(this);this.componentID=componentID;this.componentName=componentName;this.encryptionRequired=!(!opt_encryptionRequired);this.syncBehavior=Ci.GISyncComponent.SYNC_SINCE_LAST_UPDATE;this.debugZone=debugZone;this.prefNames_={};this.prefs_=new G_Preferences;this.started_=false;this.syncedItems=[];for(var i=0;i<prefNames.length;i++){this.prefNames_[prefNames[i]]=1}CLB_syncMan.addObserver(this)
  888. }
  889. CLB_PreferencesSyncer.prototype.syncOfflineChanges=true;CLB_PreferencesSyncer.prototype.syncProgress=(CLB_PreferencesSyncer.prototype.syncFailure=(CLB_PreferencesSyncer.prototype.syncComplete=(CLB_PreferencesSyncer.prototype.updateStart=(CLB_PreferencesSyncer.prototype.updateProgress=(CLB_PreferencesSyncer.prototype.updateFailure=(CLB_PreferencesSyncer.prototype.updateComplete=function(){}
  890. ))))));CLB_PreferencesSyncer.prototype.syncStart=function(){this.syncedItems=[]}
  891. ;CLB_PreferencesSyncer.prototype.start=function(){if(!this.started_){this.prefs_.addObserver("",this.handlePrefChange_);this.started_=true}}
  892. ;CLB_PreferencesSyncer.prototype.stop=function(){if(this.started_){this.prefs_.removeObserver("",this.handlePrefChange_);this.started_=false}}
  893. ;CLB_PreferencesSyncer.prototype.handlePrefChange_=function(prefName){G_Debug(this,"Got change on pref {%s}".subs(prefName));var valid=false;for(var watchedPrefName in this.prefNames_){if(prefName.indexOf(watchedPrefName)==0){valid=true;break}}if(!valid){G_Debug(this,"Skipping because we aren't watching this pref");return}var syncItem=new CLB_SyncItem({componentID:this.componentID,itemID:prefName});var prefVal=this.prefs_.getPref(prefName);if(!isDef(prefVal)){syncItem.isRemove=true}else{syncItem.setProperty(
  894. "value",prefVal)}CLB_syncMan.update(syncItem)}
  895. ;CLB_PreferencesSyncer.prototype.onBeforeResolveConflict=function(syncItem){}
  896. ;CLB_PreferencesSyncer.prototype.onItemConflict=function(conflict,oldItem,newItem){return new CLB_ArrayEnumerator([])}
  897. ;CLB_PreferencesSyncer.prototype.onItemAvailable=function(syncItem){if(syncItem.isRemove){this.prefs_.clearPref(syncItem.itemID)}else{this.prefs_.setPref(syncItem.itemID,syncItem.getProperty("value"))}this.syncedItems.push(syncItem)}
  898. ;CLB_PreferencesSyncer.prototype.getItemByID=function(id,typeid){return null}
  899. ;CLB_PreferencesSyncer.prototype.getCurrentItems=function(){var result=[];getObjectProps(this.prefNames_).forEach(function(prefName){var prefVal=this.prefs_.getPref(prefName);if(isDef(prefVal)){var syncItem=new CLB_SyncItem({componentID:this.componentID,itemID:prefName});syncItem.setProperty("value",prefVal);result.push(syncItem)}}
  900. ,this);return new CLB_ArrayEnumerator(result)}
  901. ;CLB_PreferencesSyncer.prototype.beforeUpdate=function(){}
  902. ;CLB_PreferencesSyncer.prototype.debugZone="CLB_PreferencesSyncer";G_debugService.loggifier.loggify(CLB_PreferencesSyncer.prototype);
  903. var CLB_rdf=new Object;CLB_rdf.debugZone="CLB_rdf";CLB_rdf.rdfIFaces=["nsIRDFLiteral","nsIRDFResource","nsIRDFBlob","nsIRDFInt","nsIRDFDate","nsIRDFNode"];CLB_rdf.getValueFromNode=function(node){for(var i=0;i<CLB_rdf.rdfIFaces.length;i++){var iface=CLB_rdf.rdfIFaces[i];if(node instanceof Ci[iface]){return node.Value}}G_DebugL(this,"Warning - node has no type");return null}
  904. ;CLB_rdf.getRdfDs=function(datastore,limit){var t="";var all_res=datastore.GetAllResources();for(var r=0;all_res.hasMoreElements();r++){if(limit>0&&t.length>limit){return t}var res=all_res.getNext();if(!(res instanceof Components.interfaces.nsIRDFResource)){G_DebugL(this,"Failed to cast a resource to nsIRDFResource");continue}var tr=r+" R: "+res.Value+G_File.LINE_END_CHAR;var ps=datastore.ArcLabelsOut(res);while(ps.hasMoreElements()){var predicate=ps.getNext();if(!(predicate instanceof Components.interfaces.nsIRDFResource)
  905. ){G_DebugL(this,"Failed to cast a predicate to nsIRDFResource");continue}try{tr+="  -R:  "+predicate.Value+G_File.LINE_END_CHAR;var ts=datastore.GetTargets(res,predicate,true);while(ts.hasMoreElements()){var target=ts.getNext();var tmp="";for(var i=0;i<CLB_rdf.rdfIFaces.length;i++){var iface=CLB_rdf.rdfIFaces[i];if(target instanceof Ci[iface]){tmp="   "+iface+": "+target.Value+G_File.LINE_END_CHAR;break}}if(tmp==""){tr+="   UNKNOWN NODE TYPE"+G_File.LINE_END_CHAR}else{tr+=tmp}}}catch(e){tr+="    >R: EMPTY VALUE"
  906. }}t+=tr+G_File.LINE_END_CHAR}return t}
  907. ;CLB_rdf.writeRdfToFile=function(datastore,limit,filename){var file=G_File.getProfileFile(filename);file.createUnique(file.NORMAL_FILE_TYPE,420);var data=CLB_rdf.getRdfDs(datastore,limit);G_FileWriter.writeAll(file,data);return file}
  908. ;CLB_rdf.getInitializedContainer=function(datastore,containerResource){var container=Cc["@mozilla.org/rdf/container;1"].getService(Ci.nsIRDFContainer);container.Init(datastore,containerResource);return container}
  909. ;CLB_rdf.getContainerCount=function(datastore,containerResource){var container=CLB_rdf.getInitializedContainer(datastore,containerResource);return container.GetCount()}
  910. ;G_debugService.loggifier.loggify(CLB_rdf);
  911. var CLB_RequestFactory={};CLB_RequestFactory.debugZone="CLB_RequestFactory";CLB_RequestFactory.PING="http://www.google.com/about.html";CLB_RequestFactory.AUTHENTICATE="https://www.google.com/accounts/ClientAuth";CLB_RequestFactory.GENERATE_KEY="https://www.google.com/safebrowsing/getkey";CLB_RequestFactory.USER_EXISTS="/verify_user_exists";CLB_RequestFactory.ADD_CLIENT="/add_client";CLB_RequestFactory.CREATE_USER="/create_user";CLB_RequestFactory.START_SESSION="/start_session";CLB_RequestFactory.UPDATE=
  912. "/update";CLB_RequestFactory.SYNC="/sync";CLB_RequestFactory.PROD_DOMAIN="https://browsersync.google.com/browsersync";CLB_RequestFactory.getURL=function(urlType){if(urlType==CLB_RequestFactory.PING||urlType==CLB_RequestFactory.AUTHENTICATE||urlType==CLB_RequestFactory.GENERATE_KEY){return urlType}var serverOverride=CLB_app.prefs.getPref("server");if(serverOverride){return serverOverride+urlType}else{return CLB_RequestFactory.PROD_DOMAIN+urlType}}
  913. ;CLB_RequestFactory.getRequest=function(urlType,querystring,onSuccess,onFailure,opt_onProgress,opt_useGet){var url=this.getURL(urlType);var req=Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);var params=[];if(!querystring){querystring={}}if(urlType!=CLB_RequestFactory.PING&&urlType!=CLB_RequestFactory.AUTHENTICATE&&urlType!=CLB_RequestFactory.GENERATE_KEY){querystring["v"]=CLB_app.getVersion()}if(!isEmptyObject(querystring)){for(var name in querystring){params.push(
  914. name+"="+querystring[name])}url+="?"+params.join("&")}req.async=true;G_DebugL(this,"opening %s...".subs(url));req.open(opt_useGet?"GET":"POST",url);req.onload=function(){if(req.status==200){G_DebugL(CLB_RequestFactory,"Received successful response.");onSuccess(req)}else{G_DebugL(CLB_RequestFactory,"Server error for %s. %s %s: %s".subs(url,req.status,req.statusText,req.responseText));onFailure(req.status,req.statusText,req.responseText)}}
  915. ;req.onerror=function(){G_DebugL(CLB_RequestFactory,"Could not contact server for: %s".subs(url));onFailure(CLB_RequestFactory.ERR_COULD_NOT_CONTACT_SERVER,"Could not contact server.")}
  916. ;if(opt_onProgress){req.onprogress=opt_onProgress}req.channel.notificationCallbacks=new CLB_BadCertListener;return req}
  917. ;CLB_RequestFactory.ERR_COULD_NOT_CONTACT_SERVER=50;G_debugService.loggifier.loggify(CLB_RequestFactory);
  918. function CLB_RestoreTabsUI(win,tabBrowser,bubbleRoot,tabbedBrowserWatcher){bindMethods(this);this.win_=win;this.doc_=win.document;this.tabBrowser_=tabBrowser;this.checkboxLookup_={};this.winMed_=Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);this.winWat_=Cc["@mozilla.org/embedcomp/window-watcher;1"].getService(Ci.nsIWindowWatcher);this.toolbarButton_=this.doc_.getElementById("clb-toolbarbutton");var infoBubbleWidth=CLB_app.isLinux()?CLB_RestoreTabsUI.INFO_BUBBLE_WIDTH_LINUX:
  919. CLB_RestoreTabsUI.INFO_BUBBLE_WIDTH;this.infoBubble_=new CLB_InfoBubble(bubbleRoot,tabbedBrowserWatcher,infoBubbleWidth);this.restoreRows_=bubbleRoot.getElementsByTagName("rows")[0];this.restoreAllButton_=bubbleRoot.getElementsByTagName("button")[0];this.restoreAllButton_._command=this.handleRestoreAll_;this.restoreAllButton_.setAttribute("oncommand","this._command()");this.obsSvc_=Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);this.obsSvc_.addObserver(this,"clb-show-restore"
  920. ,true);this.cleanUpItemsToOpen_();if(!CLB_RestoreTabsUI.observingSyncMan_){G_Debug(this,"Adding static interface to syncman observer.");CLB_syncMan.addObserver(CLB_RestoreTabsUI);CLB_RestoreTabsUI.observingSyncMan_=true;CLB_RestoreTabsUI.checkDupe_(this.win_)}if(CLB_RestoreTabsUI.windowsToOpen_.length&&CLB_app.getStatus()==CLB_Application.STATUS_ONLINE&&!CLB_InfoBubble.allHidden){this.populate_();this.infoBubble_.show(this.toolbarButton_)}}
  921. CLB_RestoreTabsUI.BROWSER_CHROME_URL="chrome://browser/content/browser.xul";CLB_RestoreTabsUI.DISABLED_MESSAGE="No tabs are available to be restored";CLB_RestoreTabsUI.DISABLED_IMAGE="chrome://browserstate/content/restore-disabled.png";CLB_RestoreTabsUI.ENABLED_IMAGE="chrome://browserstate/content/restore.png";CLB_RestoreTabsUI.MAX_URL_LENGTH=25;CLB_RestoreTabsUI.MAX_TITLE_LENGTH=15;CLB_RestoreTabsUI.INFO_BUBBLE_WIDTH=320;CLB_RestoreTabsUI.INFO_BUBBLE_WIDTH_LINUX=350;CLB_RestoreTabsUI.observingSyncMan_=
  922. false;CLB_RestoreTabsUI.windowsToOpen_=[];CLB_RestoreTabsUI.tabsToOpen_={};CLB_RestoreTabsUI.isReconnecting=false;CLB_RestoreTabsUI.addWindowItem=function(item){if(item.getProperty("topWindow")=="true"||this.windowsToOpen_.length==0){this.windowsToOpen_.push(item)}else{this.windowsToOpen_.splice(this.windowsToOpen_.length-2,0,item)}G_Debug(this,"windowsToOpen_ is now: "+this.windowsToOpen_)}
  923. ;CLB_RestoreTabsUI.addTabItem=function(item){var winID=item.getProperty("windowID");var tabPos=parseInt(item.getProperty("tabIndex"));var url=item.getProperty("url");if(!isDef(winID)||isNaN(tabPos)||!isDef(url)){G_DebugL(this,"WARNING: Received invalid tab item. Dropping. "+"winID: {%s}, tabPos: {%s}, url: {%s}".subs(winID,tabPos,url));return}var tabList=this.tabsToOpen_[winID];if(!tabList){this.tabsToOpen_[winID]=(tabList=[])}if(tabList[tabPos]){G_DebugL(this,"WARNING: Received tab item {%s} at position {%s} would collide with existing tab item {%s} at that position."
  924. .subs(item.itemID,tabPos,tabList[tabPos].itemID));return}tabList[tabPos]=item;G_Debug(this,"tabsToOpen_ is now: "+this.tabsToOpen_)}
  925. ;CLB_RestoreTabsUI.resetItems=function(){this.windowsToOpen_=[];this.tabsToOpen_={}}
  926. ;CLB_RestoreTabsUI.updateStart=(CLB_RestoreTabsUI.updateProgress=(CLB_RestoreTabsUI.updateFailure=(CLB_RestoreTabsUI.updateComplete=(CLB_RestoreTabsUI.syncProgress=(CLB_RestoreTabsUI.syncFailure=function(){}
  927. )))));CLB_RestoreTabsUI.syncStart=function(){G_Debug(this,"Received syncStart. Resetting items.");this.resetItems()}
  928. ;CLB_RestoreTabsUI.syncComplete=function(){G_Debug(this,"Received syncComplete.");if(!this.isReconnecting){G_Debug(this,"Not showing restore UI because this is a resync or settings change sync.");return}if(!CLB_app.prefs.getPref("restoreui-on-resync",true)){G_Debug(this,"Not showing restore UI because restoreui-on-resync pref is set to false.");return}this.checkDupe_(null);if(!this.windowsToOpen_.length){G_Debug(this,"Not showing restore UI because there are no windows to restore.");return}G_Debug(
  929. this,"Telling instances to restore...");Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService).notifyObservers(this,"clb-show-restore",null);this.isReconnecting=false}
  930. ;CLB_RestoreTabsUI.checkDupe_=function(startingWin){G_Debug(this,"Checking whether the synced state is a dupe of the current state");var winMed=Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);var currentWindows=winMed.getEnumerator("navigator:browser");var syncedTabsLookup={};var currentTabsLookup={};var tabBrowser;var win;G_Debug(this,"Iterating current windows... startinWin: "+startingWin);while(currentWindows.hasMoreElements()){win=currentWindows.getNext();G_Debug(
  931. this,"window: "+win);if(win==startingWin){G_Debug(this,"Found starting window. Arguments: "+win.arguments[0]);win.arguments[0].split("|").forEach(function(url){currentTabsLookup[url]=true}
  932. )}else{G_Debug(this,"Iterating tabs...");tabBrowser=win.document.getElementById("content");for(var i=0,browser;browser=tabBrowser.browsers[i];i++){currentTabsLookup[browser.contentWindow.location.href]=true}}}for(var winID in this.tabsToOpen_){for(var i=0,tab;tab=this.tabsToOpen_[winID][i];i++){syncedTabsLookup[tab.getProperty("url")]=true}}var syncedTabsList=getObjectProps(syncedTabsLookup);var currentTabsList=getObjectProps(currentTabsLookup);G_Debug(this,"synced tabs are: "+syncedTabsList);G_Debug(
  933. this,"current tabs are: "+currentTabsList);var xor=G_SetXOR(syncedTabsList,currentTabsList).xor;if(xor.length>0){G_Debug(this,"Not a dupe. Continuing...")}else{G_Debug(this,"This is a dupe. Cancelling restore UI.");this.resetItems()}}
  934. ;CLB_RestoreTabsUI.prototype.QueryInterface=function(iid){if(iid.equals(Ci.nsIObserver)||iid.equals(Ci.nsISupportsWeakReference)){return this}else{throw Components.results.NS_ERROR_NO_INTERFACE;}}
  935. ;CLB_RestoreTabsUI.prototype.observe=function(subject,topic,data){if(topic!="clb-show-restore"){G_DebugL(this,"ERROR: Unexpected topic {%s} received".subs(topic));return}G_Debug(this,"Received clb-show-restore. Showing restore UI.");this.populate_();this.infoBubble_.show(this.toolbarButton_)}
  936. ;CLB_RestoreTabsUI.prototype.cleanUpItemsToOpen_=function(){var windowsToOpen=CLB_RestoreTabsUI.windowsToOpen_;var tabsToOpen=CLB_RestoreTabsUI.tabsToOpen_;var winItem;G_Debug(this,"Cleaning up items to open");for(var winID in tabsToOpen){for(var i=tabsToOpen[winID].length-1;i>=0;i--){if(!isDef(tabsToOpen[winID][i])){G_DebugL(this,"ERROR: Removing undefined tab position at index "+"{%s} for window {%s}".subs(i,winID));tabsToOpen[winID].splice(i,1)}}}for(var i=windowsToOpen.length-1;i>=0;i--){winItem=
  937. windowsToOpen[i];if(!isDef(tabsToOpen[winItem.itemID])||tabsToOpen[winItem.itemID].length==0){G_Debug(this,"Removing window {%s} from list of windows to open because there are no associated tabs".subs(winItem.itemID));windowsToOpen.splice(i,1)}}}
  938. ;CLB_RestoreTabsUI.prototype.populate_=function(){G_Debug(this,"Populating windowsToOpen_: "+CLB_RestoreTabsUI.windowsToOpen_);var windowsToOpen=CLB_RestoreTabsUI.windowsToOpen_;var tabsToOpen=CLB_RestoreTabsUI.tabsToOpen_;var winItem,tabItem;while(this.restoreRows_.firstChild){this.restoreRows_.removeChild(this.restoreRows_.firstChild)}for(var i=0;i<windowsToOpen.length;i++){winItem=windowsToOpen[i];G_Debug(this,"winItem is: "+winItem);for(var j=0;j<tabsToOpen[winItem.itemID].length;j++){tabItem=
  939. tabsToOpen[winItem.itemID][j];G_Debug(this,"tabItem is: "+tabItem);if(!isDef(tabItem)){G_Debug(this,"Skipping undefined tabItem");continue}var row=this.doc_.createElement("row");var checkbox=this.doc_.createElement("checkbox");checkbox.setAttribute("class","clb-restore-checkbox");checkbox.setAttribute("checked",true);checkbox.setAttribute("label",this.ellipsize_(tabItem.getProperty("url"),CLB_RestoreTabsUI.MAX_URL_LENGTH));checkbox.addEventListener("CheckboxStateChange",this.updateRestoreAllEnabled_,
  940. false);this.checkboxLookup_[tabItem.itemID]=checkbox;var spacer=this.doc_.createElement("spacer");spacer.className="clb-restore-spacer";var hbox=this.doc_.createElement("hbox");var title=this.doc_.createElement("label");title.setAttribute("class","clb-restore-title");title.setAttribute("value",this.ellipsize_(tabItem.getProperty("title"),CLB_RestoreTabsUI.MAX_TITLE_LENGTH));hbox.setAttribute("align","center");hbox.appendChild(title);row.appendChild(checkbox);row.appendChild(spacer);row.appendChild(
  941. hbox);this.restoreRows_.appendChild(row)}if(i<windowsToOpen.length-1){var rule=this.doc_.createElement("box");rule.className="clb-restore-rule";this.restoreRows_.appendChild(rule)}}}
  942. ;CLB_RestoreTabsUI.prototype.hide=function(){this.infoBubble_.hide()}
  943. ;CLB_RestoreTabsUI.prototype.handleRestoreAll_=function(){G_Debug(this,"Restoring all checked windows.");var tabsToOpen=CLB_RestoreTabsUI.tabsToOpen_;CLB_InfoBubble.hideAll();for(var winID in tabsToOpen){for(var i=tabsToOpen[winID].length-1;i>=0;i--){var tabItem=tabsToOpen[winID][i];var checkbox=this.checkboxLookup_[tabItem.itemID];if(!checkbox.checked){G_Debug(this,"Removing item for unchecked tab {%s}".subs(tabItem.itemID));tabsToOpen[winID].splice(i,1)}}}this.cleanUpItemsToOpen_();this.restoreWindows_(
  944. this.win_)}
  945. ;CLB_RestoreTabsUI.prototype.restoreWindows_=function(firstWin){G_Debug(this,"Restoring all. firstWin: "+firstWin.__winID);var existingWindows=this.winMed_.getEnumerator("navigator:browser");var win;while(existingWindows.hasMoreElements()){win=existingWindows.getNext().QueryInterface(Ci.nsIDOMWindowInternal);if(win!=firstWin){G_Debug(this,"Closing existing win with id: "+win.__winID);win.close()}}CLB_RestoreTabsUI.windowsToOpen_.forEach(function(winItem){var winID=winItem.itemID;this.restoreWindow_(
  946. winID,CLB_RestoreTabsUI.tabsToOpen_[winID],firstWin);firstWin=null}
  947. ,this)}
  948. ;CLB_RestoreTabsUI.prototype.restoreWindow_=function(winID,tabs,opt_reuseWindow){G_Debug(this,"Restoring window. winID: {%s}, reuseWindow: {%s}, tabs: {%s}".subs(winID,opt_reuseWindow,tabs));var win=opt_reuseWindow||this.winWat_.openWindow(null,CLB_RestoreTabsUI.BROWSER_CHROME_URL,"_blank","chrome,all,dialog=no,resizable",null);var tabsOpener=this.restoreTabs_.bind(this,win,CLB_RestoreTabsUI.tabsToOpen_[winID]);if(opt_reuseWindow){tabsOpener()}else{win.QueryInterface(Ci.nsIDOMWindowInternal).addEventListener(
  949. "load",tabsOpener,false)}return win}
  950. ;CLB_RestoreTabsUI.prototype.restoreTabs_=function(win,tabsList){G_Debug(this,"Restoring tabs. win: {%s}, tabsList: {%s}".subs(win.__winID,tabsList));var tabbrowser=win.document.getElementById("content");var numTabsToKill=tabbrowser.tabContainer.childNodes.length;G_Debug(this,"numTabsToKill: {%s}".subs(numTabsToKill));for(var i=0;i<numTabsToKill;i++){tabbrowser.tabContainer.childNodes[i].collapsed=true;G_Debug(this,"collapsed previous tab num {%s}".subs(i))}tabsList.forEach(function(tabItem){try{
  951. G_Debug(this,"Opening tab {%s}".subs(tabItem.getProperty("url")));tabbrowser.addTab(tabItem.getProperty("url"))}catch(e){if(e.result==Components.results.NS_ERROR_FILE_NOT_FOUND){G_Debug(this,"WARNING: Opening tab caused error: {%s}".subs(e))}else{throw e;}}var tab=tabbrowser.tabContainer.lastChild;if(tabItem.getProperty("activeTab")=="true"){G_Debug(this,"Selecting tab");tabbrowser.selectedTab=tab}}
  952. ,this);for(var j=0;j<numTabsToKill;j++){tabbrowser.removeTab(tabbrowser.tabContainer.firstChild);G_Debug(this,"Killed previous tab num: {%s}".subs(j))}}
  953. ;CLB_RestoreTabsUI.prototype.ellipsize_=function(val,len){if(!val){return""}else if(val.length>len){return val.substring(0,len)+"..."}else{return val}}
  954. ;CLB_RestoreTabsUI.prototype.updateRestoreAllEnabled_=function(){G_Debug(this,"Updating restore button disabledness");for(var i=0,row;row=this.restoreRows_.childNodes[i];i++){if(row.firstChild&&row.firstChild.checked){G_Debug(this,"Item at index {%s} is checked. Setting button enabled.".subs(i));this.restoreAllButton_.disabled=false;return}}G_Debug(this,"Checked {%s} items. None were checked. Setting button disabled.".subs(i));this.restoreAllButton_.disabled=true}
  955. ;CLB_RestoreTabsUI.debugZone="CLB_RestoreTabsUI";CLB_RestoreTabsUI.prototype.debugZone="CLB_RestoreTabsUI";G_debugService.loggifier.loggify(CLB_RestoreTabsUI);G_debugService.loggifier.loggify(CLB_RestoreTabsUI.prototype);
  956. function CLB_SettingsForm(win){bindMethods(this);this.win_=win;this.doc_=this.win_.document;this.dialog_=this.doc_.documentElement;this.componentSelector_=new CLB_ComponentSelector(this.doc_.getElementById("clb-component-selector"));this.promptSvc_=Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);this.okButton_=this.dialog_.getButton("accept");this.resyncButton_=this.doc_.getElementById("clb-resync-button");this.tokenField_=this.doc_.getElementById("clb-restart-text")
  957. ;this.showButton_=this.doc_.getElementById("clb-show-button");this.usernameField_=this.doc_.getElementById("clb-username");this.changeLoginButton_=this.doc_.getElementById("clb-change-login");this.userDesc_=this.doc_.getElementById("clb-user-desc");this.nouserDesc_=this.doc_.getElementById("clb-nouser-desc");this.settingsDisabledDesc_=this.doc_.getElementById("clb-settings-disabled");this.syncedComponents_=[];this.encryptedComponents_=[];this.enabledComponents_=[];this.disabledComponents_=[];this.clearedComponents_=
  958. [];this.progressDlg_=null;this.progressLbl_=null;this.win_.addEventListener("load",this.handleLoad,false);this.win_.addEventListener("unload",this.handleUnload,false)}
  959. CLB_SettingsForm.LAST_UPDATES=-1;CLB_SettingsForm.SETTINGS=0;CLB_SettingsForm.IMPORT=1;CLB_SettingsForm.RESYNC=2;CLB_SettingsForm.prototype.syncStart=(CLB_SettingsForm.prototype.updateStart=(CLB_SettingsForm.prototype.updateProgress=function(){}
  960. ));CLB_SettingsForm.prototype.handleLoad=function(){this.componentSelector_.load();var token=CLB_app.getToken();if(!token){token=""}this.tokenField_.setAttribute("value",token);var username=CLB_app.getUsername();if(!username){this.userDesc_.setAttribute("hidden","true");this.nouserDesc_.setAttribute("hidden","false")}else{this.usernameField_.textContent=username}this.dialog_.setAttribute("width",CLB_BrowserOverlay.SETTINGS_DIALOG_WIDTH);this.win_.sizeToContent()}
  961. ;CLB_SettingsForm.prototype.handleUnload=function(){try{CLB_syncMan.removeObserver(this)}catch(e){G_Debug(this,"removeObserver was not required.");return}G_Debug(this,"WARNING: SyncManager observer still existed")}
  962. ;CLB_SettingsForm.prototype.handleShowButtonClicked=function(event){if(this.tokenField_.hasAttribute("type")){this.tokenField_.removeAttribute("type");this.showButton_.label="Hide"}else{this.tokenField_.setAttribute("type","password");this.showButton_.label="Show"}}
  963. ;CLB_SettingsForm.prototype.handleAccountSettingsClicked=function(event){this.win_.opener.open("https://www.google.com/accounts/ManageAccount?service=browserstate&hl=en")}
  964. ;CLB_SettingsForm.prototype.handleResyncClicked=function(e){this.win_.openDialog("chrome://browserstate/content/resyncer.xul","clb-resyncer","dialog,modal,centerscreen,chrome",this.startResync,this.cancelResync)}
  965. ;CLB_SettingsForm.prototype.startResync=function(child){this.stage_=CLB_SettingsForm.RESYNC;this.initProgressWin_(child);CLB_syncMan.addObserver(this);CLB_syncMan.startSync(true)}
  966. ;CLB_SettingsForm.prototype.cancelResync=function(){G_Debug(this,"Aborting downloader");CLB_syncMan.cancelSync()}
  967. ;CLB_SettingsForm.prototype.handleChangeLoginClicked=function(e){if(this.promptSvc_.confirm(null,"Warning","This will close your open windows and start the Google Browser Sync signup process. Your local settings will not be lost. OK to proceed?")){CLB_app.deleteUserSettings();this.win_.setTimeout(CLB_app.logOff.bind(CLB_app),5)}}
  968. ;CLB_SettingsForm.prototype.handleOKButtonClicked=function(){G_Debug(this,"Changing settings...");var oldSyncedComponents=CLB_app.getListPref("syncedComponents");var oldEncryptedComponents=CLB_app.getListPref("encryptedComponents");var choice=this.componentSelector_.getChoices();this.syncedComponents_=choice.syncedComponents;this.encryptedComponents_=choice.encryptedComponents;var syncedChanges=G_SetXOR(this.syncedComponents_,oldSyncedComponents);this.enabledComponents_=syncedChanges.left;this.disabledComponents_=
  969. syncedChanges.right;var encryptionChanges=G_SetXOR(this.encryptedComponents_,oldEncryptedComponents);this.encryptionChanges_=encryptionChanges.xor;this.clearedComponents_=G_SetMerge(this.disabledComponents_,this.encryptionChanges_);G_Debug(this,"Synced Components: %s".subs(this.syncedComponents_.join("|")));G_Debug(this,"Encrypted Components: %s".subs(this.encryptedComponents_.join("|")));G_Debug(this,"Enabled Components: %s".subs(this.enabledComponents_.join("|")));G_Debug(this,"Disabled Components: %s"
  970. .subs(this.disabledComponents_.join("|")));G_Debug(this,"Encryption Changes: %s".subs(this.encryptionChanges_.join("|")));if(syncedChanges.xor.length||encryptionChanges.xor.length){G_DebugL(this,"Opening Dialog");this.win_.openDialog("chrome://browserstate/content/resyncer.xul","clb-resyncer","dialog,modal,centerscreen,chrome",this.sendLastUpdates,this.cancelSettingsChange);return false}else{this.win_.setTimeout("window.close()",5)}}
  971. ;CLB_SettingsForm.prototype.sendLastUpdates=function(child){G_Debug(this,"Sending last updates.");this.initProgressWin_(child);if(CLB_syncMan.checkSending()){CLB_syncMan.cancelUpdate()}CLB_syncMan.addObserver(this);if(CLB_syncMan.checkPending()){this.stage_=CLB_SettingsForm.LAST_UPDATE;CLB_syncMan.sendPending();return}G_Debug(this,"No pending updates to send. Changing settings.");this.startSettingsChange()}
  972. ;CLB_SettingsForm.prototype.updateFailure=function(code,status,message){this.syncFailure(code,status,message)}
  973. ;CLB_SettingsForm.prototype.updateComplete=function(){this.startSettingsChange()}
  974. ;CLB_SettingsForm.prototype.startSettingsChange=function(){G_Debug(this,"Changing settings...");this.stage_=CLB_SettingsForm.SETTINGS;CLB_syncMan.changeSettings(this.syncedComponents_,this.encryptedComponents_,this.clearedComponents_,this.enabledComponents_,this.settingsChangeSuccess,this.syncFailure)}
  975. ;CLB_SettingsForm.prototype.cancelSettingsChange=function(){if(this.stage_==CLB_SettingsForm.LAST_UPDATE){G_Debug(this,"Cancelling last update");CLB_syncMan.cancelUpdate()}if(this.stage_==CLB_SettingsForm.SETTINGS){G_Debug(this,"Canceling settings change");CLB_syncMan.cancelChangeSettings()}if(this.stage_==CLB_SettingsForm.IMPORT){G_Debug(this,"Canceling downloader");CLB_syncMan.cancelSync()}}
  976. ;CLB_SettingsForm.prototype.settingsChangeSuccess=function(){G_Debug(this,"Settings Change Complete");this.stage_=CLB_SettingsForm.IMPORT;CLB_syncMan.startSync()}
  977. ;CLB_SettingsForm.prototype.syncProgress=function(state){this.progressLbl_.value=state}
  978. ;CLB_SettingsForm.prototype.syncFailure=function(code,status,message){G_DebugL(this,"Sync Failure - "+[code,status,message]);CLB_syncMan.removeObserver(this);if(!this.progressDlg_.closed){this.progressDlg_.setTimeout("window.close()",10)}if(this.stage_==CLB_SettingsForm.SETTINGS||this.stage_==CLB_SettingsForm.LAST_UPDATE||this.stage_==CLB_SettingsForm.IMPORT){this.win_.alert("Settings change did not complete, please try again later.")}else if(this.stage_==CLB_SettingsForm.RESYNC){this.win_.alert(
  979. "Resync of data did not complete, please try again later.")}}
  980. ;CLB_SettingsForm.prototype.syncComplete=function(){G_DebugL(this,"Sync Finished");CLB_syncMan.removeObserver(this);if(!this.progressDlg_.closed){this.progressDlg_.setTimeout("window.close()",10)}if(this.stage_==CLB_SettingsForm.IMPORT){this.win_.setTimeout("window.close()",50);return}this.componentSelector_.load()}
  981. ;CLB_SettingsForm.prototype.initProgressWin_=function(win){this.progressDlg_=win;this.progressLbl_=win.document.getElementById("clb-status")}
  982. ;CLB_SettingsForm.prototype.debugZone="CLB_SettingsForm";G_debugService.loggifier.loggify(CLB_SettingsForm.prototype);
  983. function CLB_SettingsSyncer(){return new CLB_PreferencesSyncer(CLB_SettingsSyncer.CONTRACT_ID,"Google Browser Sync Settings","CLB_PreferencesSyncer",CLB_SettingsSyncer.PREF_NAMES_)}
  984. CLB_SettingsSyncer.CONTRACT_ID="@google.com/browserstate/settings-syncer;1";CLB_SettingsSyncer.PREF_NAMES_=["extensions.browserstate.syncedComponents","extensions.browserstate.encryptedComponents","extensions.browserstate.reimportComponent."];
  985. function CLB_StartupSequence(){var winWat_=Cc["@mozilla.org/embedcomp/window-watcher;1"].getService(Ci.nsIWindowWatcher);var currentDialog_=null;var currentResult_=null;var sequenceSuccessHandler_=null;var sequenceFailureHandler_=null;var dialogClosedHandler_=null;this.debugZone="CLB_Startup";this.observe=function(aSubject,aTopic,aData){if(aTopic=="domwindowclosed"){this.handleWindowClosed(aSubject.QueryInterface(Ci.nsIDOMWindow))}else if(aTopic=="domwindowopened"){G_Debug(this,"ignoring domwindowopened topic"
  986. )}else{throw new Error("Caught unexpected topic {"+aTopic+"}.");}}
  987. ;this.start=function(sequenceSuccessHandler,sequenceFailureHandler){sequenceSuccessHandler_=sequenceSuccessHandler;sequenceFailureHandler_=sequenceFailureHandler;winWat_.registerNotification(this);this.startLogin()}
  988. ;this.handleWindowClosed=function(win){if(win==currentDialog_){currentDialog_=null;dialogClosedHandler_()}else{G_Debug(this,"WARNING: received domwindowclosed event, but not from the current window.")}}
  989. ;this.startLogin=function(){if(CLB_app.getKey()&&CLB_app.getEncryptedKey()&&CLB_app.getMID()){this.startSyncing()}else{this.showDialog("welcome",this.handleLoginComplete.bind(this))}}
  990. ;this.handleLoginComplete=function(){if(currentResult_.getProperty("success")){sequenceSuccessHandler_()}else{sequenceFailureHandler_()}}
  991. ;this.startSyncing=function(){this.showDialog("syncing",this.handleSyncingComplete.bind(this))}
  992. ;this.handleSyncingComplete=function(){if(currentResult_.getProperty("success")){sequenceSuccessHandler_()}else{sequenceFailureHandler_()}}
  993. ;this.showDialog=function(xulFileName,closedHandler){currentResult_=Cc["@mozilla.org/hash-property-bag;1"].createInstance(Ci.nsIWritablePropertyBag);currentDialog_=winWat_.openWindow(null,"chrome://browserstate/content/"+xulFileName+".xul","browserstate"+xulFileName,"centerscreen,chrome",currentResult_);dialogClosedHandler_=closedHandler}
  994. ;G_debugService.loggifier.loggify(this)}
  995. ;
  996. function CLB_SyncingForm(win){this.win=win;this.observing=false;this.loginUtil=new CLB_LoginUtil;this.result=this.win.arguments[0].QueryInterface(Components.interfaces.nsIWritablePropertyBag);this.result.setProperty("success",false);this.result.setProperty("invalidKey",false)}
  997. CLB_SyncingForm.ERROR_FORBIDDEN=403;CLB_SyncingForm.prototype.handleDialogLoad=function(){this.doc=this.win.document;this.statusElm=this.doc.getElementById("clb-status");this.progressElm=this.doc.getElementById("clb-progress");this.promptSvc=Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);if(CLB_app.browserPrefs.getPref("offline")){this.win.setTimeout(this.handleWorkingOffline.bind(this),10)}else if(CLB_app.isBackedOff()){this.win.setTimeout(this.handleBackedOff.bind(
  998. this),10)}else{this.startPing()}}
  999. ;CLB_SyncingForm.prototype.startPing=function(){this.req=CLB_RequestFactory.getRequest(CLB_RequestFactory.PING,null,this.handlePingSuccess.bind(this),this.handleError.bind(this,"Network connection error"),null,true);this.req.send(null)}
  1000. ;CLB_SyncingForm.prototype.handlePingSuccess=function(){if(this.req.channel.URI.spec!=CLB_RequestFactory.getURL(CLB_RequestFactory.PING)){this.cancel();this.win.alert("Network connection error. Please check your network settings and try again.");this.win.setTimeout("window.close()",0);return}this.startStartSession()}
  1001. ;CLB_SyncingForm.prototype.startStartSession=function(){var doc=CLB_XMLUtils.getDoc("StartSessionRequest",{uid:CLB_app.getSID(),mid:CLB_app.getMID(),key:CLB_app.getEncryptedKey()});this.req=CLB_RequestFactory.getRequest(CLB_RequestFactory.START_SESSION,null,this.handleStartSessionSuccess.bind(this),this.handleError.bind(this,"Error starting session"));this.req.send(doc)}
  1002. ;CLB_SyncingForm.prototype.handleWorkingOffline=function(){this.promptSvc.alert(this.win,"You Are Working Offline",CLB_Application.MESSAGE_WORKING_OFFLINE);CLB_app.setStatus(CLB_Application.STATUS_OFFLINE);this.win.setTimeout("window.close()",0)}
  1003. ;CLB_SyncingForm.prototype.handleBackedOff=function(){this.promptSvc.alert(this.win,"You Are Offline",CLB_Application.MESSAGE_BACKED_OFF);CLB_app.setStatus(CLB_Application.STATUS_BACKED_OFF);this.win.setTimeout("window.close()",0)}
  1004. ;CLB_SyncingForm.prototype.handleStartSessionSuccess=function(req){this.req=null;CLB_syncMan.addObserver(this);this.observing=true;this.syncing=true;CLB_syncMan.startSync()}
  1005. ;CLB_SyncingForm.prototype.syncProgress=function(state){this.statusElm.value=state}
  1006. ;CLB_SyncingForm.prototype.syncComplete=function(){this.observing=false;CLB_syncMan.removeObserver(this);this.result.setProperty("success",true);CLB_app.setStatus(CLB_Application.STATUS_ONLINE);this.win.setTimeout("window.close()",0)}
  1007. ;CLB_SyncingForm.prototype.syncFailure=function(code,status,message){this.handleError("Error synchronizing browser",code,status,message)}
  1008. ;CLB_SyncingForm.prototype.handleError=function(prefix,code,status,opt_message){this.cancel();if(CLB_app.isGAIATimeoutError(code,status,opt_message)){this.reauthenticate();return}G_DebugL(this,"ERROR:\n\tprefix:%s\n\tcode:%s\n\tstatus:%s\n\tmessage:%s".subs(prefix,code,status,opt_message));var message=CLB_app.handleServerError(code,status,opt_message);if(CLB_app.isInvalidKeyError(code,status,opt_message)||CLB_app.isInvalidUserError(code,status,opt_message)){CLB_app.deleteUserSettings();CLB_app.savePrefs(
  1009. );CLB_app.logOff();return}else if(code==CLB_RequestFactory.ERR_COULD_NOT_CONTACT_SERVER){this.win.alert("Network connection error. Please check your network settings and try again.")}else if(message){this.win.alert("Error: "+message)}else if(code==CLB_Updater.ERROR_UPLOAD_TOO_LARGE){this.win.alert("Upload too large. Try disabling some components and trying again.")}else{this.win.alert("Error '%s %s' occurred while syncing, please try again later.".subs(code,status))}CLB_app.setStatus(CLB_Application.STATUS_OFFLINE)
  1010. ;this.win.setTimeout("window.close()",0)}
  1011. ;CLB_SyncingForm.prototype.handleDialogCancel=function(){this.cancel()}
  1012. ;CLB_SyncingForm.prototype.reauthenticate=function(){var result=CLB_PasswordForm.show(this.win);if(!result.getProperty("success")){this.cancel();this.win.setTimeout("window.close()",0);return}this.reauthReq=this.loginUtil.startRequest(CLB_app.prefs.getPref("username"),result.getProperty("password"),this.handleReauthSuccess.bind(this),this.handleReauthFailure.bind(this))}
  1013. ;CLB_SyncingForm.prototype.handleReauthSuccess=function(req){this.reauthReq=null;var resp=this.loginUtil.parseResponse(req.responseText);CLB_app.setSID(resp["SID"]);this.startStartSession()}
  1014. ;CLB_SyncingForm.prototype.handleReauthFailure=function(code,status,message){if(code==CLB_SyncingForm.ERROR_FORBIDDEN){if(this.loginUtil.showErrorMessage(this.win,this.reauthReq.responseText)){this.reauthenticate()}else{this.win.setTimeout("window.close()",0)}}else{this.handleError("Error reauthenticating user",code,status,message)}}
  1015. ;CLB_SyncingForm.prototype.cancel=function(){if(this.req){G_Debug(this,"Aborting request...");this.req.abort()}if(this.reauthReq){G_Debug(this,"Aborting reauth request...");this.reauthReq.abort()}if(this.observing){G_Debug(this,"Removing syncman observer...");CLB_syncMan.removeObserver(this)}if(this.syncing){G_Debug(this,"Aborting downloader...");CLB_syncMan.cancelSync()}}
  1016. ;CLB_SyncingForm.prototype.debugZone="CLB_SyncingForm";G_debugService.loggifier.loggify(CLB_SyncingForm.prototype);
  1017. function CLB_SyncItem(opt_fields){if(!opt_fields){opt_fields={}}this.componentID=opt_fields.componentID;this.itemID=opt_fields.itemID;this.typeID=opt_fields.typeID;this.isRemove=opt_fields.isRemove?true:false;this.isRemoveAll=opt_fields.isRemoveAll?true:false;this.isEncrypted=opt_fields.isEncrypted?true:false;this.props_={};this.includesConflictResolution=false;if(opt_fields.properties){for(var name in opt_fields.properties){this.setProperty(name,opt_fields.properties[name])}}}
  1018. CLB_SyncItem.prototype.debugZone="CLB_SyncItem";CLB_SyncItem.debugZone="CLB_SyncItem";CLB_SyncItem.prototype.QueryInterface=function(iid){if(iid.equals(Ci.nsISupports)||iid.equals(Ci.GISyncItem)){return this}else{throw Components.results.NS_ERROR_NO_INTERFACE;}}
  1019. ;CLB_SyncItem.prototype.setProperty=function(name,val){this.props_[name]=val}
  1020. ;CLB_SyncItem.prototype.getProperty=function(name){return this.props_[name]}
  1021. ;CLB_SyncItem.prototype.hasProperty=function(name){return isDef(this.props_[name])}
  1022. ;CLB_SyncItem.prototype.deleteProperty=function(name){var val=this.getProperty(name);delete this.props_[name];return val}
  1023. ;CLB_SyncItem.prototype.clearProperties=function(){this.props_={}}
  1024. ;CLB_SyncItem.prototype.getPropertyNames=function(opt_count){var names=getObjectProps(this.props_);if(opt_count){opt_count.value=names.length}return names}
  1025. ;CLB_SyncItem.prototype.toString=function(){return"{CLB_SyncItem componentID=%s, typeID=%s, itemID=%s, isRemove=%s}".subs(this.componentID,this.typeID,this.itemID,this.isRemove)}
  1026. ;CLB_SyncItem.prototype.toStringVerbose=function(){var itemStr=this.toString();itemStr+=" properties = {";for(var prop in this.props_){itemStr+=" %s=%s, ".subs(prop,this.props_[prop])}itemStr+="}";return itemStr}
  1027. ;CLB_SyncItem.prototype.clone=function(){var newProps={};for(var propName in this.props_){newProps[propName]=this.props_[propName]}return new CLB_SyncItem({componentID:this.componentID,typeID:this.typeID,itemID:this.itemID,isRemove:this.isRemove,isRemoveAll:this.isRemoveAll,isEncrypted:this.isEncrypted,properties:newProps})}
  1028. ;CLB_SyncItem.prototype.updateFrom=function(otherItem){if(otherItem.componentID!=this.componentID||otherItem.typeID!=this.typeID||otherItem.itemID!=this.itemID){G_Debug(this,"Error: Cannot update from an item with a different it");return}this.isRemove=otherItem.isRemove;this.isEncrypted=otherItem.isEncrypted;this.clearProperties();otherItem.getPropertyNames().forEach(function(propName){this.props_[propName]=otherItem.getProperty(propName)}
  1029. ,this)}
  1030. ;CLB_SyncItem.prototype.equals=function(item){if(!(item instanceof CLB_SyncItem)){return false}if(this.componentID!=item.componentID||this.typeID!=item.typeID||this.itemID!=item.itemID||this.isEncrypted!=item.isEncrypted||this.isRemove!=item.isRemove||this.isRemoveAll!=item.isRemoveAll){return false}if(this.getPropertyNames().length!=item.getPropertyNames().length){return false}for(var propName in this.props_){if(this.props_[propName]!=item.props_[propName]){return false}}return true}
  1031. ;CLB_SyncItem.prototype.makeLookupKey=function(){var lookupKey=this.componentID+"/"+this.itemID;if(isDef(this.typeID)){lookupKey=lookupKey+"/"+this.typeID}return lookupKey}
  1032. ;CLB_SyncItem.prototype.crypt=function(cryptFunc){var key=CLB_app.getKey();if(!key){G_Debug(this,"WARNING: No key defined.");key=""}this.itemID=cryptFunc(this.itemID,key,false);if(isDef(this.typeID)){this.typeID=cryptFunc(this.typeID,key,false)}var newProperties={};for(var propertyName in this.props_){var val=this.props_[propertyName];if(isNull(val)){var newVal=null}else{var newVal=cryptFunc(String(val),key,true)}var newPropName=cryptFunc(propertyName,key,false);newProperties[newPropName]=newVal}
  1033. this.props_=newProperties}
  1034. ;CLB_SyncItem.prototype.encrypt=function(){if(!this.isEncrypted){this.crypt(CLB_Crypter.encryptString);this.isEncrypted=true}}
  1035. ;CLB_SyncItem.prototype.decrypt=function(){if(this.isEncrypted){this.crypt(CLB_Crypter.decryptString);this.isEncrypted=false}}
  1036. ;CLB_SyncItem.parseFromXML=function(xmlItem){var syncItem=new CLB_SyncItem;var child=null;for(var i=0;child=xmlItem.childNodes[i];i++){if(child.namespaceURI!=CLB_XMLUtils.gNamespace){G_DebugL(this,"ERROR: Unexpected namespace: {%s}".subs(child.namespaceURI));return null}if(child.localName=="componentID"){syncItem.componentID=child.textContent}else if(child.localName=="itemID"){syncItem.itemID=child.textContent}else if(child.localName=="typeID"){syncItem.typeID=child.textContent}else if(child.localName==
  1037. "isRemove"){syncItem.isRemove=true}else if(child.localName=="isRemoveAll"){syncItem.isRemoveAll=true}else if(child.localName=="isEncrypted"){syncItem.isEncrypted=true}else if(child.localName=="prop"){if(G_FirefoxXMLUtils.isNil(child)){syncItem.setProperty(child.getAttribute("name"),null)}else{syncItem.setProperty(child.getAttribute("name"),child.textContent)}}else{G_DebugL(this,"ERROR: Unexpected element {"+child.nodeName+"}");return null}}G_Debug(this,"Parsed item {%s}".subs(syncItem));return syncItem}
  1038.  
  1039. ;G_debugService.loggifier.loggify(CLB_SyncItem.prototype,"setProperty","getProperty");G_debugService.loggifier.loggify(CLB_SyncItem);
  1040. function CLB_SyncManager(){this.started_=false;this.importExisting=false;this.registeredComponents_={};this.registeredConflicts_={};this.syncedComponents_={};this.encryptedComponents_={};this.observers_=[];this.updateQueue_=new CLB_UpdateQueue;this.updater_=null;this.downloader_=null;this.updateTimer_=null;this.sendingUpdateQueue_=null;this.periodicRate_=null;this.immediateRate_=null;this.lastActive_=(new Date).getTime();this.zzz_=false;this.updateSuccessHandler_=this.handleUpdateSuccess.bind(this)
  1041. ;this.updateFailureHandler_=this.handleUpdateFailure.bind(this);this.notifyObserversProgress_=this.notifyObservers_.bind(this,"updateProgress")}
  1042. CLB_SyncManager.DEFAULT_IMMEDIATE_RATE=5;CLB_SyncManager.DEFAULT_PERIODIC_RATE=60;CLB_SyncManager.DEFAULT_NO_SLEEP_TILL=600;CLB_SyncManager.REIMPORT_PREF_PREFIX="extensions.browserstate.reimportComponent.";CLB_SyncManager.prototype.debugZone="CLB_SyncManager";CLB_SyncManager.prototype.QueryInterface=function(aIID){if(!aIID.equals(Ci.nsISupports)&&!aIID.equals(Ci.GISyncManager))throw Components.results.NS_ERROR_NO_INTERFACE;return this}
  1043. ;CLB_SyncManager.prototype.start=function(){this.refreshComponents();this.periodicRate_=CLB_app.prefs.getPref("periodicRate",CLB_SyncManager.DEFAULT_PERIODIC_RATE)*1000;this.immediateRate_=CLB_app.prefs.getPref("immediateRate",CLB_SyncManager.DEFAULT_IMMEDIATE_RATE)*1000;this.noSleepTill_=CLB_app.prefs.getPref("noSleepTill",CLB_SyncManager.DEFAULT_NO_SLEEP_TILL)*1000;G_Debug(this,"Initialized periodic rate to: {%s}.".subs(this.periodicRate_));G_Debug(this,"Initialized immediate rate to: {%s}.".subs(
  1044. this.immediateRate_));G_Debug(this,"Brooklyn is {%s} milliseconds away.".subs(this.noSleepTill_));this.started_=true;this.startSyncedComponents_();this.schedule_(this.periodicRate_)}
  1045. ;CLB_SyncManager.prototype.stop=function(){this.cancelScheduledSend_();this.started_=false;G_Debug(this,"sync manager stopped")}
  1046. ;CLB_SyncManager.prototype.startComponent=function(componentID){if(!isDef(this.registeredComponents_[componentID])){G_Debug(this,"ERROR: Cannot start component '%s'; "+"component does not exist".subs(componentID));return}G_Debug(this,"Starting component %s".subs(componentID));this.registeredComponents_[componentID].start()}
  1047. ;CLB_SyncManager.prototype.stopComponent=function(componentID){if(!isDef(this.registeredComponents_[componentID])){G_Debug(this,"ERROR: Cannot stop component '%s'; "+"component does not exist".subs(componentID));return}G_Debug(this,"Stopping component '%s'".subs(componentID));this.registeredComponents_[componentID].stop()}
  1048. ;CLB_SyncManager.prototype.registerComponent=function(component){this.registeredComponents_[component.componentID]=component}
  1049. ;CLB_SyncManager.prototype.unregisterComponent=function(component){delete this.registeredComponents_[component.componentID]}
  1050. ;CLB_SyncManager.prototype.registerConflict=function(component,typeID,name,properties){if(!isDef(this.registeredConflicts_[component.componentID])){this.registeredConflicts_[component.componentID]=[]}var props=[];while(properties.hasMoreElements()){props.push(properties.getNext())}this.registeredConflicts_[component.componentID].push(new CLB_Conflict(name,typeID,props))}
  1051. ;CLB_SyncManager.prototype.getComponents=function(){var retVal=[];for(var c in this.registeredComponents_){retVal.push(this.registeredComponents_[c])}return new CLB_ArrayEnumerator(retVal)}
  1052. ;CLB_SyncManager.prototype.getComponent=function(id){return this.registeredComponents_[id]}
  1053. ;CLB_SyncManager.prototype.update=function(newItem){if(!this.started_){G_DebugL(this,"ERROR: Received unexpected update while offline for item %s".subs(newItem));return}var comp=this.syncedComponents_[newItem.componentID];if(!comp){G_DebugL(this,"ERROR: Received update from non-synced or unknown component: {%s}".subs(newItem));return}if(CLB_app.getStatus()!=CLB_Application.STATUS_ONLINE&&!comp.syncOfflineChanges){G_DebugL(this,"Received unexpected update while offline from component which does not sync offline changes. Item: "
  1054. +newItem);return}this.updateQueue_.addItem(newItem);if(this.started_){this.schedule_(this.immediateRate_)}}
  1055. ;CLB_SyncManager.prototype.addObserver=function(observer){this.observers_.push(observer)}
  1056. ;CLB_SyncManager.prototype.removeObserver=function(observer){for(var i=0;i<this.observers_.length;i++){if(this.observers_[i]==observer){this.observers_.splice(i,1);return}}throw new Error("Specified observer not found.");}
  1057. ;CLB_SyncManager.prototype.cancelSync=function(){if(this.currentSyncer_){this.currentSyncer_.abort();this.currentSyncer_=null;this.syncFailure(-1,"cancel","cancel")}else{G_Debug(this,"Warning: no currentSyncer when trying to cancel sync")}}
  1058. ;CLB_SyncManager.prototype.startSync=function(opt_skipSettings){G_Debug(this,"Start Sync Called...");G_Debug(this,"Refreshing synced and encrypted components...");this.refreshComponents();this.stopSyncedComponents();this.notifyObservers_("syncStart");if(opt_skipSettings||CLB_app.prefs.getPref("reimport",false)){var componentsToImport=[];componentsToImport.push(CLB_SettingsSyncer.CONTRACT_ID);for(var componentID in this.syncedComponents_){componentsToImport.push(componentID)}this.startDownload(componentsToImport)
  1059. ;return}G_Debug(this,"Syncing just settings...");var syncedComponents={};syncedComponents[CLB_SettingsSyncer.CONTRACT_ID]=CLB_app.settingsSyncer;this.lastSyncedComponents_=CLB_app.getListPref("syncedComponents");G_Debug(this,"Creating settings downloader...");this.currentSyncer_=new CLB_Downloader(syncedComponents,null,this.registeredConflicts_,null,this.getTimestamp("lastUpdate"),this.getTimestamp("lastSync"),this.settingsSyncComplete.bind(this),this.syncFailure.bind(this),this.notifyObservers_.bind(
  1060. this,"syncProgress"))}
  1061. ;CLB_SyncManager.prototype.settingsSyncComplete=function(){G_Debug(this,"Settings Sync Complete");this.refreshComponents();var componentsToImport=[];for(var i=0,item;item=CLB_app.settingsSyncer.syncedItems[i];i++){if(item.componentID==CLB_app.settingsSyncer.componentID&&item.itemID.startsWith(CLB_SyncManager.REIMPORT_PREF_PREFIX)){componentsToImport.push(decodeURIComponent(item.itemID.substring(CLB_SyncManager.REIMPORT_PREF_PREFIX.length)))}}var newSyncedComponents=CLB_app.getListPref("syncedComponents"
  1062. );newSyncedComponents=G_SetXOR(this.lastSyncedComponents_,newSyncedComponents).right;componentsToImport=G_SetMerge(componentsToImport,newSyncedComponents);G_Debug(this,"Importing these components: "+componentsToImport);this.startDownload(componentsToImport)}
  1063. ;CLB_SyncManager.prototype.changeSettings=function(syncedComponents,encryptedComponents,clearedComponents,reimportComponents,onSuccess,onFailure){if(this.updater_){throw new Error("Cannot change settings. Update in progress.");}if(this.updateQueue_.hasPending()){throw new Error("Cannot change settings. Changes are pending.");}var pending=[];for(var i=0;i<clearedComponents.length;i++){var componentID=clearedComponents[i];if(!this.registeredComponents_[componentID]){G_Debug(this,"WARNING: Could not clear Component, '%s' not registered"
  1064. .subs(componentID));continue}G_Debug(this,"%s isRemoveAll created".subs(componentID));pending.push(new CLB_SyncItem({componentID:componentID,isRemoveAll:true}))}pending.push(new CLB_SyncItem({componentID:CLB_SettingsSyncer.CONTRACT_ID,itemID:"extensions.browserstate.syncedComponents",properties:{value:syncedComponents.join(",")}}));pending.push(new CLB_SyncItem({componentID:CLB_SettingsSyncer.CONTRACT_ID,itemID:"extensions.browserstate.encryptedComponents",properties:{value:encryptedComponents.join(
  1065. ",")}}));for(var i=0;i<reimportComponents.length;i++){var componentID=reimportComponents[i];pending.push(new CLB_SyncItem({componentID:CLB_SettingsSyncer.CONTRACT_ID,itemID:CLB_SyncManager.REIMPORT_PREF_PREFIX+encodeURIComponent(componentID),properties:{value:1}}))}this.updater_=new CLB_Updater;this.updater_.start(pending,false,this.changeSettingsComplete.bind(this,onSuccess),this.changeSettingsFailure.bind(this,onFailure),function(){}
  1066. ,true,false)}
  1067. ;CLB_SyncManager.prototype.changeSettingsComplete=function(onSuccess){this.updater_=null;onSuccess()}
  1068. ;CLB_SyncManager.prototype.changeSettingsFailure=function(onFailure,code,status,message){this.updater_=null;onFailure(code,status,message)}
  1069. ;CLB_SyncManager.prototype.cancelChangeSettings=function(){if(this.updater_){this.updater_.cancel();this.updater_=null}else{G_Debug(this,"Warning: no updater when trying to cancel update")}}
  1070. ;CLB_SyncManager.prototype.startDownload=function(componentsToImport){this.refreshComponents();if(this.syncedComponents_[CLB_PasswordSyncer.CONTRACT_ID]){if(CLB_app.passwordSyncer.unlockPasswordStore()&&CLB_app.prefs.getPref("reimportPasswords",false)){componentsToImport.push(CLB_PasswordSyncer.CONTRACT_ID)}}var pending;if(componentsToImport.length){pending=[];CLB_app.prefs.setPref("reimport",true);CLB_app.savePrefs();var alreadyDone={};for(var i=0;i<componentsToImport.length;i++){var componentID=
  1071. componentsToImport[i];if(isDef(alreadyDone[componentID])){G_Debug(this,"Duplicate component '%s', skipping".subs(componentID));continue}alreadyDone[componentID]=true;G_Debug(this,"Importing component '%s'".subs(componentID));var items=this.registeredComponents_[componentID].getCurrentItems();if(jsInstanceOf(items,Ci.nsISimpleEnumerator)){pending.push(items)}else{G_Debug(this,"Error: getCurrentItems didn't return an enumerator")}}}else{if(this.checkSending()){this.cancelUpdate()}pending=this.updateQueue_.getPending(
  1072. )}this.updateQueue_.reset();this.currentSyncer_=new CLB_Downloader(this.syncedComponents_,componentsToImport,this.registeredConflicts_,pending,this.getTimestamp("lastUpdate"),this.getTimestamp("lastSync"),this.syncComplete.bind(this),this.syncFailure.bind(this),this.notifyObservers_.bind(this,"syncProgress"))}
  1073. ;CLB_SyncManager.prototype.stopSyncedComponents=function(){G_Debug(this,"Stopping started components...");if(!this.started_){G_Debug(this,"SyncManager is not started. Nothing to do.");return}for(var compID in this.syncedComponents_){G_Debug(this,"Stopping {%s}".subs(compID));this.syncedComponents_[compID].stop()}}
  1074. ;CLB_SyncManager.prototype.startSyncedComponents_=function(){G_Debug(this,"Starting synced components...");if(!this.started_){G_Debug(this,"SyncManager is not started. Nothing to do.");return}for(var compID in this.syncedComponents_){G_Debug(this,"Starting {%s}".subs(compID));this.syncedComponents_[compID].start()}}
  1075. ;CLB_SyncManager.prototype.syncComplete=function(lastUpdate){this.currentSyncer_=null;CLB_app.prefs.setPref("reimport",false);CLB_app.prefs.setPref("hasOfflineData",false);this.clearedComponents_={};if(lastUpdate){CLB_app.prefs.setPref("lastUpdate",lastUpdate);CLB_app.prefs.setPref("lastSync",lastUpdate);G_Debug(this,"Set lastSync and lastUpdate to: "+lastUpdate)}CLB_app.savePrefs();this.notifyObservers_("syncComplete");this.startSyncedComponents_()}
  1076. ;CLB_SyncManager.prototype.syncFailure=function(code,status,message){this.currentSyncer_=null;this.notifyObservers_("syncFailure",code,status,message);this.startSyncedComponents_()}
  1077. ;CLB_SyncManager.prototype.checkPending=function(){for(var componentID in this.syncedComponents_){this.syncedComponents_[componentID].beforeUpdate()}return this.updateQueue_.hasPending()}
  1078. ;CLB_SyncManager.prototype.checkSending=function(){return Boolean(this.updater_)}
  1079. ;CLB_SyncManager.prototype.sendPending=function(opt_finalSend,opt_pingSucceeded){G_Debug(this,"SendPending for {%s} items".subs(this.updateQueue_.pendingSize()));if(this.updater_){if(opt_finalSend){G_Debug(this,"Previous update still pending, but this is a final send, so we're recycling it and forging onwards. Tally ho!");this.cancelUpdate()}else{G_Debug(this,"WARNING: Previous update still pending. Skipping request.");return false}}if(this.currentSyncer_&&!opt_finalSend){G_Debug(this,"WARNING: Previous sync still running. Skipping request."
  1080. );return}this.cancelScheduledSend_();if(!opt_finalSend){this.checkPending()}this.maybeSleep_();if(this.zzz_){return}this.notifyObservers_("updateStart");this.updater_=new CLB_Updater;if(!opt_pingSucceeded&&CLB_app.getStatus()==CLB_Application.STATUS_UPDATE_ERROR&&CLB_app.canReconnect()){G_Debug(this,"Sending empty ping");var req=CLB_RequestFactory.getRequest(CLB_RequestFactory.PING,null,this.handlePingSuccess.bind(this),this.handlePingFailure.bind(this),this.notifyObserversProgress_,true);req.send(
  1081. null)}else{this.sendingUpdateQueue_=this.updateQueue_;this.updateQueue_=new CLB_UpdateQueue;this.updater_.start(this.sendingUpdateQueue_.getPending(),true,this.updateSuccessHandler_,this.updateFailureHandler_,this.notifyObserversProgress_,CLB_app.canSend(),true)}}
  1082. ;CLB_SyncManager.prototype.handlePingFailure=function(code,status,opt_message){this.updater_=null;this.notifyObservers_("updateFailure",code,status,opt_message);G_Debug(this,"Ping failed");CLB_app.handleServerError(code,status,opt_message);if(this.started_){this.schedule_(this.periodicRate_)}}
  1083. ;CLB_SyncManager.prototype.handlePingSuccess=function(){G_Debug(this,"Ping succeeded");this.updater_=null;this.sendPending(false,true)}
  1084. ;CLB_SyncManager.prototype.handleUpdateFailure=function(code,status,opt_message){this.updater_=null;this.notifyObservers_("updateFailure",code,status,opt_message);if(code==CLB_Updater.ERROR_APPLICATION_PRE_FILE_WRITE){G_Debug(this,"Recycling {%s} items from failed update".subs(this.sendingUpdateQueue_.pendingSize()));this.sendingUpdateQueue_.append(this.updateQueue_);this.updateQueue_=this.sendingUpdateQueue_}CLB_app.handleServerError(code,status,opt_message);if(this.started_){this.schedule_(this.periodicRate_)
  1085. }}
  1086. ;CLB_SyncManager.prototype.handleUpdateSuccess=function(opt_newLastUpdate){this.updater_=null;if(isDef(opt_newLastUpdate)){CLB_app.prefs.setPref("lastUpdate",opt_newLastUpdate);G_Debug(this,"Set lastUpdate to: "+opt_newLastUpdate)}CLB_app.prefs.setPref("hasOfflineData",false);CLB_app.savePrefs();this.notifyObservers_("updateComplete");if(this.started_){this.schedule_(this.periodicRate_)}}
  1087. ;CLB_SyncManager.prototype.refreshSyncedComponents_=function(){G_Debug(this,"Refreshing syncedComponents_ lookup... ");this.syncedComponents_={};CLB_app.getListPref("syncedComponents").forEach(function(id){if(!this.registeredComponents_[id]){G_Debug(this,"WARNING: The component {%s} has not been registered. "+"Skipping.".subs(id))}else{this.syncedComponents_[id]=this.registeredComponents_[id];G_Debug(this,"  added component {%s}".subs(id))}}
  1088. ,this);G_Debug(this,"Done.")}
  1089. ;CLB_SyncManager.prototype.refreshEncryptedComponents_=function(){G_Debug(this,"Refreshing encryptedComponents_ lookup... ");this.encryptedComponents_={};CLB_app.getListPref("encryptedComponents").forEach(function(id){if(!this.registeredComponents_[id]){G_Debug(this,"WARNING: The component {%s} has not been registered. "+"Skipping.".subs(id))}else{this.encryptedComponents_[id]=this.registeredComponents_[id];G_Debug(this,"  added component {%s}".subs(id))}}
  1090. ,this);G_Debug(this,"Done.")}
  1091. ;CLB_SyncManager.prototype.refreshComponents=function(){this.refreshSyncedComponents_();this.refreshEncryptedComponents_()}
  1092. ;CLB_SyncManager.prototype.isEncryptedComponent=function(componentID){if(this.registeredComponents_[componentID].requiresEncryption){return true}return isDef(this.encryptedComponents_[componentID])}
  1093. ;CLB_SyncManager.prototype.schedule_=function(timeoutInMilliseconds){if(timeoutInMilliseconds<=0){G_Debug(this,"Skipping schedule because timeout is zero.")}else{this.cancelScheduledSend_();G_Debug(this,"Scheduling send in {%s} milliseconds".subs(timeoutInMilliseconds));this.updateTimer_=new G_Alarm(this.sendPending.bind(this),timeoutInMilliseconds)}}
  1094. ;CLB_SyncManager.prototype.cancelScheduledSend_=function(){G_Debug(this,"Canceling scheduled send");if(!this.updateTimer_){G_Debug(this,"No scheduled send found to cancel");return}this.updateTimer_.cancel();this.updateTimer_=null}
  1095. ;CLB_SyncManager.prototype.cancelUpdate=function(){if(!this.checkSending()){G_Debug(this,"No existing update to recycle. Continuing.");return}this.updater_.cancel();this.updater_=null;if(isNull(this.sendingUpdateQueue_)){G_DebugL(this,"ERROR: Expected sendingUpdateQueue to be non-null since updater is. Skipping.");return}G_Debug(this,"Recycling existing update containing {%s} items".subs(this.sendingUpdateQueue_.pendingSize()));this.sendingUpdateQueue_.append(this.updateQueue_);this.updateQueue_=
  1096. this.sendingUpdateQueue_}
  1097. ;CLB_SyncManager.prototype.notifyObservers_=function(methName){var meth=arguments[0];var args=Array.prototype.splice.apply(arguments,[1,arguments.length]);for(var i=0,observer;observer=this.observers_[i];i++){if(!observer[meth]){G_Debug(this,"WARNING: observer does not have method {%s}.".subs(meth));continue}observer[meth].apply(observer,args)}}
  1098. ;CLB_SyncManager.prototype.maybeSleep_=function(){var now=(new Date).getTime();var msSinceLastActive=now-this.lastActive_;G_Debug(this,"Checking whether should sleep. ms since last active: {%s}, limit: {%s}".subs(msSinceLastActive,this.noSleepTill_));if(msSinceLastActive>this.noSleepTill_){G_DebugL(this,"There has been no activity for too long. Going to sleep. zzz...");this.zzz_=true}}
  1099. ;CLB_SyncManager.prototype.updateSleepyState=function(){this.lastActive_=(new Date).getTime();if(this.zzz_){this.zzz_=false;G_DebugL(this,"Waking up! lastActive is now: {%s}.".subs(this.lastActive_));this.sendPending()}}
  1100. ;CLB_SyncManager.prototype.getTimestamp=function(name){return CLB_app.prefs.getPref(name,(new Date(0)).toISO8601String())}
  1101. ;G_debugService.loggifier.loggify(CLB_SyncManager.prototype,"maybeWakeUp");
  1102. function CLB_TabSyncer(){bindMethods(this);this.winMed_=Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);this.nextID_=1;this.started_=false;this.syncedItems_=[];this.queuedUnload_=null}
  1103. CLB_TabSyncer.UNLOAD_QUEUE_SECONDS=15;CLB_TabSyncer.prototype.componentID="@google.com/browserstate/tab-syncer;1";CLB_TabSyncer.prototype.componentName="Tabs and Windows";CLB_TabSyncer.prototype.encryptionRequred=false;CLB_TabSyncer.prototype.syncOfflineChanges=false;CLB_TabSyncer.prototype.syncBehavior=Ci.GISyncComponent.SYNC_SINCE_LAST_SYNC;CLB_TabSyncer.prototype.start=function(){this.started_=true;var initialTabs=this.getCurrentItems();G_Debug(this,"Sending remove items for tabsyncer to syncman."
  1104. );if(this.syncedItems_){for(var i=0,syncedItem;syncedItem=this.syncedItems_[i];i++){CLB_syncMan.update(new CLB_SyncItem({componentID:syncedItem.componentID,typeID:syncedItem.typeID,itemID:syncedItem.itemID,isRemove:true}))}this.syncedItems_=[]}var updateItem;while(updateItem=initialTabs.getNext()){G_Debug(this,"Sending update item to syncman: "+updateItem);CLB_syncMan.update(updateItem)}}
  1105. ;CLB_TabSyncer.prototype.stop=function(){this.started_=false}
  1106. ;CLB_TabSyncer.prototype.onBeforeResolveConflict=function(item){}
  1107. ;CLB_TabSyncer.prototype.onItemConflict=function(conflict,oldItem,newItem){return new CLB_ArrayEnumerator([])}
  1108. ;CLB_TabSyncer.prototype.onItemAvailable=function(item){G_Debug(this,"onItemAvailable - item: "+item);if(!isDef(item.itemID)||!isDef(item.typeID)||!isDef(item.componentID)){G_DebugL(this,"ERROR: Skipping malformed item. "+"itemID: {%s}, typeID: {%s}, componentID: {%s}".subs(item.itemID,item.typeID,item.componentID));return}if(item.isRemove){G_Debug(this,"WARNING: Skipping delete item: "+item);return}if(item.typeID=="window"){CLB_RestoreTabsUI.addWindowItem(item)}else if(item.typeID=="tab"){CLB_RestoreTabsUI.addTabItem(
  1109. item)}else{G_DebugL(this,"Skipping item with unexpected {%s}".subs(item.typeID));return}this.syncedItems_.push(item);this.updateID_(item.itemID)}
  1110. ;CLB_TabSyncer.prototype.getItemByID=function(id,typeid){return null}
  1111. ;CLB_TabSyncer.prototype.getCurrentItems=function(){var result=[];var winEnum=this.winMed_.getEnumerator("navigator:browser");while(winEnum.hasMoreElements()){var win=winEnum.getNext();var xulWin=win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem).treeOwner.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIXULWindow);if(!isDef(win.__winID)){win.__winID=this.getNextID_()}var newItem=new CLB_SyncItem({componentID:this.componentID,
  1112. typeID:"window",itemID:win.__winID,properties:{topWindow:xulWin.zLevel==Ci.nsIXULWindow.highestZ}});result.push(newItem);var tab;var tabBrowser=win.document.getElementById("content");for(var tabIndex=0;tab=tabBrowser.browsers[tabIndex];tabIndex++){G_Debug(this,"checking tabID: "+tab.__tabID);if(!isDef(tab.__tabID)){tab.__tabID=this.getNextID_()}var newItem=new CLB_SyncItem({componentID:this.componentID,typeID:"tab",itemID:tab.__tabID,properties:{url:tab.contentWindow.location.href,title:tab.contentDocument.title,
  1113. tabIndex:tabIndex,activeTab:tabBrowser.selectedBrowser==tab,windowID:win.__winID}});result.push(newItem)}}return new CLB_ArrayEnumerator(result)}
  1114. ;CLB_TabSyncer.prototype.onLoad=function(win){G_Debug(this,"Received onload event for win {%s}".subs(win.__winID));if(!this.shouldProcessEvents_()){return}if(isDef(win.__winID)){G_Debug(this,"Window already created with winID {%s}. Ignoring.".subs(win.__winID));return}win.__winID=this.getNextID_();var syncItem=new CLB_SyncItem({componentID:this.componentID,typeID:"window",itemID:win.__winID});G_Debug(this,"Sending new window item to syncman: "+syncItem);CLB_syncMan.update(syncItem);var tabBrowser=
  1115. win.document.getElementById("content");if(tabBrowser){for(var i=0,browser;browser=tabBrowser.browsers[i];i++){this.createTab_(win,browser,tabBrowser.selectedBrowser==browser,i)}}else{G_Debug(this,"ERROR: Could not get first browser.")}}
  1116. ;CLB_TabSyncer.prototype.ensureTabCreated_=function(win,browser,isSelected){if(isDef(browser.__tabID)){G_Debug(this,"Tab already created with tabID {%s}. Ignoring.".subs(browser.__tabID));return false}if(!isDef(win.__winID)){G_Debug(this,"ERROR: Could not get winID from window. Ignoring.");return false}var tabPos=CLB_TabSyncer.findBrowserPosition(win,browser);if(tabPos==-1){G_Debug(this,"ERROR: Could not find position of tab. Ignoring.");return false}this.createTab_(win,browser,isSelected,tabPos)
  1117. }
  1118. ;CLB_TabSyncer.prototype.createTab_=function(win,browser,isSelected,tabPos){browser.__tabID=this.getNextID_();G_Debug(this,"Assigned ID {%s} to new tab".subs(browser.__tabID));var syncItem=new CLB_SyncItem({componentID:this.componentID,typeID:"tab",itemID:browser.__tabID});syncItem.setProperty("tabIndex",tabPos);syncItem.setProperty("activeTab",isSelected);syncItem.setProperty("windowID",win.__winID);G_Debug(this,"Sending new tab item to syncman: "+syncItem);CLB_syncMan.update(syncItem);return true}
  1119.  
  1120. ;CLB_TabSyncer.prototype.onTabLoad=function(win,ev){G_Debug(this,"tabload for window {%s}.".subs(win.__winID));if(!this.shouldProcessEvents_()){return}this.ensureTabCreated_(win,ev.browser,ev.isSelected)}
  1121. ;CLB_TabSyncer.prototype.onTabUnload=function(win,ev){G_Debug(this,"tabunload for tab {%s}".subs(ev.browser.__tabID));if(!this.shouldProcessEvents_()){return}var browser=ev.browser;if(!isDef(browser.__tabID)){G_Debug(this,"ERROR: Could not find tabID for unloaded tab.");return}browser.__isUnloading=true;var syncItem=new CLB_SyncItem({componentID:this.componentID,typeID:"tab",itemID:browser.__tabID,isRemove:true});G_Debug(this,"Sending remove tab item to syncman: "+syncItem);CLB_syncMan.update(syncItem)
  1122. ;G_Debug(this,"Resetting all tab indicies");var tabBrowser=win.document.getElementById("content");this.resetTabIndicies_(tabBrowser,0,tabBrowser.browsers.length-1)}
  1123. ;CLB_TabSyncer.prototype.onPageShow=function(win,ev){G_Debug(this,"pageshow for tab {%s}".subs(ev.browser.__tabID));if(!this.shouldProcessEvents_()){return}if(!ev.isTop){G_Debug(this,"Skipping pageshow for non-top content window.");return}var browser=ev.browser;if(!isDef(browser.__tabID)){G_Debug(this,"ERROR: Could not find tabID for pageshow in tab.");return}var syncItem=new CLB_SyncItem({componentID:this.componentID,typeID:"tab",itemID:browser.__tabID});syncItem.setProperty("url",browser.contentWindow.location.href)
  1124. ;syncItem.setProperty("title",browser.contentWindow.document.title);G_Debug(this,"Sending pageshow item to syncman: "+syncItem);CLB_syncMan.update(syncItem)}
  1125. ;CLB_TabSyncer.prototype.onTabSwitch=function(win,ev){G_Debug(this,"tabswitch from tab {%s} to tab {%s}".subs(ev.fromBrowser.__tabID,ev.toBrowser.__tabID));if(!this.shouldProcessEvents_()){return}var toTabIsNew=this.ensureTabCreated_(win,ev.toBrowser,true);if(!isDef(ev.fromBrowser.__tabID)){G_Debug(this,"Could not get tabID from fromBrowser. Ignoring.");return}if(!isDef(ev.toBrowser.__tabID)){G_Debug(this,"Could not get tabID from toBrowser. Ignoring.");return}if(!ev.fromBrowser.__isUnloading){var syncItem1=
  1126. new CLB_SyncItem({componentID:this.componentID,typeID:"tab",itemID:ev.fromBrowser.__tabID});syncItem1.setProperty("activeTab",false);G_Debug(this,"Sending tabswitch item for fromBrowser: "+syncItem1);CLB_syncMan.update(syncItem1)}if(!toTabIsNew){var syncItem2=new CLB_SyncItem({componentID:this.componentID,typeID:"tab",itemID:ev.toBrowser.__tabID});syncItem2.setProperty("activeTab",true);G_Debug(this,"Sending tabswitch item for toBrowser: "+syncItem2);CLB_syncMan.update(syncItem2)}}
  1127. ;CLB_TabSyncer.prototype.onTabMove=function(win,ev){G_Debug(this,"tabmove from index {%s} to index {%s}".subs(ev.fromIndex,ev.toIndex));if(!this.shouldProcessEvents_()){return}var tabBrowser=win.document.getElementById("content");var min=Math.min(ev.fromIndex,ev.toIndex);var max=Math.max(ev.fromIndex,ev.toIndex);this.resetTabIndicies_(tabBrowser,min,max)}
  1128. ;CLB_TabSyncer.prototype.resetTabIndicies_=function(tabBrowser,fromIndex,toIndex){var syncItem,browser;for(var i=fromIndex;i<=toIndex;i++){syncItem=new CLB_SyncItem({componentID:this.componentID,typeID:"tab"});browser=tabBrowser.browsers[i];if(!browser){G_DebugL(this,"ERROR: Could not find browser at position {%s}".subs(i));continue}if(!isDef(browser.__tabID)){G_DebugL(this,"ERROR: Could not get tabID from browser at position {%s}".subs(i));continue}syncItem.itemID=browser.__tabID;syncItem.setProperty(
  1129. "tabIndex",i);G_Debug(this,"Sending tabIndex update syncitem: "+syncItem);CLB_syncMan.update(syncItem)}}
  1130. ;CLB_TabSyncer.prototype.onUnload=function(win){G_Debug(this,"Received onunload event for win {%s}".subs(win.__winID));if(!this.shouldProcessEvents_()){return}if(this.unloadQueueAlarm_){G_Debug(this,"Found existing unload timer with {%s} queued items. Rescuing them.".subs(this.queuedUnload_.length));this.unloadQueueAlarm_.cancel()}else{this.queuedUnload_=[]}if(!isDef(win.__winID)){G_DebugL(this,"ERROR: Could not find winID for unloaded window. Ignoring.")}else{var winSyncItem=new CLB_SyncItem({componentID:
  1131. this.componentID,typeID:"window",itemID:win.__winID,isRemove:true});G_Debug(this,"Queuing win remove syncitem: "+winSyncItem);this.queuedUnload_.push(winSyncItem)}var tabBrowser=win.document.getElementById("content");if(!tabBrowser){G_DebugL(this,"ERROR: Could not get tabBrowser from unloading window. Skipping window's tabs.")}for(var i=0,browser;browser=tabBrowser.browsers[i];i++){if(!isDef(browser.__tabID)){G_DebugL(this,"ERROR: Could not find tabID for tab in unloading "+"window at position {%s}. Ignoring tab."
  1132. .subs(i));continue}var tabSyncItem=new CLB_SyncItem({componentID:this.componentID,typeID:"tab",itemID:browser.__tabID,isRemove:true});G_Debug(this,"Sending tab remove syncitem: "+tabSyncItem);this.queuedUnload_.push(tabSyncItem)}this.unloadQueueAlarm_=new G_Alarm(this.handleUnloadTimerElapsed_,CLB_TabSyncer.UNLOAD_QUEUE_SECONDS*1000)}
  1133. ;CLB_TabSyncer.prototype.handleUnloadTimerElapsed_=function(){G_Debug(this,"Unload timer elapsed. Sending {%s} queued unloads to the server.".subs(this.queuedUnload_.length));this.unloadQueueAlarm_=null;this.queuedUnload_.forEach(function(item){CLB_syncMan.update(item)}
  1134. );this.queuedUnload_=null}
  1135. ;CLB_TabSyncer.prototype.shouldProcessEvents_=function(){return this.started_&&CLB_app.getStatus()==CLB_Application.STATUS_ONLINE}
  1136. ;CLB_TabSyncer.findBrowserPosition=function(win,target){var tabBrowser=win.document.getElementById("content");var numCollapsedTabs=0;for(var i=0,cand;cand=tabBrowser.browsers[i];i++){if(tabBrowser.tabContainer.childNodes[i].collapsed){G_Debug(CLB_TabSyncer.prototype,"Skipping collapsed tab at pos {%s}".subs(i));numCollapsedTabs++;continue}if(cand==target){G_Debug(CLB_TabSyncer.prototype,"Found tab at pos {%s}. Adjusting for collapsed tabs to {%s}.".subs(i,i-numCollapsedTabs));return i-numCollapsedTabs}
  1137. }return-1}
  1138. ;CLB_TabSyncer.prototype.beforeUpdate=function(){}
  1139. ;CLB_TabSyncer.prototype.updateID_=function(downloadedID){downloadedID=parseInt(downloadedID);if(isNaN(downloadedID)){G_DebugL(this,"ERROR: Unexpected format for downloadedID: {%s}".subs(downloadedID));return}if(downloadedID>=this.nextID_){this.nextID_=downloadedID+1;G_Debug(this,"Received ID {%s} and updated to {%s}".subs(downloadedID,this.nextID_))}}
  1140. ;CLB_TabSyncer.prototype.getNextID_=function(){return String(this.nextID_++)}
  1141. ;CLB_TabSyncer.prototype.debugZone="CLB_TabSyncer";G_debugService.loggifier.loggify(CLB_TabSyncer.prototype);
  1142. function CLB_UpdateQueue(){this.reset()}
  1143. CLB_UpdateQueue.smooshItems=function(existingItem,newItem){var itemChanged=false;if(newItem.isRemove){if(!existingItem.isRemove){existingItem.isRemove=true;existingItem.clearProperties();itemChanged=true}}else{if(existingItem.isRemove){existingItem.isRemove=false;itemChanged=true}var propNames=newItem.getPropertyNames({});if(propNames.length){propNames.forEach(function(propName){var propVal=newItem.getProperty(propName);if(existingItem.getProperty(propName)!=propVal){existingItem.setProperty(propName,
  1144. propVal);itemChanged=true}}
  1145. ,this)}}return itemChanged}
  1146. ;CLB_UpdateQueue.prototype.replaceItem=function(newItem){this.addItem(newItem,true)}
  1147. ;CLB_UpdateQueue.prototype.addItem=function(newItem,opt_clobber){var lookupKey=newItem.makeLookupKey();var existingItem=this.pendingLookup[lookupKey];if(!existingItem){this.pendingLookup[lookupKey]=newItem}else{if(opt_clobber){existingItem.clearProperties()}CLB_UpdateQueue.smooshItems(existingItem,newItem)}}
  1148. ;CLB_UpdateQueue.prototype.getItemByLookupKey=function(lookupKey){if(isDef(this.pendingLookup[lookupKey])){return this.pendingLookup[lookupKey]}else{return null}}
  1149. ;CLB_UpdateQueue.prototype.deleteItemByLookupKey=function(lookupKey){if(lookupKey in this.pendingLookup){delete this.pendingLookup[lookupKey]}else{G_Debug(this,"Warning: trying to delete nonexistant update queue item  with lookupKey: "+lookupKey)}}
  1150. ;CLB_UpdateQueue.prototype.hasPending=function(){return this.pendingLookup.__count__>0}
  1151. ;CLB_UpdateQueue.prototype.getPending=function(){var pending=[];for(var lookupKey in this.pendingLookup){pending.push(this.pendingLookup[lookupKey])}return pending}
  1152. ;CLB_UpdateQueue.prototype.popNextItem=function(){var lookupKey;var nextItem;for(lookupKey in this.pendingLookup){nextItem=this.pendingLookup[lookupKey];break}delete this.pendingLookup[lookupKey];return nextItem}
  1153. ;CLB_UpdateQueue.prototype.pendingSize=function(){return this.pendingLookup.__count__}
  1154. ;CLB_UpdateQueue.prototype.append=function(queue){for(var lookupKey in queue.pendingLookup){this.addItem(queue.getItemByLookupKey(lookupKey))}}
  1155. ;CLB_UpdateQueue.prototype.reset=function(){this.pendingLookup={}}
  1156. ;CLB_UpdateQueue.debugZone="CLB_UpdateQueue";G_debugService.loggifier.loggify(CLB_UpdateQueue.prototype);
  1157. function CLB_Updater(){bindMethods(this)}
  1158. CLB_Updater.MAX_ITEM_SIZE=30720;CLB_Updater.MAX_UPLOAD_SIZE=4194304;CLB_Updater.UPDATE_TIMEOUT=60000;CLB_Updater.ERROR_UPDATE_TIMEOUT=51;CLB_Updater.ERROR_UPLOAD_TOO_LARGE=53;CLB_Updater.ERROR_APPLICATION_PRE_FILE_WRITE=-1;CLB_Updater.ERROR_APPLICATION_POST_FILE_WRITE=-2;CLB_Updater.getOfflineFile=function(){return G_File.getProfileFile("browserstate-offline.xml")}
  1159. ;CLB_Updater.hasOfflineData=function(){return CLB_app.prefs.getPref("hasOfflineData")&&this.getOfflineFile().exists()}
  1160. ;CLB_Updater.prototype.cancel=function(){if(this.funQueue_){this.funQueue_.cancel()}if(this.req_){this.req_.abort()}}
  1161. ;CLB_Updater.prototype.start=function(data,getOfflineData,onSuccess,onFailure,onProgress,opt_sendToServer,opt_writeOfflineFile){this.data_=data||[];this.currentDataItem_=null;this.onSuccess_=onSuccess;this.onFailure_=onFailure;this.onProgress_=onProgress;this.wroteOfflineFile_=false;this.writeOfflineFile_=Boolean(opt_writeOfflineFile);this.sendToServer_=Boolean(opt_sendToServer);this.doc_=CLB_XMLUtils.getDoc("UpdateRequest",{uid:CLB_app.getSID(),mid:CLB_app.getMID(),key:CLB_app.getEncryptedKey()}
  1162. );this.items_=this.doc_.createElement("items");this.clearedComponents_=this.doc_.createElement("clearedComponents");this.funQueue_=new G_WorkQueue;this.funQueue_.onError=this.handleWorkQueueError_;if(!getOfflineData){G_Debug(this,"Skipping prepend offline step since getOfflineData is false.");this.funQueue_.addJob(this.buildXML_);return}if(!CLB_Updater.hasOfflineData()){G_Debug(this,"Skipping prepend offline steps because there is no offline data.");this.funQueue_.addJob(this.buildXML_);return}this.funQueue_.addJob(
  1163. this.prependOfflineData_)}
  1164. ;CLB_Updater.prototype.prependOfflineData_=function(){G_Debug(this,"Prepending offline data");var offlineDoc=G_FirefoxXMLUtils.loadXML(CLB_Updater.getOfflineFile());var clearedComponentNodes=G_FirefoxXMLUtils.selectNodes(offlineDoc,"/g:UpdateRequest/g:clearedComponents/g:component",CLB_XMLUtils.gNamespaceResolver);var itemNodes=G_FirefoxXMLUtils.selectNodes(offlineDoc,"/g:UpdateRequest/g:items/g:item",CLB_XMLUtils.gNamespaceResolver);var updateQueue=new CLB_UpdateQueue;var syncItem,node;G_Debug(this,
  1165. "Parsing clearedComponents...");while(node=clearedComponentNodes.iterateNext()){syncItem=new CLB_SyncItem({componentID:node.textContent,isRemoveAll:true});updateQueue.addItem(syncItem)}G_Debug(this,"Parsing items...");var next=bind(function(){node=itemNodes.iterateNext();if(!node){G_Debug(this,"Done prepending offline items. Next: append pending items.");this.appendPendingItems_(updateQueue);return}syncItem=CLB_SyncItem.parseFromXML(node);if(syncItem){updateQueue.addItem(syncItem)}this.funQueue_.addJob(
  1166. next)}
  1167. ,this);next()}
  1168. ;CLB_Updater.prototype.appendPendingItems_=function(updateQueue){G_Debug(this,"Appending pending items to offline update queue.");var idx=0;var next=bind(function(){if(idx==this.data_.length){G_Debug(this,"Done appending pending items. Replacing data_.");this.data_=updateQueue.getPending();this.buildXML_();return}updateQueue.addItem(this.data_[idx++]);this.funQueue_.addJob(next)}
  1169. ,this);next()}
  1170. ;CLB_Updater.prototype.buildXML_=function(){G_Debug(this,"Building XML document...");var idx=0;var next=bind(function(){if(idx==this.data_.length){G_Debug(this,"Done building XML. Next up: send update.");this.maybeSendDoc_();return}var nextItem=this.data_[idx];G_Debug(this,"index: %s, totalItems: %s".subs(idx,this.data_.length));if(this.onProgress_){this.onProgress_(CLB_Application.PROGRESS_PREPARING,idx/this.data_.length)}var itemIsEncrypted=CLB_syncMan.isEncryptedComponent(nextItem.componentID)
  1171. ;var dataItem;if(itemIsEncrypted){G_Debug(this,"Cloning and encrypting item");dataItem=nextItem.clone();dataItem.encrypt()}else{dataItem=nextItem}idx++;if(dataItem.isRemoveAll){CLB_XMLUtils.addElm(this.clearedComponents_,"component",dataItem.componentID);this.funQueue_.addJob(next);return}var itemLength=0;G_Debug(this,"DataItem: %s".subs(dataItem));itemLength+=dataItem.componentID.length;itemLength+=dataItem.itemID.length;if(isDef(dataItem.typeID)){itemLength+=dataItem.typeID.length}var item=this.doc_.createElement(
  1172. "item");if(dataItem.isEncrypted){item.appendChild(this.doc_.createElement("isEncrypted"))}if(dataItem.isRemove){item.appendChild(this.doc_.createElement("isRemove"))}CLB_XMLUtils.addElm(item,"componentID",dataItem.componentID);CLB_XMLUtils.addElm(item,"itemID",dataItem.itemID);CLB_XMLUtils.addElm(item,"typeID",dataItem.typeID);var propertyNames=dataItem.getPropertyNames({});propertyNames.forEach(function(propName){var val=dataItem.getProperty(propName);if(isDef(val)&&!isNull(val)){itemLength+=val.toString(
  1173. ).length}var elm=CLB_XMLUtils.addElm(item,"prop",dataItem.getProperty(propName));if(elm){elm.setAttribute("name",propName)}}
  1174. ,this);if(itemLength>CLB_Updater.MAX_ITEM_SIZE){G_DebugL(this,"Not sending item {%s} because it's length {%s} exceeds the maximum item length {%s}.".subs(dataItem,itemLength,CLB_Updater.MAX_ITEM_SIZE))}else{this.items_.appendChild(item)}this.funQueue_.addJob(next)}
  1175. ,this);next()}
  1176. ;CLB_Updater.prototype.maybeSendDoc_=function(){if(this.clearedComponents_.childNodes.length>0){this.doc_.documentElement.appendChild(this.clearedComponents_)}if(this.items_.childNodes.length>0){this.doc_.documentElement.appendChild(this.items_)}var serializer=Cc["@mozilla.org/xmlextras/xmlserializer;1"].createInstance(Ci.nsIDOMSerializer);var contents=serializer.serializeToString(this.doc_);var fos=Cc["@mozilla.org/network/file-output-stream;1"].getService(Ci.nsIFileOutputStream);var cos=Cc["@mozilla.org/intl/converter-output-stream;1"
  1177. ].getService(Ci.nsIConverterOutputStream);var flags=G_File.PR_WRONLY|G_File.PR_CREATE_FILE|G_File.PR_TRUNCATE;this.uploadFile_=this.writeOfflineFile_?CLB_Updater.getOfflineFile():G_File.getTempFile("browserstate-upload.xml");try{fos.init(this.uploadFile_,flags,-1,0);cos.init(fos,"UTF-8",0,0);cos.writeString(contents)}finally{cos.close()}if(this.writeOfflineFile_){CLB_app.prefs.setPref("hasOfflineData",true)}this.wroteOfflineFile_=true;var fileSize=this.uploadFile_.fileSize;G_Debug(this,"upload filesize: "
  1178. +fileSize);if(fileSize>CLB_Updater.MAX_UPLOAD_SIZE){this.handleFailure_(CLB_Updater.ERROR_UPLOAD_TOO_LARGE,"Upload too large","Try disabling some components");return}if(this.sendToServer_){this.definitelySendDoc_()}else{this.onFailure_(0,null,null)}}
  1179. ;CLB_Updater.prototype.definitelySendDoc_=function(){if(this.data_.length==0){G_Debug(this,"Not writing temp file because this is just a ping");this.req_=CLB_RequestFactory.getRequest(CLB_RequestFactory.UPDATE,null,this.handleSuccess_,this.handleFailure_);this.req_.send(this.doc_);this.startTimer_();return}G_Debug(this,"Sending %s new items:...".subs(this.data_.length));if(CLB_app.prefs.getPref("log-xml",false)){var tmpFile=CLB_app.getUniqueTempFile("upload","xml");this.uploadFile_.copyTo(tmpFile.parent,
  1180. tmpFile.leafName);G_Debug(this,"Logging sent data in: %s...".subs(tmpFile.path))}var uploadInputStream=Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);uploadInputStream.init(this.uploadFile_,G_File.PR_RDONLY,292,0);G_Debug(this,"Upload stream initialized");var bufferedInputStream=Cc["@mozilla.org/network/buffered-input-stream;1"].createInstance(Ci.nsIBufferedInputStream);bufferedInputStream.init(uploadInputStream,4096);this.onProgress_(CLB_Application.PROGRESS_UPDATING,
  1181. 1);this.req_=CLB_RequestFactory.getRequest(CLB_RequestFactory.UPDATE,null,this.handleSuccess_,this.handleFailure_);this.req_.send(bufferedInputStream);this.startTimer_()}
  1182. ;CLB_Updater.prototype.startTimer_=function(){this.alarm_=new G_Alarm(this.timerElapsed_,CLB_Updater.UPDATE_TIMEOUT)}
  1183. ;CLB_Updater.prototype.timerElapsed_=function(){this.req_.abort();this.handleFailure_(CLB_Updater.ERROR_UPDATE_TIMEOUT,"Request timeout","Gave up waiting for server update to return, sorry.")}
  1184. ;CLB_Updater.prototype.handleSuccess_=function(req){this.req_=null;if(this.alarm_){this.alarm_.cancel()}CLB_app.setStatus(CLB_Application.STATUS_ONLINE);if(!req.responseXML){G_DebugL(this,"ERROR: The server response was not valid XML: "+req.responseText);this.onSuccess_()}else{this.onSuccess_(CLB_XMLUtils.getTimestamp(req.responseXML))}}
  1185. ;CLB_Updater.prototype.handleWorkQueueError_=function(job,e){if(this.wroteOfflineFile_){this.handleFailure_(CLB_Updater.ERROR_APPLICATION_POST_FILE_WRITE,"Unexpected error",e)}else{this.handleFailure_(CLB_Updater.ERROR_APPLICATION_PRE_FILE_WRITE,"Unexpected error",e)}}
  1186. ;CLB_Updater.prototype.handleFailure_=function(code,status,message){G_DebugL(this,"Updater failed with error: %s, %s, %s".subs(code,status,message));this.req_=null;if(this.alarm_){this.alarm_.cancel()}if(CLB_app.isKickError(code,status,message)){CLB_app.setStatus(CLB_Application.STATUS_KICKED)}else{CLB_app.setStatus(CLB_Application.STATUS_UPDATE_ERROR)}this.onFailure_(code,status,message)}
  1187. ;CLB_Updater.debugZone="CLB_Updater";CLB_Updater.prototype.debugZone="CLB_Updater";G_debugService.loggifier.loggify(CLB_Updater.prototype);
  1188. function CLB_UpdatingForm(win){this.win=win;this.appStatus=CLB_app.getStatus()}
  1189. CLB_UpdatingForm.prototype.debugZone="CLB_UpdatingForm";CLB_UpdatingForm.prototype.handleFormLoad=function(){this.doc=this.win.document;this.statusElm=this.doc.getElementById("clb-status");this.progressElm=this.doc.getElementById("clb-progress");if(CLB_syncMan.checkPending()){G_Debug(this,"We have some stuff to send to the server.");G_Debug(this,"Sending final update");CLB_syncMan.addObserver(this);CLB_syncMan.sendPending(true)}else if(CLB_syncMan.checkSending()){CLB_syncMan.addObserver(this);G_Debug(
  1190. this,"Updatingform is modally blocking so that another update can finish")}else{G_Debug(this,"Warning: updatingform didn't need to exist");this.win.setTimeout("window.close()",0)}}
  1191. ;CLB_UpdatingForm.prototype.updateProgress=function(percent,status){}
  1192. ;CLB_UpdatingForm.prototype.updateComplete=function(){CLB_syncMan.removeObserver(this);this.win.setTimeout("window.close()",0)}
  1193. ;CLB_UpdatingForm.prototype.updateFailure=function(code,status,opt_message){CLB_syncMan.removeObserver(this);var message=CLB_app.handleServerError(code,status,opt_message);if(message){this.win.alert("Error: "+message)}else if(this.appStatus==CLB_Application.STATUS_ONLINE&&!CLB_app.isKickError(code,status,opt_message)&&!CLB_app.isGAIATimeoutError(code,status,opt_message)){this.win.alert("Error '%s %s' occurred while syncing, please try again later.".subs(code,status))}this.win.setTimeout("window.close()"
  1194. ,0)}
  1195. ;G_debugService.loggifier.loggify(CLB_UpdatingForm.prototype);
  1196. function CLB_WelcomeForm(win){bindMethods(this);this.loaded=false;this.win=win;this.promptSvc=Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);this.result=this.win.arguments[0].QueryInterface(Components.interfaces.nsIWritablePropertyBag);this.result.setProperty("success",false);this.creatingAccount=false}
  1197. CLB_WelcomeForm.NO_USER_ERROR=403;CLB_WelcomeForm.REFRESH_SID_REQUIRED=403;CLB_WelcomeForm.MIN_TOKEN_LENGTH=4;CLB_WelcomeForm.REFRESH_SID_REQUIRED_MSG="Need to refresh SID cookie.";CLB_WelcomeForm.NO_ACCOUNT_MSG="Account does not exist for this user.";CLB_WelcomeForm.prototype.handleLoad=function(){this.doc=this.win.document;this.wizard=this.doc.documentElement;this.welcomePage=this.doc.getElementById("clb-welcome");this.progressPage=this.doc.getElementById("clb-progress");this.usernameField=this.doc.getElementById(
  1198. "clb-username");this.passwordField=this.doc.getElementById("clb-password");this.progressTitleField=this.doc.getElementById("clb-progress-title");this.progressBlurbField=this.doc.getElementById("clb-progress-blurb");this.progressMeter=this.doc.getElementById("clb-progress-meter");this.progressDetailsField=this.doc.getElementById("clb-progress-details");this.createTokenTextElm=this.doc.getElementById("clb-create-token");this.confirmTokenTextElm=this.doc.getElementById("clb-confirm-token");this.verifyTokenTextElm=
  1199. this.doc.getElementById("clb-verify-token");this.installTypeDefaultRadio=this.doc.getElementById("clb-installtype-default");this.usingAdvancedSettings=false;this.refreshingSID=false;this.loginUtil=new CLB_LoginUtil;this.componentSelector=new CLB_ComponentSelector(this.doc.getElementById("clb-component-selector"));this.componentSelector.settingsChanged=this.handleSettingsSelected.bind(this);this.wizard.getButton("cancel").addEventListener("click",this.handleCancel.bind(this),false);if(CLB_app.browserPrefs.getPref(
  1200. "offline")){this.win.setTimeout(this.handleWorkingOffline.bind(this),10)}else if(CLB_app.isBackedOff()){this.win.setTimeout(this.handleBackedOff.bind(this),10)}}
  1201. ;CLB_WelcomeForm.prototype.handleWorkingOffline=function(){this.promptSvc.alert(this.win,"You Are Working Offline",CLB_Application.MESSAGE_WORKING_OFFLINE);CLB_app.setStatus(CLB_Application.STATUS_OFFLINE);this.win.setTimeout("window.close()",0)}
  1202. ;CLB_WelcomeForm.prototype.handleBackedOff=function(){this.promptSvc.alert(this.win,"You Are Offline",CLB_Application.MESSAGE_BACKED_OFF);CLB_app.setStatus(CLB_Application.STATUS_BACKED_OFF);this.win.setTimeout("window.close()",0)}
  1203. ;CLB_WelcomeForm.prototype.handleForgotPassword=function(){if(!this.win.confirm("This will close the setup wizard and take you to a webpage to have your password sent to you. When you're ready, choose 'Setup Google Browser Sync' from the Google Browser Sync toolbar button to restart this wizard.")){return}CLB_app.setStatus(CLB_Application.STATUS_OFFLINE);CLB_app.errorURL="https://www.google.com/accounts/ForgotPasswd?service=browserstate";this.win.setTimeout("window.close()",0)}
  1204. ;CLB_WelcomeForm.prototype.handleCreateGAIAAcct=function(){if(!this.win.confirm("This will close the setup wizard and take you to a webpage to create a Google account. When you're ready, choose 'Setup Google Browser Sync' from the Google Browser Sync toolbar button to restart this wizard.")){return}CLB_app.setStatus(CLB_Application.STATUS_OFFLINE);CLB_app.errorURL="https://www.google.com/accounts/NewAccount";this.win.setTimeout("window.close()",0)}
  1205. ;CLB_WelcomeForm.prototype.showLearnMore=function(){var width=300;var height=300;var left=this.win.screenX+(this.win.outerWidth-width)/2;var top=this.win.screenY+(this.win.outerHeight-height)/2;this.win.open("chrome://browserstate/content/learnmore1.html","learnmore","width=%s,height=%s,left=%s,top=%s,scrollbars=yes,chrome,dialog".subs(width,height,left,top))}
  1206. ;CLB_WelcomeForm.prototype.handleCancel=function(){if(isDef(this.req)&&this.req){this.req.abort();this.req=null}if(this.syncing){CLB_syncMan.cancelSync()}if(this.observingSyncMan){CLB_syncMan.removeObserver(this);this.observingSyncMan=false}}
  1207. ;CLB_WelcomeForm.prototype.handleWizardFinish=function(){this.result.setProperty("success",true)}
  1208. ;CLB_WelcomeForm.prototype.handleWarningPageShow=function(){if(!this.loaded){this.handleLoad()}this.wizard.canAdvance=true}
  1209. ;CLB_WelcomeForm.prototype.handleWarningPageAdvanced=function(){if(CLB_app.detectConflicts()){return false}return true}
  1210. ;CLB_WelcomeForm.prototype.handleWelcomePageShow=function(){this.usernameField.focus();this.handleWelcomePageInput()}
  1211. ;CLB_WelcomeForm.prototype.handleWelcomePageInput=function(){this.username=this.usernameField.value.trim().replace(/@gmail\.com$/i,"");this.password=this.passwordField.value.trim();this.wizard.canAdvance=this.username!=""&&this.password!=""}
  1212. ;CLB_WelcomeForm.prototype.handleWelcomePageAdvanced=function(){this.setStatusTitle("Logging in");this.setStatusBlurb("Please wait while we log you into Google Browser Sync.");this.wizard.canAdvance=false;this.startPing()}
  1213. ;CLB_WelcomeForm.prototype.startPing=function(){this.setStatusDetails("Checking network configuration...");this.req=CLB_RequestFactory.getRequest(CLB_RequestFactory.PING,null,this.handlePingSuccess,this.handleLoginPhaseError.bind(null,"Error checking connection settings"),null,true);this.req.send(null)}
  1214. ;CLB_WelcomeForm.prototype.handlePingSuccess=function(req){this.req=null;if(req.channel.URI.spec==CLB_RequestFactory.getURL(CLB_RequestFactory.PING)){this.setStatusDetails("Authenticating user...");this.req=this.loginUtil.startRequest(this.username,this.password,this.handleLoginSuccess,this.handleLoginFailure)}else{this.promptSvc.alert(this.win,"Network requires login","It looks like you are accessing the internet through a connection which requires a web login. This can happen when you connect through a public network like at a hotel or an airport.\n\nPlease setup your internet connection, then reconnect to Google Browser Sync."
  1215. );CLB_app.setStatus(CLB_Application.STATUS_PING_REDIRECT);this.win.setTimeout("window.close()",0)}}
  1216. ;CLB_WelcomeForm.prototype.handleLoginFailure=function(code,status,message){if(code==403){this.loginUtil.showErrorMessage(this.win,this.req.responseText);this.wizard.canAdvance=true;this.hideProgressMeter();this.wizard.goTo("clb-welcome")}else{this.handleLoginPhaseError("Error authenticating user",code,status,message)}this.req=null}
  1217. ;CLB_WelcomeForm.prototype.handleLoginSuccess=function(req){this.req=null;CLB_app.errorURL=null;this.sid=this.loginUtil.parseResponse(req.responseText)["SID"];var doc=CLB_XMLUtils.getDoc("VerifyUserExistsRequest",{uid:this.sid});this.setStatusDetails("Checking user status...");this.req=CLB_RequestFactory.getRequest(CLB_RequestFactory.USER_EXISTS,null,this.handleCheckUserSuccess,this.handleCheckUserFailure);this.req.send(doc)}
  1218. ;CLB_WelcomeForm.prototype.handleCheckUserFailure=function(code,status,message){this.req=null;if(code==CLB_WelcomeForm.REFRESH_SID_REQUIRED&&message==CLB_WelcomeForm.REFRESH_SID_REQUIRED_MSG&&!this.refreshingSID){this.refreshingSID=true;this.setStatusDetails("Refreshing authorization...");this.req=this.loginUtil.startRequest(this.username,this.password,this.handleLoginSuccess,this.handleLoginFailure)}else if(code==CLB_WelcomeForm.NO_USER_ERROR&&message==CLB_WelcomeForm.NO_ACCOUNT_MSG){CLB_app.prefs.setPref(
  1219. "showWelcome",true);this.wizard.canAdvance=true;this.hideProgressMeter();this.wizard.goTo("clb-installtype")}else{this.handleLoginPhaseError("Error checking user status",code,status,message)}}
  1220. ;CLB_WelcomeForm.prototype.handleCheckUserSuccess=function(req){this.req=null;CLB_app.prefs.setPref("showWelcome",false);this.wizard.canAdvance=true;this.hideProgressMeter();this.wizard.advance("clb-token")}
  1221. ;CLB_WelcomeForm.prototype.showInstallTypePage=function(){this.wizard.canAdvance=true}
  1222. ;CLB_WelcomeForm.prototype.handleInstallTypePageAdvanced=function(){var registeredComponents=CLB_syncMan.getComponents();var syncedComponents=[];var encryptedComponents=[];var component;while(component=registeredComponents.getNext()){if(component.QueryInterface){component.QueryInterface(Ci.GISyncComponent)}if(component.componentID==CLB_SettingsSyncer.CONTRACT_ID){continue}syncedComponents.push(component.componentID);if(component.encryptionRequired){encryptedComponents.push(component.componentID)}
  1223. }CLB_app.setListPref("syncedComponents",syncedComponents);CLB_app.setListPref("encryptedComponents",encryptedComponents);if(this.installTypeDefaultRadio.selected){this.usingAdvancedSettings=false;this.wizard.currentPage.next="clb-createpin";return true}else{this.usingAdvancedSettings=true;this.wizard.currentPage.next="clb-settings";return true}}
  1224. ;CLB_WelcomeForm.prototype.showSettingsPage=function(){this.wizard.canAdvance=true;if(this.settingsPageInitialized){return}this.componentSelector.load();this.settingsPageInitialized=true}
  1225. ;CLB_WelcomeForm.prototype.handleSettingsSelected=function(isValid){this.wizard.canAdvance=isValid}
  1226. ;CLB_WelcomeForm.prototype.handleSettingPageAdvanced=function(){this.componentSelector.save()}
  1227. ;CLB_WelcomeForm.prototype.showCreatePinPage=function(){this.createTokenTextElm.focus();this.handleCreatePinPageInput()}
  1228. ;CLB_WelcomeForm.prototype.handleCreatePinPageInput=function(){this.token=this.createTokenTextElm.value.trim();this.wizard.canAdvance=this.confirmTokenTextElm.value.trim()!=""&&this.token!=""}
  1229. ;CLB_WelcomeForm.prototype.handleCreatePinPageAdvanced=function(){if(this.token.length<CLB_WelcomeForm.MIN_TOKEN_LENGTH){this.promptSvc.alert(this.win,"Invalid PIN","Your PIN must be at least four characters long.");return false}if(this.token!=this.confirmTokenTextElm.value.trim()){this.promptSvc.alert(this.win,"PINs do not match","Please enter the same PIN in both fields.");return false}this.startGenerateKey()}
  1230. ;CLB_WelcomeForm.prototype.startGenerateKey=function(){this.setStatusTitle("Creating account");this.setStatusBlurb("Please wait while we create your Google Browser Sync account.");this.setStatusDetails("Generating security key...");this.req=CLB_RequestFactory.getRequest(CLB_RequestFactory.GENERATE_KEY,{client:"browserstate"},this.handleGenerateKeySuccess,this.handleCreatePhaseError.bind(null,"Error generating security key"),null,true);this.req.send(null)}
  1231. ;CLB_WelcomeForm.prototype.handleGenerateKeySuccess=function(req){var result=(new G_Protocol4Parser).parse(req.responseText);if(!result||!result["clientkey"]){this.handleCreatePhaseError("Unexpected response while generating security key.");return}G_Debug(this,"Received server randomness. Generating client randomness.");var serverData=result["clientkey"];var clientData=[];for(var i=0;i<10;i++){clientData.push(Math.floor(Math.random()*255))}G_Debug(this,"Generated client randomness. Hashing.");var hasher=
  1232. new G_CryptoHasher;hasher.init(G_CryptoHasher.algorithms.SHA1);hasher.updateFromString(serverData);hasher.updateFromArray(clientData);this.key=hasher.digestBase64();G_Debug(this,"Hashing complete, key generated. Creating user.");this.setStatusDetails("Initializing account...");this.encryptedKey=CLB_Crypter.encryptString(this.key,this.token,true);var hashedToken=CLB_WelcomeForm.hashToken(this.token);var doc=CLB_XMLUtils.getDoc("CreateUserRequest",{uid:this.sid,key:this.encryptedKey,token:hashedToken}
  1233. );this.req=CLB_RequestFactory.getRequest(CLB_RequestFactory.CREATE_USER,null,this.handleCreateAccountSuccess,this.handleCreatePhaseError.bind(null,"Error initializing account"));this.req.send(doc)}
  1234. ;CLB_WelcomeForm.hashToken=function(token){var tokenHasher=new G_CryptoHasher;tokenHasher.init(G_CryptoHasher.algorithms.SHA1);tokenHasher.updateFromString(token);return tokenHasher.digestBase64()}
  1235. ;CLB_WelcomeForm.prototype.handleCreateAccountSuccess=function(req){CLB_app.prefs.setPref("SID",this.sid);CLB_app.prefs.setPref("username",this.username);CLB_app.prefs.setPref("key",this.key);CLB_app.prefs.setPref("encryptedKey",this.encryptedKey);CLB_app.setToken(this.token);var mid=req.responseXML.getElementsByTagName("mid")[0];CLB_app.prefs.setPref("MID",mid.textContent);CLB_app.savePrefs();this.setStatusDetails("Importing initial state...");CLB_syncMan.addObserver(this);this.observingSyncMan=
  1236. true;this.wizard.canRewind=false;this.creatingAccount=true;this.syncing=true;CLB_syncMan.startSync(this.creatingAccount)}
  1237. ;CLB_WelcomeForm.prototype.showRestartPage=function(){this.wizard.canRewind=false;this.wizard.getButton("cancel").disabled=true}
  1238. ;CLB_WelcomeForm.prototype.handleTokenPageShow=function(){this.verifyTokenTextElm.focus();this.handleTokenPageInput()}
  1239. ;CLB_WelcomeForm.prototype.handleTokenPageInput=function(){this.token=this.verifyTokenTextElm.value.trim();this.wizard.canAdvance=this.token!=""}
  1240. ;CLB_WelcomeForm.prototype.handleTokenPageAdvanced=function(){this.tokenPageAdvanced=true;return true}
  1241. ;CLB_WelcomeForm.prototype.hideProgressMeter=function(){this.progressMeter.setAttribute("collapsed",true)}
  1242. ;CLB_WelcomeForm.prototype.handleSyncingPageShow=function(){this.progressMeter.setAttribute("collapsed",false);this.wizard.canAdvance=false;this.wizard.canRewind=false;if(this.tokenPageAdvanced){var hashedToken=CLB_WelcomeForm.hashToken(this.token);var doc=CLB_XMLUtils.getDoc("AddClientRequest",{uid:this.sid,token:hashedToken});this.setStatusTitle("Synchronizing browser");this.setStatusBlurb("");this.progressBlurbField.appendChild(this.doc.createTextNode("Please wait while we synchronize this browser with the server. This can take several minutes, but "
  1243. ));var bolded=this.doc.createElementNS("http://www.w3.org/1999/xhtml","html:b");bolded.textContent="you only need to do it once.";this.progressBlurbField.appendChild(bolded);this.setStatusDetails("Authenticating token...");this.req=CLB_RequestFactory.getRequest(CLB_RequestFactory.ADD_CLIENT,null,this.handleAddClientSuccess,this.handleAddClientPhaseError.bind(null,"Error authenticating token"));this.req.send(doc);this.tokenPageAdvanced=false}}
  1244. ;CLB_WelcomeForm.prototype.handleAddClientSuccess=function(req){this.req=null;CLB_app.setToken(this.token);var mid=req.responseXML.getElementsByTagName("mid")[0];var key=req.responseXML.getElementsByTagName("key")[0];CLB_app.prefs.setPref("encryptedKey",key.textContent);var key=CLB_Crypter.decryptString(key.textContent,this.token);CLB_app.prefs.setPref("MID",mid.textContent);CLB_app.prefs.setPref("key",key);CLB_app.prefs.setPref("SID",this.sid);CLB_app.prefs.setPref("username",this.username);CLB_app.prefs.clearPref(
  1245. "lastUpdate");CLB_app.prefs.clearPref("encryptedComponents");CLB_app.prefs.clearPref("syncedComponents");CLB_app.savePrefs();CLB_syncMan.addObserver(this);this.observingSyncMan=true;this.setStatusDetails("Getting synchronization settings...");this.creatingAccount=false;this.syncing=true;CLB_syncMan.startSync()}
  1246. ;CLB_WelcomeForm.prototype.syncProgress=function(state,fraction){this.setStatusDetails(state)}
  1247. ;CLB_WelcomeForm.prototype.syncFailure=function(code,status,message){this.syncing_=null;CLB_syncMan.removeObserver(this);if(this.syncing){this.handleUpdatePhaseError("Error while sending update",code,status,message)}else if(this.creatingAccount){this.handleCreatePhaseError("Error while creating client",code,status,message)}else{this.handleAddClientPhaseError("Error while adding client",code,status,message)}}
  1248. ;CLB_WelcomeForm.prototype.syncComplete=function(){this.syncing=null;CLB_syncMan.removeObserver(this);this.wizard.canAdvance=true;this.hideProgressMeter();if(this.creatingAccount){this.wizard.advance("clb-restart")}else{this.wizard.advance("clb-success")}}
  1249. ;CLB_WelcomeForm.prototype.showSuccessPage=function(){this.wizard.canRewind=false;this.wizard.getButton("cancel").disabled=true}
  1250. ;CLB_WelcomeForm.prototype.handleLoginPhaseError=function(prefix,code,status,opt_message){this.showError(prefix,code,status,opt_message);this.wizard.canRewind=true;this.wizard.rewind();this.wizard.canAdvance=true}
  1251. ;CLB_WelcomeForm.prototype.handleUpdatePhaseError=function(prefix,code,status,opt_message){this.showError(prefix,code,status,opt_message);CLB_app.setStatus(CLB_Application.STATUS_OFFLINE);this.win.setTimeout("window.close()",0)}
  1252. ;CLB_WelcomeForm.prototype.handleCreatePhaseError=function(prefix,code,status,opt_message){this.showError(prefix,code,status,opt_message);this.wizard.canRewind=true;this.wizard.rewind();this.wizard.canAdvance=true}
  1253. ;CLB_WelcomeForm.prototype.handleAddClientPhaseError=function(prefix,code,status,opt_message){this.showError(prefix,code,status,opt_message);this.wizard.goTo("clb-token");this.wizard.canAdvance=true}
  1254. ;CLB_WelcomeForm.prototype.showError=function(prefix,opt_code,opt_status,opt_message){var message=CLB_app.handleServerError(opt_code,opt_status,opt_message);if(!message){G_DebugL(this,opt_message);if(opt_code==CLB_Application.HTTP_STATUS_FORBIDDEN&&opt_message==CLB_Application.ERROR_INVALID_PIN){message=CLB_Application.MESSAGE_INVALID_PIN}else if(opt_code==CLB_Updater.ERROR_UPLOAD_TOO_LARGE){message="Upload too large. Try disabling some components."}else{message="An unknown error occurred, please try again later"
  1255. ;G_DebugL(this,"ERROR:\n\tprefix:%s\n\tcode:%s\n\tstatus:%s\n\tmessage:%s".subs(prefix,opt_code,opt_status,opt_message))}}this.promptSvc.alert(this.win,null,message)}
  1256. ;CLB_WelcomeForm.prototype.setStatusTitle=function(title){this.progressPage.setAttribute("description",title)}
  1257. ;CLB_WelcomeForm.prototype.setStatusBlurb=function(blurb){while(this.progressBlurbField.childNodes.length){this.progressBlurbField.removeChild(this.progressBlurbField.childNodes[0])}this.progressBlurbField.textContent=blurb}
  1258. ;CLB_WelcomeForm.prototype.setStatusDetails=function(detail){this.progressDetailsField.textContent=detail}
  1259. ;CLB_WelcomeForm.prototype.debugZone="CLB_WelcomeForm";G_debugService.loggifier.loggify(CLB_WelcomeForm.prototype,"hashToken");
  1260. var CLB_XMLUtils={};CLB_XMLUtils.debugZone="CLB_XMLUtils";CLB_XMLUtils.selectText=function(context,xpath){var node=G_FirefoxXMLUtils.selectSingleNode(context,xpath,this.gNamespaceResolver);if(!node){return}else if(G_FirefoxXMLUtils.isNil(node)){return null}else{return node.textContent}}
  1261. ;CLB_XMLUtils.addElm=function(parent,elmName,opt_text,opt_elmNS){var doc=parent.ownerDocument;if(isDef(opt_text)){if(opt_elmNS){var elm=doc.createElementNS(opt_elmNS,elmName)}else{var elm=doc.createElement(elmName)}parent.appendChild(elm);if(opt_text==null){G_FirefoxXMLUtils.setNil(elm)}else{elm.appendChild(doc.createTextNode(opt_text))}}return elm}
  1262. ;CLB_XMLUtils.gNamespace="http://google.com/browserstate";CLB_XMLUtils.gNamespaceResolver=function(prefix){if(prefix=="g"){return CLB_XMLUtils.gNamespace}else{return null}}
  1263. ;CLB_XMLUtils.getComponentNamespace=function(compID){return"moz://"+compID}
  1264. ;CLB_XMLUtils.getDoc=function(topElmName,authBlock){var doc=G_FirefoxXMLUtils.newXML(topElmName,"http://google.com/browserstate",{xsi:G_FirefoxXMLUtils.XSI_NAMESPACE});if(!authBlock||isEmptyObject(authBlock)){return doc}var authElm=doc.createElement("auth");doc.documentElement.appendChild(authElm);for(var fieldName in authBlock){this.addElm(authElm,fieldName,authBlock[fieldName])}return doc}
  1265. ;CLB_XMLUtils.getTimestamp=function(doc){if(!doc){G_DebugL(this,"WARNING: document is null or undefined.");return null}var elm=doc.getElementsByTagName("timestamp")[0];if(!elm){G_DebugL(this,"WARNING: Could not find timestamp element in document:\n"+G_FirefoxXMLUtils.getXMLString(doc));return null}return elm.textContent}
  1266. ;
  1267. ;
  1268.  
  1269.