# # # patch "static/MochiKit/MochiKit.js" # from [db162319790852ff3e02f6e673b729a3c262f4ec] # to [b2e5faf9283ed95c29bc154751b681e1ae82ed10] # # patch "web.py" # from [4c396c690078ecd159e98a016dd3c9de67d63f42] # to [d5e776d5df9b8a3485fed19be37f647f538ebcdf] # ============================================================ --- static/MochiKit/MochiKit.js db162319790852ff3e02f6e673b729a3c262f4ec +++ static/MochiKit/MochiKit.js b2e5faf9283ed95c29bc154751b681e1ae82ed10 @@ -1,6 +1,6 @@ /*** - MochiKit.MochiKit 1.2 : PACKED VERSION + MochiKit.MochiKit 1.3.1 : PACKED VERSION THIS FILE IS AUTOMATICALLY GENERATED. If creating patches, please diff against the source tree, not this file. @@ -20,15 +20,15 @@ MochiKit.Base={}; if(typeof (MochiKit.Base)=="undefined"){ MochiKit.Base={}; } -MochiKit.Base.VERSION="1.2"; +MochiKit.Base.VERSION="1.3.1"; MochiKit.Base.NAME="MochiKit.Base"; MochiKit.Base.update=function(_1,_2){ -if(_1==null){ +if(_1===null){ _1={}; } for(var i=1;i=0;i--){ +_12.unshift(o[i]); } +}else{ +res.push(o); +} +} +return res; +},extend:function(_13,obj,_15){ +if(!_15){ +_15=0; +} if(obj){ var l=obj.length; if(typeof (l)!="number"){ @@ -67,68 +82,68 @@ throw new TypeError("Argument not an arr throw new TypeError("Argument not an array-like and MochiKit.Iter not present"); } } -if(!_9){ -_9=[]; +if(!_13){ +_13=[]; } -for(var i=_11;il){ -_37=l; +if(_41===null||_41>l){ +_41=l; } } -_36=[]; -for(i=0;i<_37;i++){ -var _38=[]; +_40=[]; +for(i=0;i<_41;i++){ +var _42=[]; for(var j=1;j0){ -_51=m.concat(me.im_preargs,_51); +_57=m.concat(me.im_preargs,_57); } -var _46=me.im_self; -if(!_46){ -_46=this; +var _52=me.im_self; +if(!_52){ +_52=this; } -return me.im_func.apply(_46,_51); +return me.im_func.apply(_52,_57); }; -_50.im_self=_49; -_50.im_func=_47; -_50.im_preargs=_48; -return _50; -},bindMethods:function(_52){ -var _53=MochiKit.Base.bind; -for(var k in _52){ -var _54=_52[k]; -if(typeof (_54)=="function"){ -_52[k]=_53(_54,_52); +_56.im_self=_55; +_56.im_func=_53; +_56.im_preargs=_54; +return _56; +},bindMethods:function(_58){ +var _59=MochiKit.Base.bind; +for(var k in _58){ +var _60=_58[k]; +if(typeof (_60)=="function"){ +_58[k]=_59(_60,_58); } } -},registerComparator:function(_55,_56,_57,_58){ -MochiKit.Base.comparatorRegistry.register(_55,_56,_57,_58); -},_primitives:{"bool":true,"string":true,"number":true},compare:function(a,b){ +},registerComparator:function(_61,_62,_63,_64){ +MochiKit.Base.comparatorRegistry.register(_61,_62,_63,_64); +},_primitives:{"boolean":true,"string":true,"number":true},compare:function(a,b){ if(a==b){ return 0; } -var _59=(typeof (a)=="undefined"||a==null); -var _60=(typeof (b)=="undefined"||b==null); -if(_59&&_60){ +var _65=(typeof (a)=="undefined"||a===null); +var _66=(typeof (b)=="undefined"||b===null); +if(_65&&_66){ return 0; }else{ -if(_59){ +if(_65){ return -1; }else{ -if(_60){ +if(_66){ return 1; } } } var m=MochiKit.Base; -var _61=m._primitives; -if(!(typeof (a) in _61&&typeof (b) in _61)){ +var _67=m._primitives; +if(!(typeof (a) in _67&&typeof (b) in _67)){ try{ return m.comparatorRegistry.match(a,b); } @@ -455,31 +481,31 @@ return 1; return 1; } } -var _62=m.repr; -throw new TypeError(_62(a)+" and "+_62(b)+" can not be compared"); +var _68=m.repr; +throw new TypeError(_68(a)+" and "+_68(b)+" can not be compared"); },compareDateLike:function(a,b){ return MochiKit.Base.compare(a.getTime(),b.getTime()); },compareArrayLike:function(a,b){ -var _63=MochiKit.Base.compare; -var _64=a.length; -var _65=0; -if(_64>b.length){ -_65=1; -_64=b.length; +var _69=MochiKit.Base.compare; +var _70=a.length; +var _71=0; +if(_70>b.length){ +_71=1; +_70=b.length; }else{ -if(_640))){ -var kv=MochiKit.DOM.formContents(_103); -_103=kv[0]; -_104=kv[1]; +},queryString:function(_113,_114){ +if(typeof (MochiKit.DOM)!="undefined"&&arguments.length==1&&(typeof (_113)=="string"||(typeof (_113.nodeType)!="undefined"&&_113.nodeType>0))){ +var kv=MochiKit.DOM.formContents(_113); +_113=kv[0]; +_114=kv[1]; }else{ if(arguments.length==1){ -var o=_103; -_103=[]; -_104=[]; +var o=_113; +_113=[]; +_114=[]; for(var k in o){ var v=o[k]; if(typeof (v)!="function"){ -_103.push(k); -_104.push(v); +_113.push(k); +_114.push(v); } } } } var rval=[]; -var len=Math.min(_103.length,_104.length); -var _108=MochiKit.Base.urlEncode; +var len=Math.min(_113.length,_114.length); +var _118=MochiKit.Base.urlEncode; for(var i=0;i=stop){ +if(_147>=stop){ throw self.StopIteration; } -_137+=step; +_147+=step; return rval; }}; },imap:function(fun,p,q){ var m=MochiKit.Base; var self=MochiKit.Iter; -var _141=m.map(self.iter,m.extend(null,arguments,1)); +var _151=m.map(self.iter,m.extend(null,arguments,1)); var map=m.map; var next=self.next; return {repr:function(){ return "imap(...)"; -},toString:m.forward("repr"),next:function(){ -return fun.apply(this,map(next,_141)); +},toString:m.forwardCall("repr"),next:function(){ +return fun.apply(this,map(next,_151)); }}; },applymap:function(fun,seq,self){ seq=MochiKit.Iter.iter(seq); var m=MochiKit.Base; return {repr:function(){ return "applymap(...)"; -},toString:m.forward("repr"),next:function(){ +},toString:m.forwardCall("repr"),next:function(){ return fun.apply(self,seq.next()); }}; },chain:function(p,q){ @@ -1034,24 +1089,24 @@ return self.iter(arguments[0]); if(arguments.length==1){ return self.iter(arguments[0]); } -var _143=m.map(self.iter,arguments); +var _153=m.map(self.iter,arguments); return {repr:function(){ return "chain(...)"; -},toString:m.forward("repr"),next:function(){ -while(_143.length>1){ +},toString:m.forwardCall("repr"),next:function(){ +while(_153.length>1){ try{ -return _143[0].next(); +return _153[0].next(); } catch(e){ if(e!=self.StopIteration){ throw e; } -_143.shift(); +_153.shift(); } } -if(_143.length==1){ -var arg=_143.shift(); -this.next=m.bind(arg.next,arg); +if(_153.length==1){ +var arg=_153.shift(); +this.next=m.bind("next",arg); return this.next(); } throw self.StopIteration; @@ -1061,7 +1116,7 @@ return "takewhile(...)"; seq=self.iter(seq); return {repr:function(){ return "takewhile(...)"; -},toString:MochiKit.Base.forward("repr"),next:function(){ +},toString:MochiKit.Base.forwardCall("repr"),next:function(){ var rval=seq.next(); if(!pred(rval)){ this.next=function(){ @@ -1077,68 +1132,68 @@ return "dropwhile(...)"; var bind=m.bind; return {"repr":function(){ return "dropwhile(...)"; -},"toString":m.forward("repr"),"next":function(){ +},"toString":m.forwardCall("repr"),"next":function(){ while(true){ var rval=seq.next(); if(!pred(rval)){ break; } } -this.next=bind(seq.next,seq); +this.next=bind("next",seq); return rval; }}; -},_tee:function(_145,sync,_147){ -sync.pos[_145]=-1; +},_tee:function(_155,sync,_157){ +sync.pos[_155]=-1; var m=MochiKit.Base; -var _148=m.listMin; +var _158=m.listMin; return {repr:function(){ -return "tee("+_145+", ...)"; -},toString:m.forward("repr"),next:function(){ +return "tee("+_155+", ...)"; +},toString:m.forwardCall("repr"),next:function(){ var rval; -var i=sync.pos[_145]; +var i=sync.pos[_155]; if(i==sync.max){ -rval=_147.next(); +rval=_157.next(); sync.deque.push(rval); sync.max+=1; -sync.pos[_145]+=1; +sync.pos[_155]+=1; }else{ rval=sync.deque[i-sync.min]; -sync.pos[_145]+=1; -if(i==sync.min&&_148(sync.pos)!=sync.min){ +sync.pos[_155]+=1; +if(i==sync.min&&_158(sync.pos)!=sync.min){ sync.min+=1; sync.deque.shift(); } } return rval; }}; -},tee:function(_149,n){ +},tee:function(_159,n){ var rval=[]; var sync={"pos":[],"deque":[],"max":-1,"min":-1}; if(arguments.length==1){ n=2; } var self=MochiKit.Iter; -_149=self.iter(_149); +_159=self.iter(_159); var _tee=self._tee; for(var i=0;i0&&_155>=stop)||(step<0&&_155<=stop)){ +if((step>0&&_165>=stop)||(step<0&&_165<=stop)){ throw MochiKit.Iter.StopIteration; } -var rval=_155; -_155+=step; +var rval=_165; +_165+=step; return rval; },repr:function(){ -return "range("+[_155,stop,step].join(", ")+")"; -},toString:MochiKit.Base.forward("repr")}; -},sum:function(_156,_157){ -var x=_157||0; +return "range("+[_165,stop,step].join(", ")+")"; +},toString:MochiKit.Base.forwardCall("repr")}; +},sum:function(_166,_167){ +var x=_167||0; var self=MochiKit.Iter; -_156=self.iter(_156); +_166=self.iter(_166); try{ while(true){ -x+=_156.next(); +x+=_166.next(); } } catch(e){ @@ -1224,12 +1279,12 @@ return x; } } return x; -},exhaust:function(_158){ +},exhaust:function(_168){ var self=MochiKit.Iter; -_158=self.iter(_158); +_168=self.iter(_168); try{ while(true){ -_158.next(); +_168.next(); } } catch(e){ @@ -1237,23 +1292,30 @@ throw e; throw e; } } -},forEach:function(_159,func,self){ +},forEach:function(_169,func,self){ var m=MochiKit.Base; if(arguments.length>2){ func=m.bind(func,self); } -if(m.isArrayLike(_159)){ -for(var i=0;i<_159.length;i++){ -func(_159[i]); +if(m.isArrayLike(_169)){ +try{ +for(var i=0;i<_169.length;i++){ +func(_169[i]); } +} +catch(e){ +if(e!=MochiKit.Iter.StopIteration){ +throw e; +} +} }else{ self=MochiKit.Iter; -self.exhaust(self.imap(func,_159)); +self.exhaust(self.imap(func,_169)); } -},every:function(_161,func){ +},every:function(_171,func){ var self=MochiKit.Iter; try{ -self.ifilterfalse(func,_161).next(); +self.ifilterfalse(func,_171).next(); return false; } catch(e){ @@ -1262,21 +1324,21 @@ return true; } return true; } -},sorted:function(_162,cmp){ -var rval=MochiKit.Iter.list(_162); +},sorted:function(_172,cmp){ +var rval=MochiKit.Iter.list(_172); if(arguments.length==1){ cmp=MochiKit.Base.compare; } rval.sort(cmp); return rval; -},reversed:function(_163){ -var rval=MochiKit.Iter.list(_163); +},reversed:function(_173){ +var rval=MochiKit.Iter.list(_173); rval.reverse(); return rval; -},some:function(_164,func){ +},some:function(_174,func){ var self=MochiKit.Iter; try{ -self.ifilter(func,_164).next(); +self.ifilter(func,_174).next(); return true; } catch(e){ @@ -1285,17 +1347,17 @@ return false; } return false; } -},iextend:function(lst,_165){ -if(MochiKit.Base.isArrayLike(_165)){ -for(var i=0;i<_165.length;i++){ -lst.push(_165[i]); +},iextend:function(lst,_175){ +if(MochiKit.Base.isArrayLike(_175)){ +for(var i=0;i<_175.length;i++){ +lst.push(_175[i]); } }else{ var self=MochiKit.Iter; -_165=self.iter(_165); +_175=self.iter(_175); try{ while(true){ -lst.push(_165.next()); +lst.push(_175.next()); } } catch(e){ @@ -1305,33 +1367,33 @@ return lst; } } return lst; -},groupby:function(_166,_167){ +},groupby:function(_176,_177){ var m=MochiKit.Base; var self=MochiKit.Iter; if(arguments.length<2){ -_167=m.operator.identity; +_177=m.operator.identity; } -_166=self.iter(_166); +_176=self.iter(_176); var pk=undefined; var k=undefined; var v; function fetch(){ -v=_166.next(); -k=_167(v); +v=_176.next(); +k=_177(v); } function eat(){ var ret=v; v=undefined; return ret; } -var _170=true; +var _180=true; return {repr:function(){ return "groupby(...)"; },next:function(){ while(k==pk){ fetch(); -if(_170){ -_170=false; +if(_180){ +_180=false; break; } } @@ -1346,20 +1408,20 @@ return eat(); return eat(); }}]; }}; -},groupby_as_array:function(_171,_172){ +},groupby_as_array:function(_181,_182){ var m=MochiKit.Base; var self=MochiKit.Iter; if(arguments.length<2){ -_172=m.operator.identity; +_182=m.operator.identity; } -_171=self.iter(_171); -var _173=[]; -var _174=true; -var _175; +_181=self.iter(_181); +var _183=[]; +var _184=true; +var _185; while(true){ try{ -var _176=_171.next(); -var key=_172(_176); +var _186=_181.next(); +var key=_182(_186); } catch(e){ if(e==self.StopIteration){ @@ -1367,32 +1429,32 @@ throw e; } throw e; } -if(_174||key!=_175){ -var _177=[]; -_173.push([key,_177]); +if(_184||key!=_185){ +var _187=[]; +_183.push([key,_187]); } -_177.push(_176); -_174=false; -_175=key; +_187.push(_186); +_184=false; +_185=key; } -return _173; -},arrayLikeIter:function(_178){ +return _183; +},arrayLikeIter:function(_188){ var i=0; return {repr:function(){ return "arrayLikeIter(...)"; -},toString:MochiKit.Base.forward("repr"),next:function(){ -if(i>=_178.length){ +},toString:MochiKit.Base.forwardCall("repr"),next:function(){ +if(i>=_188.length){ throw MochiKit.Iter.StopIteration; } -return _178[i++]; +return _188[i++]; }}; -},hasIterateNext:function(_179){ -return (_179&&typeof (_179.iterateNext)=="function"); -},iterateNextIter:function(_180){ +},hasIterateNext:function(_189){ +return (_189&&typeof (_189.iterateNext)=="function"); +},iterateNextIter:function(_190){ return {repr:function(){ return "iterateNextIter(...)"; -},toString:MochiKit.Base.forward("repr"),next:function(){ -var rval=_180.iterateNext(); +},toString:MochiKit.Base.forwardCall("repr"),next:function(){ +var rval=_190.iterateNext(); if(rval===null||rval===undefined){ throw MochiKit.Iter.StopIteration; } @@ -1411,7 +1473,9 @@ MochiKit.Iter.__new__(); m.nameFunctions(this); }; MochiKit.Iter.__new__(); +if(!MochiKit.__compat__){ reduce=MochiKit.Iter.reduce; +} MochiKit.Base._exportSymbols(this,MochiKit.Iter); if(typeof (dojo)!="undefined"){ dojo.provide("MochiKit.Logging"); @@ -1432,7 +1496,7 @@ MochiKit.Logging.NAME="MochiKit.Logging" MochiKit.Logging={}; } MochiKit.Logging.NAME="MochiKit.Logging"; -MochiKit.Logging.VERSION="1.2"; +MochiKit.Logging.VERSION="1.3.1"; MochiKit.Logging.__repr__=function(){ return "["+this.NAME+" "+this.VERSION+"]"; }; @@ -1441,32 +1505,32 @@ MochiKit.Logging.EXPORT_OK=["logLevelAtL }; MochiKit.Logging.EXPORT=["LogLevel","LogMessage","Logger","alertListener","logger","log","logError","logDebug","logFatal","logWarning"]; MochiKit.Logging.EXPORT_OK=["logLevelAtLeast","isLogMessage","compareLogMessage"]; -MochiKit.Logging.LogMessage=function(num,_182,info){ +MochiKit.Logging.LogMessage=function(num,_192,info){ this.num=num; -this.level=_182; +this.level=_192; this.info=info; this.timestamp=new Date(); }; MochiKit.Logging.LogMessage.prototype={repr:function(){ var m=MochiKit.Base; return "LogMessage("+m.map(m.repr,[this.num,this.level,this.info]).join(", ")+")"; -},toString:MochiKit.Base.forward("repr")}; -MochiKit.Base.update(MochiKit.Logging,{logLevelAtLeast:function(_184){ +},toString:MochiKit.Base.forwardCall("repr")}; +MochiKit.Base.update(MochiKit.Logging,{logLevelAtLeast:function(_194){ var self=MochiKit.Logging; -if(typeof (_184)=="string"){ -_184=self.LogLevel[_184]; +if(typeof (_194)=="string"){ +_194=self.LogLevel[_194]; } return function(msg){ -var _186=msg.level; -if(typeof (_186)=="string"){ -_186=self.LogLevel[_186]; +var _196=msg.level; +if(typeof (_196)=="string"){ +_196=self.LogLevel[_196]; } -return _186>=_184; +return _196>=_194; }; },isLogMessage:function(){ -var _187=MochiKit.Logging.LogMessage; +var _197=MochiKit.Logging.LogMessage; for(var i=0;i=0&&this._messages.length>this.maxSize){ -this._messges.shift(); +this._messages.shift(); } -},getMessages:function(_196){ -var _197=0; -if(!(typeof (_196)=="undefined"||_196==null)){ -_197=Math.max(0,this._messages.length-_196); +},getMessages:function(_206){ +var _207=0; +if(!(typeof (_206)=="undefined"||_206===null)){ +_207=Math.max(0,this._messages.length-_206); } -return this._messages.slice(_197); -},getMessageText:function(_198){ -if(typeof (_198)=="undefined"||_198==null){ -_198=30; +return this._messages.slice(_207); +},getMessageText:function(_208){ +if(typeof (_208)=="undefined"||_208===null){ +_208=30; } -var _199=this.getMessages(_198); -if(_199.length){ +var _209=this.getMessages(_208); +if(_209.length){ var lst=map(function(m){ return "\n ["+m.num+"] "+m.level+": "+m.info.join(" "); -},_199); -lst.unshift("LAST "+_199.length+" MESSAGES:"); +},_209); +lst.unshift("LAST "+_209.length+" MESSAGES:"); return lst.join(""); } return ""; -},debuggingBookmarklet:function(_200){ +},debuggingBookmarklet:function(_210){ if(typeof (MochiKit.LoggingPane)=="undefined"){ alert(this.getMessageText()); }else{ -MochiKit.LoggingPane.createLoggingPane(_200||false); +MochiKit.LoggingPane.createLoggingPane(_210||false); } }}; MochiKit.Logging.__new__=function(){ this.LogLevel={ERROR:40,FATAL:50,WARNING:30,INFO:20,DEBUG:10}; var m=MochiKit.Base; m.registerComparator("LogMessage",this.isLogMessage,this.compareLogMessage); -var _201=m.partial; -var _202=this.Logger; -var _203=_202.prototype.baseLog; -m.update(this.Logger.prototype,{debug:_201(_203,"DEBUG"),log:_201(_203,"INFO"),error:_201(_203,"ERROR"),fatal:_201(_203,"FATAL"),warning:_201(_203,"WARNING")}); +var _211=m.partial; +var _212=this.Logger; +var _213=_212.prototype.baseLog; +m.update(this.Logger.prototype,{debug:_211(_213,"DEBUG"),log:_211(_213,"INFO"),error:_211(_213,"ERROR"),fatal:_211(_213,"FATAL"),warning:_211(_213,"WARNING")}); var self=this; -var _204=function(name){ +var _214=function(name){ return function(){ self.logger[name].apply(self.logger,arguments); }; }; -this.log=_204("log"); -this.logError=_204("error"); -this.logDebug=_204("debug"); -this.logFatal=_204("fatal"); -this.logWarning=_204("warning"); -this.logger=new _202(); +this.log=_214("log"); +this.logError=_214("error"); +this.logDebug=_214("debug"); +this.logFatal=_214("fatal"); +this.logWarning=_214("warning"); +this.logger=new _212(); +this.logger.useNativeConsole=true; this.EXPORT_TAGS={":common":this.EXPORT,":all":m.concat(this.EXPORT,this.EXPORT_OK)}; m.nameFunctions(this); }; +if(typeof (printfire)=="undefined"&&typeof (document)!="undefined"&&document.createEvent&&typeof (dispatchEvent)!="undefined"){ +printfire=function(){ +printfire.args=arguments; +var ev=document.createEvent("Events"); +ev.initEvent("printfire",false,true); +dispatchEvent(ev); +}; +} MochiKit.Logging.__new__(); MochiKit.Base._exportSymbols(this,MochiKit.Logging); if(typeof (dojo)!="undefined"){ @@ -1573,7 +1662,7 @@ MochiKit.DateTime.NAME="MochiKit.DateTim MochiKit.DateTime={}; } MochiKit.DateTime.NAME="MochiKit.DateTime"; -MochiKit.DateTime.VERSION="1.2"; +MochiKit.DateTime.VERSION="1.3.1"; MochiKit.DateTime.__repr__=function(){ return "["+this.NAME+" "+this.VERSION+"]"; }; @@ -1582,11 +1671,11 @@ str=str+""; }; MochiKit.DateTime.isoDate=function(str){ str=str+""; -if(typeof (str)!="string"||str.length==0){ +if(typeof (str)!="string"||str.length===0){ return null; } var iso=str.split("-"); -if(iso.length==0){ +if(iso.length===0){ return null; } return new Date(iso[0],iso[1]-1,iso[2]); @@ -1594,38 +1683,38 @@ str=str+""; MochiKit.DateTime._isoRegexp=/(\d{4,})(?:-(\d{1,2})(?:-(\d{1,2})(?:[T ](\d{1,2}):(\d{1,2})(?::(\d{1,2})(?:\.(\d+))?)?(?:(Z)|([+-])(\d{1,2})(?::(\d{1,2}))?)?)?)?)?/; MochiKit.DateTime.isoTimestamp=function(str){ str=str+""; -if(typeof (str)!="string"||str.length==0){ +if(typeof (str)!="string"||str.length===0){ return null; } var res=str.match(MochiKit.DateTime._isoRegexp); -if(typeof (res)=="undefined"||res==null){ +if(typeof (res)=="undefined"||res===null){ return null; } var year,month,day,hour,min,sec,msec; year=parseInt(res[1],10); -if(typeof (res[2])=="undefined"||res[2]==""){ +if(typeof (res[2])=="undefined"||res[2]===""){ return new Date(year); } month=parseInt(res[2],10)-1; day=parseInt(res[3],10); -if(typeof (res[4])=="undefined"||res[4]==""){ +if(typeof (res[4])=="undefined"||res[4]===""){ return new Date(year,month,day); } hour=parseInt(res[4],10); min=parseInt(res[5],10); -sec=(typeof (res[6])!="undefined"&&res[6]!="")?parseInt(res[6],10):0; -if(typeof (res[7])!="undefined"&&res[7]!=""){ +sec=(typeof (res[6])!="undefined"&&res[6]!=="")?parseInt(res[6],10):0; +if(typeof (res[7])!="undefined"&&res[7]!==""){ msec=Math.round(1000*parseFloat("0."+res[7])); }else{ msec=0; } -if((typeof (res[8])=="undefined"||res[8]=="")&&(typeof (res[9])=="undefined"||res[9]=="")){ +if((typeof (res[8])=="undefined"||res[8]==="")&&(typeof (res[9])=="undefined"||res[9]==="")){ return new Date(year,month,day,hour,min,sec,msec); } var ofs; -if(typeof (res[9])!="undefined"&&res[9]!=""){ +if(typeof (res[9])!="undefined"&&res[9]!==""){ ofs=parseInt(res[10],10)*3600000; -if(typeof (res[11])!="undefined"&&res[11]!=""){ +if(typeof (res[11])!="undefined"&&res[11]!==""){ ofs+=parseInt(res[11],10)*60000; } if(res[9]=="-"){ @@ -1636,37 +1725,37 @@ return new Date(Date.UTC(year,month,day, } return new Date(Date.UTC(year,month,day,hour,min,sec,msec)-ofs); }; -MochiKit.DateTime.toISOTime=function(date,_210){ -if(typeof (date)=="undefined"||date==null){ +MochiKit.DateTime.toISOTime=function(date,_221){ +if(typeof (date)=="undefined"||date===null){ return null; } var hh=date.getHours(); var mm=date.getMinutes(); var ss=date.getSeconds(); -var lst=[((_210&&(hh<10))?"0"+hh:hh),((mm<10)?"0"+mm:mm),((ss<10)?"0"+ss:ss)]; +var lst=[((_221&&(hh<10))?"0"+hh:hh),((mm<10)?"0"+mm:mm),((ss<10)?"0"+ss:ss)]; return lst.join(":"); }; -MochiKit.DateTime.toISOTimestamp=function(date,_214){ -if(typeof (date)=="undefined"||date==null){ +MochiKit.DateTime.toISOTimestamp=function(date,_225){ +if(typeof (date)=="undefined"||date===null){ return null; } -var sep=_214?"T":" "; -var foot=_214?"Z":""; -if(_214){ +var sep=_225?"T":" "; +var foot=_225?"Z":""; +if(_225){ date=new Date(date.getTime()+(date.getTimezoneOffset()*60000)); } -return MochiKit.DateTime.toISODate(date)+sep+MochiKit.DateTime.toISOTime(date,_214)+foot; +return MochiKit.DateTime.toISODate(date)+sep+MochiKit.DateTime.toISOTime(date,_225)+foot; }; MochiKit.DateTime.toISODate=function(date){ -if(typeof (date)=="undefined"||date==null){ +if(typeof (date)=="undefined"||date===null){ return null; } -var _217=MochiKit.DateTime._padTwo; -return [date.getFullYear(),_217(date.getMonth()+1),_217(date.getDate())].join("-"); +var _228=MochiKit.DateTime._padTwo; +return [date.getFullYear(),_228(date.getMonth()+1),_228(date.getDate())].join("-"); }; MochiKit.DateTime.americanDate=function(d){ d=d+""; -if(typeof (d)!="string"||d.length==0){ +if(typeof (d)!="string"||d.length===0){ return null; } var a=d.split("/"); @@ -1676,14 +1765,14 @@ MochiKit.DateTime.toPaddedAmericanDate=f return (n>9)?n:"0"+n; }; MochiKit.DateTime.toPaddedAmericanDate=function(d){ -if(typeof (d)=="undefined"||d==null){ +if(typeof (d)=="undefined"||d===null){ return null; } -var _219=MochiKit.DateTime._padTwo; -return [_219(d.getMonth()+1),_219(d.getDate()),d.getFullYear()].join("/"); +var _230=MochiKit.DateTime._padTwo; +return [_230(d.getMonth()+1),_230(d.getDate()),d.getFullYear()].join("/"); }; MochiKit.DateTime.toAmericanDate=function(d){ -if(typeof (d)=="undefined"||d==null){ +if(typeof (d)=="undefined"||d===null){ return null; } return [d.getMonth()+1,d.getDate(),d.getFullYear()].join("/"); @@ -1705,14 +1794,18 @@ MochiKit.DateTime.__new__(); } }; MochiKit.DateTime.__new__(); -(function(_220,_221){ +if(typeof (MochiKit.Base)!="undefined"){ +MochiKit.Base._exportSymbols(this,MochiKit.DateTime); +}else{ +(function(_231,_232){ if((typeof (JSAN)=="undefined"&&typeof (dojo)=="undefined")||(typeof (MochiKit.__compat__)=="boolean"&&MochiKit.__compat__)){ -var all=_221.EXPORT_TAGS[":all"]; +var all=_232.EXPORT_TAGS[":all"]; for(var i=0;i_229){ -var i=_235.length-_229; -res=fmt.separator+_235.substring(i,_235.length)+res; -_235=_235.substring(0,i); +if(_240){ +while(_246.length>_240){ +var i=_246.length-_240; +res=fmt.separator+_246.substring(i,_246.length)+res; +_246=_246.substring(0,i); } } -res=_235+res; -if(_227>0){ -while(frac.length<_230){ +res=_246+res; +if(_238>0){ +while(frac.length<_241){ frac=frac+"0"; } res=res+fmt.decimal+frac; } -return _231+res+_232; +return _242+res+_243; }; }; -MochiKit.Format.numberFormatter=function(_237,_238,_239){ -if(typeof (_238)=="undefined"){ -_238=""; +MochiKit.Format.numberFormatter=function(_248,_249,_250){ +if(typeof (_249)=="undefined"){ +_249=""; } -var _240=_237.match(/((?:[0#]+,)?[0#]+)(?:\.([0#]+))?(%)?/); -if(!_240){ +var _251=_248.match(/((?:[0#]+,)?[0#]+)(?:\.([0#]+))?(%)?/); +if(!_251){ throw TypeError("Invalid pattern"); } -var _241=_237.substr(0,_240.index); -var _242=_237.substr(_240.index+_240[0].length); -if(_241.search(/-/)==-1){ -_241=_241+"-"; +var _252=_248.substr(0,_251.index); +var _253=_248.substr(_251.index+_251[0].length); +if(_252.search(/-/)==-1){ +_252=_252+"-"; } -var _243=_240[1]; -var frac=(typeof (_240[2])=="string"&&_240[2]!="")?_240[2]:""; -var _244=(typeof (_240[3])=="string"&&_240[3]!=""); -var tmp=_243.split(/,/); -var _246; -if(typeof (_239)=="undefined"){ -_239="default"; +var _254=_251[1]; +var frac=(typeof (_251[2])=="string"&&_251[2]!="")?_251[2]:""; +var _255=(typeof (_251[3])=="string"&&_251[3]!=""); +var tmp=_254.split(/,/); +var _257; +if(typeof (_250)=="undefined"){ +_250="default"; } if(tmp.length==1){ -_246=null; +_257=null; }else{ -_246=tmp[1].length; +_257=tmp[1].length; } -var _247=_243.length-_243.replace(/0/g,"").length; -var _248=frac.length-frac.replace(/0/g,"").length; -var _249=frac.length; -var rval=MochiKit.Format._numberFormatter(_238,_241,_242,_239,_244,_249,_247,_246,_248); +var _258=_254.length-_254.replace(/0/g,"").length; +var _259=frac.length-frac.replace(/0/g,"").length; +var _260=frac.length; +var rval=MochiKit.Format._numberFormatter(_249,_252,_253,_250,_255,_260,_258,_257,_259); var m=MochiKit.Base; if(m){ var fn=arguments.callee; @@ -1814,33 +1907,33 @@ return rval; } return rval; }; -MochiKit.Format.formatLocale=function(_251){ -if(typeof (_251)=="undefined"||_251==null){ -_251="default"; +MochiKit.Format.formatLocale=function(_262){ +if(typeof (_262)=="undefined"||_262===null){ +_262="default"; } -if(typeof (_251)=="string"){ -var rval=MochiKit.Format.LOCALE[_251]; +if(typeof (_262)=="string"){ +var rval=MochiKit.Format.LOCALE[_262]; if(typeof (rval)=="string"){ rval=arguments.callee(rval); -MochiKit.Format.LOCALE[_251]=rval; +MochiKit.Format.LOCALE[_262]=rval; } return rval; }else{ -return _251; +return _262; } }; -MochiKit.Format.twoDigitAverage=function(_252,_253){ -if(_253){ -var res=_252/_253; +MochiKit.Format.twoDigitAverage=function(_263,_264){ +if(_264){ +var res=_263/_264; if(!isNaN(res)){ -return MochiKit.Format.twoDigitFloat(_252/_253); +return MochiKit.Format.twoDigitFloat(_263/_264); } } return "0"; }; -MochiKit.Format.twoDigitFloat=function(_254){ -var sign=(_254<0?"-":""); -var s=Math.floor(Math.abs(_254)*100).toString(); +MochiKit.Format.twoDigitFloat=function(_265){ +var sign=(_265<0?"-":""); +var s=Math.floor(Math.abs(_265)*100).toString(); if(s=="0"){ return s; } @@ -1862,45 +1955,45 @@ return head+"."+tail; } } }; -MochiKit.Format.lstrip=function(str,_259){ +MochiKit.Format.lstrip=function(str,_270){ str=str+""; if(typeof (str)!="string"){ return null; } -if(!_259){ +if(!_270){ return str.replace(/^\s+/,""); }else{ -return str.replace(new RegExp("^["+_259+"]+"),""); +return str.replace(new RegExp("^["+_270+"]+"),""); } }; -MochiKit.Format.rstrip=function(str,_260){ +MochiKit.Format.rstrip=function(str,_271){ str=str+""; if(typeof (str)!="string"){ return null; } -if(!_260){ +if(!_271){ return str.replace(/\s+$/,""); }else{ -return str.replace(new RegExp("["+_260+"]+$"),""); +return str.replace(new RegExp("["+_271+"]+$"),""); } }; -MochiKit.Format.strip=function(str,_261){ +MochiKit.Format.strip=function(str,_272){ var self=MochiKit.Format; -return self.rstrip(self.lstrip(str,_261),_261); +return self.rstrip(self.lstrip(str,_272),_272); }; -MochiKit.Format.truncToFixed=function(_262,_263){ -_262=Math.floor(_262*Math.pow(10,_263)); -var res=(_262*Math.pow(10,-_263)).toFixed(_263); +MochiKit.Format.truncToFixed=function(_273,_274){ +_273=Math.floor(_273*Math.pow(10,_274)); +var res=(_273*Math.pow(10,-_274)).toFixed(_274); if(res.charAt(0)=="."){ res="0"+res; } return res; }; -MochiKit.Format.roundToFixed=function(_264,_265){ -return MochiKit.Format.truncToFixed(_264+0.5*Math.pow(10,-_265),_265); +MochiKit.Format.roundToFixed=function(_275,_276){ +return MochiKit.Format.truncToFixed(_275+0.5*Math.pow(10,-_276),_276); }; -MochiKit.Format.percentFormat=function(_266){ -return MochiKit.Format.twoDigitFloat(100*_266)+"%"; +MochiKit.Format.percentFormat=function(_277){ +return MochiKit.Format.twoDigitFloat(100*_277)+"%"; }; MochiKit.Format.EXPORT=["truncToFixed","roundToFixed","numberFormatter","formatLocale","twoDigitAverage","twoDigitFloat","percentFormat","lstrip","rstrip","strip"]; MochiKit.Format.LOCALE={en_US:{separator:",",decimal:".",percent:"%"},de_DE:{separator:".",decimal:",",percent:"%"},fr_FR:{separator:" ",decimal:",",percent:"%"},"default":"en_US"}; @@ -1930,14 +2023,18 @@ MochiKit.Format.__new__(); } }; MochiKit.Format.__new__(); -(function(_267,_268){ +if(typeof (MochiKit.Base)!="undefined"){ +MochiKit.Base._exportSymbols(this,MochiKit.Format); +}else{ +(function(_278,_279){ if((typeof (JSAN)=="undefined"&&typeof (dojo)=="undefined")||(typeof (MochiKit.__compat__)=="boolean"&&MochiKit.__compat__)){ -var all=_268.EXPORT_TAGS[":all"]; +var all=_279.EXPORT_TAGS[":all"]; for(var i=0;i=0)){ +if((this.paused===0)&&(this.fired>=0)){ this._fire(); } },_continue:function(res){ @@ -2025,11 +2123,18 @@ this._check(); } },callback:function(res){ this._check(); +if(res instanceof MochiKit.Async.Deferred){ +throw new Error("Deferred instances can only be chained if they are the result of a callback"); +} this._resback(res); },errback:function(res){ this._check(); +var self=MochiKit.Async; +if(res instanceof self.Deferred){ +throw new Error("Deferred instances can only be chained if they are the result of a callback"); +} if(!(res instanceof Error)){ -res=new MochiKit.Async.GenericError(res); +res=new self.GenericError(res); } this._resback(res); },addBoth:function(fn){ @@ -2048,26 +2153,29 @@ return this.addCallbacks(null,fn); } return this.addCallbacks(null,fn); },addCallbacks:function(cb,eb){ +if(this.chained){ +throw new Error("Chained Deferreds can not be re-used"); +} this.chain.push([cb,eb]); if(this.fired>=0){ this._fire(); } return this; },_fire:function(){ -var _273=this.chain; -var _274=this.fired; -var res=this.results[_274]; +var _284=this.chain; +var _285=this.fired; +var res=this.results[_285]; var self=this; var cb=null; -while(_273.length>0&&this.paused==0){ -var pair=_273.shift(); -var f=pair[_274]; -if(f==null){ +while(_284.length>0&&this.paused===0){ +var pair=_284.shift(); +var f=pair[_285]; +if(f===null){ continue; } try{ res=f(res); -_274=((res instanceof Error)?1:0); +_285=((res instanceof Error)?1:0); if(res instanceof MochiKit.Async.Deferred){ cb=function(res){ self._continue(res); @@ -2076,30 +2184,34 @@ catch(err){ } } catch(err){ -_274=1; +_285=1; +if(!(err instanceof Error)){ +err=new MochiKit.Async.GenericError(err); +} res=err; } } -this.fired=_274; -this.results[_274]=res; +this.fired=_285; +this.results[_285]=res; if(cb&&this.paused){ res.addBoth(cb); +res.chained=true; } }}; MochiKit.Base.update(MochiKit.Async,{evalJSONRequest:function(){ return eval("("+arguments[0].responseText+")"); -},succeed:function(_276){ +},succeed:function(_287){ var d=new MochiKit.Async.Deferred(); d.callback.apply(d,arguments); return d; -},fail:function(_277){ +},fail:function(_288){ var d=new MochiKit.Async.Deferred(); d.errback.apply(d,arguments); return d; },getXMLHttpRequest:function(){ var self=arguments.callee; if(!self.XMLHttpRequest){ -var _278=[function(){ +var _289=[function(){ return new XMLHttpRequest(); },function(){ return new ActiveXObject("Msxml2.XMLHTTP"); @@ -2110,8 +2222,8 @@ throw new MochiKit.Async.BrowserComplian },function(){ throw new MochiKit.Async.BrowserComplianceError("Browser does not support XMLHttpRequest"); }]; -for(var i=0;i<_278.length;i++){ -var func=_278[i]; +for(var i=0;i<_289.length;i++){ +var func=_289[i]; try{ self.XMLHttpRequest=func; return func(); @@ -2121,63 +2233,61 @@ return self.XMLHttpRequest(); } } return self.XMLHttpRequest(); -},sendXMLHttpRequest:function(req,_280){ -if(typeof (_280)=="undefined"){ -_280=null; -} -var _281=function(){ +},_nothing:function(){ +},_xhr_onreadystatechange:function(d){ +if(this.readyState==4){ try{ -req.onreadystatechange=null; +this.onreadystatechange=null; } catch(e){ try{ -req.onreadystatechange=function(){ -}; +this.onreadystatechange=MochiKit.Async._nothing; } catch(e){ } } -req.abort(); -}; -var self=MochiKit.Async; -var d=new self.Deferred(_281); -var _282=function(){ -if(req.readyState==4){ +var _290=null; try{ -req.onreadystatechange=null; +_290=this.status; +if(!_290&&MochiKit.Base.isNotEmpty(this.responseText)){ +_290=304; } +} catch(e){ -try{ -req.onreadystatechange=function(){ -}; } -catch(e){ +if(_290==200||_290==304){ +d.callback(this); +}else{ +var err=new MochiKit.Async.XMLHttpRequestError(this,"Request failed"); +if(err.number){ +d.errback(err); +}else{ +d.errback(err); } } -var _283=null; +} +},_xhr_canceller:function(req){ try{ -_283=req.status; -if(!_283&&MochiKit.Base.isNotEmpty(req.responseText)){ -_283=304; +req.onreadystatechange=null; } -} catch(e){ +try{ +req.onreadystatechange=MochiKit.Async._nothing; } -if(_283==200||_283==304){ -d.callback(req); -}else{ -var err=new self.XMLHttpRequestError(req,"Request failed"); -if(err.number){ -d.errback(err); -}else{ -d.errback(err); +catch(e){ } } +req.abort(); +},sendXMLHttpRequest:function(req,_293){ +if(typeof (_293)=="undefined"||_293===null){ +_293=""; } -}; +var m=MochiKit.Base; +var self=MochiKit.Async; +var d=new self.Deferred(m.partial(self._xhr_canceller,req)); try{ -req.onreadystatechange=_282; -req.send(_280); +req.onreadystatechange=m.bind(self._xhr_onreadystatechange,req,d); +req.send(_293); } catch(e){ try{ @@ -2205,28 +2315,28 @@ return d; var d=self.doSimpleXMLHttpRequest.apply(self,arguments); d=d.addCallback(self.evalJSONRequest); return d; -},wait:function(_287,_288){ +},wait:function(_296,_297){ var d=new MochiKit.Async.Deferred(); var m=MochiKit.Base; -if(typeof (_288)!="undefined"){ +if(typeof (_297)!="undefined"){ d.addCallback(function(){ -return _288; +return _297; }); } -var _289=setTimeout(m.bind(d.callback,d),Math.floor(_287*1000)); +var _298=setTimeout(m.bind("callback",d),Math.floor(_296*1000)); d.canceller=function(){ try{ -clearTimeout(_289); +clearTimeout(_298); } catch(e){ } }; return d; -},callLater:function(_290,func){ +},callLater:function(_299,func){ var m=MochiKit.Base; -var _291=m.partial.apply(m,m.extend(null,arguments,1)); -return MochiKit.Async.wait(_290).addCallback(function(res){ -return _291(); +var _300=m.partial.apply(m,m.extend(null,arguments,1)); +return MochiKit.Async.wait(_299).addCallback(function(res){ +return _300(); }); }}); MochiKit.Async.DeferredLock=function(){ @@ -2253,24 +2363,101 @@ this.waiting.shift().callback(this); this.waiting.shift().callback(this); } },_nextId:MochiKit.Base.counter(),repr:function(){ -var _292; +var _301; if(this.locked){ -_292="locked, "+this.waiting.length+" waiting"; +_301="locked, "+this.waiting.length+" waiting"; }else{ -_292="unlocked"; +_301="unlocked"; } -return "DeferredLock("+this.id+", "+_292+")"; -},toString:MochiKit.Base.forward("repr")}; -MochiKit.Async.EXPORT=["AlreadyCalledError","CancelledError","BrowserComplianceError","GenericError","XMLHttpRequestError","Deferred","succeed","fail","getXMLHttpRequest","doSimpleXMLHttpRequest","loadJSONDoc","wait","callLater","sendXMLHttpRequest","DeferredLock"]; +return "DeferredLock("+this.id+", "+_301+")"; +},toString:MochiKit.Base.forwardCall("repr")}; +MochiKit.Async.DeferredList=function(list,_303,_304,_305,_306){ +this.list=list; +this.resultList=new Array(this.list.length); +this.chain=[]; +this.id=this._nextId(); +this.fired=-1; +this.paused=0; +this.results=[null,null]; +this.canceller=_306; +this.silentlyCancelled=false; +if(this.list.length===0&&!_303){ +this.callback(this.resultList); +} +this.finishedCount=0; +this.fireOnOneCallback=_303; +this.fireOnOneErrback=_304; +this.consumeErrors=_305; +var _307=0; +MochiKit.Base.map(MochiKit.Base.bind(function(d){ +d.addCallback(MochiKit.Base.bind(this._cbDeferred,this),_307,true); +d.addErrback(MochiKit.Base.bind(this._cbDeferred,this),_307,false); +_307+=1; +},this),this.list); +}; +MochiKit.Base.update(MochiKit.Async.DeferredList.prototype,MochiKit.Async.Deferred.prototype); +MochiKit.Base.update(MochiKit.Async.DeferredList.prototype,{_cbDeferred:function(_308,_309,_310){ +this.resultList[_308]=[_309,_310]; +this.finishedCount+=1; +if(this.fired!==0){ +if(_309&&this.fireOnOneCallback){ +this.callback([_308,_310]); +}else{ +if(!_309&&this.fireOnOneErrback){ +this.errback(_310); +}else{ +if(this.finishedCount==this.list.length){ +this.callback(this.resultList); +} +} +} +} +if(!_309&&this.consumeErrors){ +_310=null; +} +return _310; +}}); +MochiKit.Async.gatherResults=function(_311){ +var d=new MochiKit.Async.DeferredList(_311,false,true,false); +d.addCallback(function(_312){ +var ret=[]; +for(var i=0;i<_312.length;i++){ +ret.push(_312[i][1]); +} +return ret; +}); +return d; +}; +MochiKit.Async.maybeDeferred=function(func){ +var self=MochiKit.Async; +var _313; +try{ +var r=func.apply(null,MochiKit.Base.extend([],arguments,1)); +if(r instanceof self.Deferred){ +_313=r; +}else{ +if(r instanceof Error){ +_313=self.fail(r); +}else{ +_313=self.succeed(r); +} +} +} +catch(e){ +_313=self.fail(e); +} +return _313; +}; +MochiKit.Async.EXPORT=["AlreadyCalledError","CancelledError","BrowserComplianceError","GenericError","XMLHttpRequestError","Deferred","succeed","fail","getXMLHttpRequest","doSimpleXMLHttpRequest","loadJSONDoc","wait","callLater","sendXMLHttpRequest","DeferredLock","DeferredList","gatherResults","maybeDeferred"]; MochiKit.Async.EXPORT_OK=["evalJSONRequest"]; MochiKit.Async.__new__=function(){ var m=MochiKit.Base; var ne=m.partial(m._newNamedError,this); -ne("AlreadyCalledError",function(_294){ -this.deferred=_294; +ne("AlreadyCalledError",function(_316){ +this.deferred=_316; }); -ne("CancelledError",function(_295){ -this.deferred=_295; +ne("CancelledError",function(_317){ +this.deferred=_317; }); ne("BrowserComplianceError",function(msg){ this.message=msg; @@ -2311,15 +2498,23 @@ MochiKit.DOM.NAME="MochiKit.DOM"; MochiKit.DOM={}; } MochiKit.DOM.NAME="MochiKit.DOM"; -MochiKit.DOM.VERSION="1.2"; +MochiKit.DOM.VERSION="1.3.1"; MochiKit.DOM.__repr__=function(){ return "["+this.NAME+" "+this.VERSION+"]"; }; MochiKit.DOM.toString=function(){ return this.__repr__(); }; -MochiKit.DOM.EXPORT=["formContents","currentWindow","currentDocument","withWindow","withDocument","registerDOMConverter","coerceToDOM","createDOM","createDOMFunc","getNodeAttribute","setNodeAttribute","updateNodeAttributes","appendChildNodes","replaceChildNodes","removeElement","swapDOM","BUTTON","TT","PRE","H1","H2","H3","BR","CANVAS","HR","LABEL","TEXTAREA","FORM","STRONG","SELECT","OPTION","OPTGROUP","LEGEND","FIELDSET","P","UL","OL","LI","TD","TR","THEAD","TBODY","TFOOT","TABLE","TH","INPUT","SPAN","A","DIV","IMG","getElement","$","computedStyle","getElementsByTagAndClassName","addToCallStack","addLoadEvent","focusOnLoad","setElementClass","toggleElementClass","addElementClass","removeElementClass","swapElementClass","hasElementClass","escapeHTML","toHTML","emitHTML","setDisplayForElement","hideElement","showElement","scrapeText","elementPosition"]; +MochiKit.DOM.EXPORT=["formContents","currentWindow","currentDocument","withWindow","withDocument","registerDOMConverter","coerceToDOM","createDOM","createDOMFunc","getNodeAttribute","setNodeAttribute","updateNodeAttributes","appendChildNodes","replaceChildNodes","removeElement","swapDOM","BUTTON","TT","PRE","H1","H2","H3","BR","CANVAS","HR","LABEL","TEXTAREA","FORM","STRONG","SELECT","OPTION","OPTGROUP","LEGEND","FIELDSET","P","UL","OL","LI","TD","TR","THEAD","TBODY","TFOOT","TABLE","TH","INPUT","SPAN","A","DIV","IMG","getElement","$","computedStyle","getElementsByTagAndClassName","addToCallStack","addLoadEvent","focusOnLoad","setElementClass","toggleElementClass","addElementClass","removeElementClass","swapElementClass","hasElementClass","escapeHTML","toHTML","emitHTML","setDisplayForElement","hideElement","showElement","scrapeText","elementDimensions","elementPosition","setElementDimensions","setElementPosition","getViewportDimensions","setOpacity"]; MochiKit.DOM.EXPORT_OK=["domConverters"]; +MochiKit.DOM.Dimensions=function(w,h){ +this.w=w; +this.h=h; +}; +MochiKit.DOM.Dimensions.prototype.repr=function(){ +var repr=MochiKit.Base.repr; +return "{w: "+repr(this.w)+", h: "+repr(this.h)+"}"; +}; MochiKit.DOM.Coordinates=function(x,y){ this.x=x; this.y=y; @@ -2328,43 +2523,147 @@ return "{x: "+repr(this.x)+", y: "+repr( var repr=MochiKit.Base.repr; return "{x: "+repr(this.x)+", y: "+repr(this.y)+"}"; }; -MochiKit.DOM.elementPosition=function(elem,_298){ +MochiKit.DOM.Coordinates.prototype.toString=function(){ +return this.repr(); +}; +MochiKit.Base.update(MochiKit.DOM,{setOpacity:function(elem,o){ +elem=MochiKit.DOM.getElement(elem); +MochiKit.DOM.updateNodeAttributes(elem,{"style":{"opacity":o,"-moz-opacity":o,"-khtml-opacity":o,"filter":" alpha(opacity="+(o*100)+")"}}); +},getViewportDimensions:function(){ +var d=new MochiKit.DOM.Dimensions(); +var w=MochiKit.DOM._window; +var b=MochiKit.DOM._document.body; +if(w.innerWidth){ +d.w=w.innerWidth; +d.h=w.innerHeight; +}else{ +if(b.parentElement.clientWidth){ +d.w=b.parentElement.clientWidth; +d.h=b.parentElement.clientHeight; +}else{ +if(b&&b.clientWidth){ +d.w=b.clientWidth; +d.h=b.clientHeight; +} +} +} +return d; +},elementDimensions:function(elem){ var self=MochiKit.DOM; +if(typeof (elem.w)=="number"||typeof (elem.h)=="number"){ +return new self.Dimensions(elem.w||0,elem.h||0); +} elem=self.getElement(elem); if(!elem){ return undefined; } -var x=0; -var y=0; +if(self.computedStyle(elem,"display")!="none"){ +return new self.Dimensions(elem.offsetWidth||0,elem.offsetHeight||0); +} +var s=elem.style; +var _322=s.visibility; +var _323=s.position; +s.visibility="hidden"; +s.position="absolute"; +s.display=""; +var _324=elem.offsetWidth; +var _325=elem.offsetHeight; +s.display="none"; +s.position=_323; +s.visibility=_322; +return new self.Dimensions(_324,_325); +},elementPosition:function(elem,_326){ +var self=MochiKit.DOM; +elem=self.getElement(elem); +if(!elem){ +return undefined; +} +var c=new self.Coordinates(0,0); +if(elem.x&&elem.y){ +c.x+=elem.x||0; +c.y+=elem.y||0; +return c; +}else{ +if(elem.parentNode===null||self.computedStyle(elem,"display")=="none"){ +return undefined; +} +} +var box=null; +var _329=null; +var d=MochiKit.DOM._document; +var de=d.documentElement; +var b=d.body; +if(elem.getBoundingClientRect){ +box=elem.getBoundingClientRect(); +c.x+=box.left+(de.scrollLeft||b.scrollLeft)-(de.clientLeft||b.clientLeft); +c.y+=box.top+(de.scrollTop||b.scrollTop)-(de.clientTop||b.clientTop); +}else{ +if(d.getBoxObjectFor){ +box=d.getBoxObjectFor(elem); +c.x+=box.x; +c.y+=box.y; +}else{ if(elem.offsetParent){ -while(elem.offsetParent){ -x+=elem.offsetLeft; -y+=elem.offsetTop; -elem=elem.offsetParent; +c.x+=elem.offsetLeft; +c.y+=elem.offsetTop; +_329=elem.offsetParent; +if(_329!=elem){ +while(_329){ +c.x+=_329.offsetLeft; +c.y+=_329.offsetTop; +_329=_329.offsetParent; } +} +var ua=navigator.userAgent.toLowerCase(); +if((typeof (opera)!="undefined"&&parseFloat(opera.version())<9)||(ua.indexOf("safari")!=-1&&self.computedStyle(elem,"position")=="absolute")){ +c.x-=b.offsetLeft; +c.y-=b.offsetTop; +} +} +} +} +if(typeof (_326)!="undefined"){ +_326=arguments.callee(_326); +if(_326){ +c.x-=(_326.x||0); +c.y-=(_326.y||0); +} +} +if(elem.parentNode){ +_329=elem.parentNode; }else{ -x=elem.x||x; -y=elem.y||y; +_329=null; } -if(_298){ -_298=arguments.callee(_298); -if(_298){ -x-=(_298.x||0); -y-=(_298.y||0); +while(_329&&_329.tagName!="BODY"&&_329.tagName!="HTML"){ +c.x-=_329.scrollLeft; +c.y-=_329.scrollTop; +if(_329.parentNode){ +_329=_329.parentNode; +}else{ +_329=null; } } -return new self.Coordinates(x,y); -}; -MochiKit.DOM.currentWindow=function(){ +return c; +},setElementDimensions:function(elem,_332,_333){ +elem=MochiKit.DOM.getElement(elem); +if(typeof (_333)=="undefined"){ +_333="px"; +} +MochiKit.DOM.updateNodeAttributes(elem,{"style":{"width":_332.w+_333,"height":_332.h+_333}}); +},setElementPosition:function(elem,_334,_335){ +elem=MochiKit.DOM.getElement(elem); +if(typeof (_335)=="undefined"){ +_335="px"; +} +MochiKit.DOM.updateNodeAttributes(elem,{"style":{"left":_334.x+_335,"top":_334.y+_335}}); +},currentWindow:function(){ return MochiKit.DOM._window; -}; -MochiKit.DOM.currentDocument=function(){ +},currentDocument:function(){ return MochiKit.DOM._document; -}; -MochiKit.DOM.withWindow=function(win,func){ +},withWindow:function(win,func){ var self=MochiKit.DOM; -var _300=self._document; -var _301=self._win; +var _337=self._document; +var _338=self._win; var rval; try{ self._window=win; @@ -2372,74 +2671,84 @@ catch(e){ rval=func(); } catch(e){ -self._window=_301; -self._document=_300; +self._window=_338; +self._document=_337; throw e; } -self._window=_301; -self._document=_300; +self._window=_338; +self._document=_337; return rval; -}; -MochiKit.DOM.formContents=function(elem){ -var _302=[]; -var _303=[]; +},formContents:function(elem){ +var _339=[]; +var _340=[]; var m=MochiKit.Base; var self=MochiKit.DOM; -if(typeof (elem)=="undefined"||elem==null){ +if(typeof (elem)=="undefined"||elem===null){ elem=self._document; }else{ elem=self.getElement(elem); } m.nodeWalk(elem,function(elem){ var name=elem.name; -var _304=elem.value; -if(m.isNotEmpty(name,_304)){ -if(elem.tagName=="INPUT"&&(elem.type=="radio"||elem.type=="checkbox")&&!elem.checked){ +if(m.isNotEmpty(name)){ +var _341=elem.nodeName; +if(_341=="INPUT"&&(elem.type=="radio"||elem.type=="checkbox")&&!elem.checked){ return null; } -_302.push(name); -_303.push(_304); +if(_341=="SELECT"){ +if(elem.selectedIndex>=0){ +var opt=elem.options[elem.selectedIndex]; +_339.push(name); +_340.push((opt.value)?opt.value:opt.text); return null; } +_339.push(name); +_340.push(""); +return null; +} +if(_341=="FORM"||_341=="P"||_341=="SPAN"||_341=="DIV"){ return elem.childNodes; +} +_339.push(name); +_340.push(elem.value||""); +return null; +} +return elem.childNodes; }); -return [_302,_303]; -}; -MochiKit.DOM.withDocument=function(doc,func){ +return [_339,_340]; +},withDocument:function(doc,func){ var self=MochiKit.DOM; -var _306=self._document; +var _344=self._document; var rval; try{ self._document=doc; rval=func(); } catch(e){ -self._document=_306; +self._document=_344; throw e; } -self._document=_306; +self._document=_344; return rval; -}; -MochiKit.DOM.registerDOMConverter=function(name,_307,wrap,_308){ -MochiKit.DOM.domConverters.register(name,_307,wrap,_308); -}; -MochiKit.DOM.coerceToDOM=function(node,ctx){ +},registerDOMConverter:function(name,_345,wrap,_346){ +MochiKit.DOM.domConverters.register(name,_345,wrap,_346); +},coerceToDOM:function(node,ctx){ var im=MochiKit.Iter; var self=MochiKit.DOM; var iter=im.iter; -var _313=im.repeat; +var _350=im.repeat; var imap=im.imap; -var _315=self.domConverters; -var _316=self.coerceToDOM; -var _317=MochiKit.Base.NotFound; +var _352=self.domConverters; +var _353=self.coerceToDOM; +var _354=MochiKit.Base.NotFound; while(true){ -if(typeof (node)=="undefined"||node==null){ +if(typeof (node)=="undefined"||node===null){ return null; } if(typeof (node.nodeType)!="undefined"&&node.nodeType>0){ return node; } -if(typeof (node)=="number"||typeof (node)=="bool"){ +if(typeof (node)=="number"||typeof (node)=="boolean"){ node=node.toString(); } if(typeof (node)=="string"){ @@ -2453,65 +2762,62 @@ continue; node=node(ctx); continue; } -var _318=null; +var _355=null; try{ -_318=iter(node); +_355=iter(node); } catch(e){ } -if(_318){ -return imap(_316,_318,_313(ctx)); +if(_355){ +return imap(_353,_355,_350(ctx)); } try{ -node=_315.match(node,ctx); +node=_352.match(node,ctx); continue; } catch(e){ -if(e!=_317){ +if(e!=_354){ throw e; } } return self._document.createTextNode(node.toString()); } return undefined; -}; -MochiKit.DOM.setNodeAttribute=function(node,attr,_320){ +},setNodeAttribute:function(node,attr,_357){ var o={}; -o[attr]=_320; +o[attr]=_357; try{ return MochiKit.DOM.updateNodeAttributes(node,o); } catch(e){ } return null; -}; -MochiKit.DOM.getNodeAttribute=function(node,attr){ +},getNodeAttribute:function(node,attr){ var self=MochiKit.DOM; -var _321=self.attributeArray.renames[attr]; +var _358=self.attributeArray.renames[attr]; node=self.getElement(node); try{ -if(_321){ -return node[_321]; +if(_358){ +return node[_358]; } return node.getAttribute(attr); } catch(e){ } return null; -}; -MochiKit.DOM.updateNodeAttributes=function(node,_322){ +},updateNodeAttributes:function(node,_359){ var elem=node; var self=MochiKit.DOM; if(typeof (node)=="string"){ elem=self.getElement(node); } -if(_322){ -var _323=MochiKit.Base.updatetree; +if(_359){ +var _360=MochiKit.Base.updatetree; if(self.attributeArray.compliant){ -for(var k in _322){ -var v=_322[k]; +for(var k in _359){ +var v=_359[k]; if(typeof (v)=="object"&&typeof (elem[k])=="object"){ -_323(elem[k],v); +_360(elem[k],v); }else{ if(k.substring(0,2)=="on"){ if(typeof (v)=="string"){ @@ -2524,18 +2830,18 @@ elem.setAttribute(k,v); } } }else{ -var _324=self.attributeArray.renames; -for(k in _322){ -v=_322[k]; -var _325=_324[k]; +var _361=self.attributeArray.renames; +for(k in _359){ +v=_359[k]; +var _362=_361[k]; if(k=="style"&&typeof (v)=="string"){ elem.style.cssText=v; }else{ -if(typeof (_325)=="string"){ -elem[_325]=v; +if(typeof (_362)=="string"){ +elem[_362]=v; }else{ if(typeof (elem[k])=="object"&&typeof (v)=="object"){ -_323(elem[k],v); +_360(elem[k],v); }else{ if(k.substring(0,2)=="on"){ if(typeof (v)=="string"){ @@ -2552,146 +2858,142 @@ return elem; } } return elem; -}; -MochiKit.DOM.appendChildNodes=function(node){ +},appendChildNodes:function(node){ var elem=node; var self=MochiKit.DOM; if(typeof (node)=="string"){ elem=self.getElement(node); } -var _326=[self.coerceToDOM(MochiKit.Base.extend(null,arguments,1),elem)]; -var _327=MochiKit.Iter.iextend; -while(_326.length){ -var n=_326.shift(); -if(typeof (n)=="undefined"||n==null){ +var _363=[self.coerceToDOM(MochiKit.Base.extend(null,arguments,1),elem)]; +var _364=MochiKit.Base.concat; +while(_363.length){ +var n=_363.shift(); +if(typeof (n)=="undefined"||n===null){ }else{ if(typeof (n.nodeType)=="number"){ elem.appendChild(n); }else{ -_327(_326,n); +_363=_364(n,_363); } } } return elem; -}; -MochiKit.DOM.replaceChildNodes=function(node){ +},replaceChildNodes:function(node){ var elem=node; var self=MochiKit.DOM; if(typeof (node)=="string"){ elem=self.getElement(node); arguments[0]=elem; } -var _328; -while((_328=elem.firstChild)){ -elem.removeChild(_328); +var _365; +while((_365=elem.firstChild)){ +elem.removeChild(_365); } if(arguments.length<2){ return elem; }else{ return self.appendChildNodes.apply(this,arguments); } -}; -MochiKit.DOM.createDOM=function(name,_329){ +},createDOM:function(name,_366){ var elem; var self=MochiKit.DOM; +var m=MochiKit.Base; +if(typeof (_366)=="string"||typeof (_366)=="number"){ +var args=m.extend([name,null],arguments,1); +return arguments.callee.apply(this,args); +} if(typeof (name)=="string"){ -if(_329&&"name" in _329&&!self.attributeArray.compliant){ -name="<"+name+" name=\""+self.escapeHTML(_329.name)+"\">"; +if(_366&&"name" in _366&&!self.attributeArray.compliant){ +name=("<"+name+" name=\""+self.escapeHTML(_366.name)+"\">"); } elem=self._document.createElement(name); }else{ elem=name; } -if(_329){ -self.updateNodeAttributes(elem,_329); +if(_366){ +self.updateNodeAttributes(elem,_366); } if(arguments.length<=2){ return elem; }else{ -var args=MochiKit.Base.extend([elem],arguments,2); +var args=m.extend([elem],arguments,2); return self.appendChildNodes.apply(this,args); } -}; -MochiKit.DOM.createDOMFunc=function(){ +},createDOMFunc:function(){ var m=MochiKit.Base; return m.partial.apply(this,m.extend([MochiKit.DOM.createDOM],arguments)); -}; -MochiKit.DOM.swapDOM=function(dest,src){ +},swapDOM:function(dest,src){ var self=MochiKit.DOM; dest=self.getElement(dest); -var _332=dest.parentNode; +var _369=dest.parentNode; if(src){ src=self.getElement(src); -_332.replaceChild(src,dest); +_369.replaceChild(src,dest); }else{ -_332.removeChild(dest); +_369.removeChild(dest); } return src; -}; -MochiKit.DOM.getElement=function(id){ +},getElement:function(id){ var self=MochiKit.DOM; if(arguments.length==1){ return ((typeof (id)=="string")?self._document.getElementById(id):id); }else{ return MochiKit.Base.map(self.getElement,arguments); } -}; -MochiKit.DOM.computedStyle=function(_334,_335,_336){ +},computedStyle:function(_371,_372,_373){ if(arguments.length==2){ -_336=_335; +_373=_372; } var self=MochiKit.DOM; -var el=self.getElement(_334); -var _338=self._document; -if(!el||el==_338){ +var el=self.getElement(_371); +var _375=self._document; +if(!el||el==_375){ return undefined; } if(el.currentStyle){ -return el.currentStyle[_335]; +return el.currentStyle[_372]; } -if(typeof (_338.defaultView)=="undefined"){ +if(typeof (_375.defaultView)=="undefined"){ return undefined; } -if(_338.defaultView==null){ +if(_375.defaultView===null){ return undefined; } -var _339=_338.defaultView.getComputedStyle(el,null); -if(typeof (_339)=="undefined"||_339==null){ +var _376=_375.defaultView.getComputedStyle(el,null); +if(typeof (_376)=="undefined"||_376===null){ return undefined; } -return _339.getPropertyValue(_336); -}; -MochiKit.DOM.getElementsByTagAndClassName=function(_340,_341,_342){ +return _376.getPropertyValue(_373); +},getElementsByTagAndClassName:function(_377,_378,_379){ var self=MochiKit.DOM; -if(typeof (_340)=="undefined"||_340==null){ -_340="*"; +if(typeof (_377)=="undefined"||_377===null){ +_377="*"; } -if(typeof (_342)=="undefined"||_342==null){ -_342=self._document; +if(typeof (_379)=="undefined"||_379===null){ +_379=self._document; } -_342=self.getElement(_342); -var _343=_342.getElementsByTagName(_340)||self._document.all; -if(typeof (_341)=="undefined"||_341==null){ -return MochiKit.Base.extend(null,_343); +_379=self.getElement(_379); +var _380=(_379.getElementsByTagName(_377)||self._document.all); +if(typeof (_378)=="undefined"||_378===null){ +return MochiKit.Base.extend(null,_380); } -var _344=[]; -for(var i=0;i<_343.length;i++){ -var _345=_343[i]; -var _346=_345.className.split(" "); -for(var j=0;j<_346.length;j++){ -if(_346[j]==_341){ -_344.push(_345); +var _381=[]; +for(var i=0;i<_380.length;i++){ +var _382=_380[i]; +var _383=_382.className.split(" "); +for(var j=0;j<_383.length;j++){ +if(_383[j]==_378){ +_381.push(_382); break; } } } -return _344; -}; -MochiKit.DOM._newCallStack=function(path,once){ +return _381; +},_newCallStack:function(path,once){ var rval=function(){ -var _349=arguments.callee.callStack; -for(var i=0;i<_349.length;i++){ -if(_349[i].apply(this,arguments)===false){ +var _386=arguments.callee.callStack; +for(var i=0;i<_386.length;i++){ +if(_386[i].apply(this,arguments)===false){ break; } } @@ -2705,107 +3007,98 @@ return rval; }; rval.callStack=[]; return rval; -}; -MochiKit.DOM.addToCallStack=function(_350,path,func,once){ +},addToCallStack:function(_387,path,func,once){ var self=MochiKit.DOM; -var _351=_350[path]; -var _352=_351; -if(!(typeof (_351)=="function"&&typeof (_351.callStack)=="object"&&_351.callStack!=null)){ -_352=self._newCallStack(path,once); -if(typeof (_351)=="function"){ -_352.callStack.push(_351); +var _388=_387[path]; +var _389=_388; +if(!(typeof (_388)=="function"&&typeof (_388.callStack)=="object"&&_388.callStack!==null)){ +_389=self._newCallStack(path,once); +if(typeof (_388)=="function"){ +_389.callStack.push(_388); } -_350[path]=_352; +_387[path]=_389; } -_352.callStack.push(func); -}; -MochiKit.DOM.addLoadEvent=function(func){ +_389.callStack.push(func); +},addLoadEvent:function(func){ var self=MochiKit.DOM; self.addToCallStack(self._window,"onload",func,true); -}; -MochiKit.DOM.focusOnLoad=function(_353){ +},focusOnLoad:function(_390){ var self=MochiKit.DOM; self.addLoadEvent(function(){ -_353=self.getElement(_353); -if(_353){ -_353.focus(); +_390=self.getElement(_390); +if(_390){ +_390.focus(); } }); -}; -MochiKit.DOM.setElementClass=function(_354,_355){ +},setElementClass:function(_391,_392){ var self=MochiKit.DOM; -var obj=self.getElement(_354); +var obj=self.getElement(_391); if(self.attributeArray.compliant){ -obj.setAttribute("class",_355); +obj.setAttribute("class",_392); }else{ -obj.setAttribute("className",_355); +obj.setAttribute("className",_392); } -}; -MochiKit.DOM.toggleElementClass=function(_356){ +},toggleElementClass:function(_393){ var self=MochiKit.DOM; for(var i=1;i/g,">"); -}; -MochiKit.DOM.toHTML=function(dom){ +},toHTML:function(dom){ return MochiKit.DOM.emitHTML(dom).join(""); -}; -MochiKit.DOM.emitHTML=function(dom,lst){ -if(typeof (lst)=="undefined"||lst==null){ +},emitHTML:function(dom,lst){ +if(typeof (lst)=="undefined"||lst===null){ lst=[]; } -var _372=[dom]; +var _409=[dom]; var self=MochiKit.DOM; -var _373=self.escapeHTML; -var _374=self.attributeArray; -while(_372.length){ -dom=_372.pop(); +var _410=self.escapeHTML; +var _411=self.attributeArray; +while(_409.length){ +dom=_409.pop(); if(typeof (dom)=="string"){ lst.push(dom); }else{ if(dom.nodeType==1){ lst.push("<"+dom.nodeName.toLowerCase()); -var _375=[]; -var _376=_374(dom); -for(var i=0;i<_376.length;i++){ -var a=_376[i]; -_375.push([" ",a.name,"=\"",_373(a.value),"\""]); +var _412=[]; +var _413=_411(dom); +for(var i=0;i<_413.length;i++){ +var a=_413[i]; +_412.push([" ",a.name,"=\"",_410(a.value),"\""]); } -_375.sort(); -for(i=0;i<_375.length;i++){ -var _377=_375[i]; -for(var j=0;j<_377.length;j++){ -lst.push(_377[j]); +_412.sort(); +for(i=0;i<_412.length;i++){ +var _414=_412[i]; +for(var j=0;j<_414.length;j++){ +lst.push(_414[j]); } } if(dom.hasChildNodes()){ lst.push(">"); -_372.push(""); -var _378=dom.childNodes; -for(i=_378.length-1;i>=0;i--){ -_372.push(_378[i]); +_409.push(""); +var _415=dom.childNodes; +for(i=_415.length-1;i>=0;i--){ +_409.push(_415[i]); } }else{ lst.push("/>"); } }else{ if(dom.nodeType==3){ -lst.push(_373(dom.nodeValue)); +lst.push(_410(dom.nodeValue)); } } } } return lst; -}; -MochiKit.DOM.setDisplayForElement=function(_379,_380){ +},setDisplayForElement:function(_416,_417){ var m=MochiKit.Base; -var _381=m.extend(null,arguments,1); -MochiKit.Iter.forEach(m.filter(null,m.map(MochiKit.DOM.getElement,_381)),function(_380){ -_380.style.display=_379; +var _418=m.extend(null,arguments,1); +MochiKit.Iter.forEach(m.filter(null,m.map(MochiKit.DOM.getElement,_418)),function(_417){ +_417.style.display=_416; }); -}; -MochiKit.DOM.scrapeText=function(node,_382){ +},scrapeText:function(node,_419){ var rval=[]; (function(node){ var cn=node.childNodes; @@ -2885,89 +3173,92 @@ arguments.callee.call(this,cn[i]); arguments.callee.call(this,cn[i]); } } -var _384=node.nodeValue; -if(typeof (_384)=="string"){ -rval.push(_384); +var _421=node.nodeValue; +if(typeof (_421)=="string"){ +rval.push(_421); } })(MochiKit.DOM.getElement(node)); -if(_382){ +if(_419){ return rval; }else{ return rval.join(""); } -}; -MochiKit.DOM.__new__=function(win){ +},__new__:function(win){ var m=MochiKit.Base; this._document=document; this._window=win; this.domConverters=new m.AdapterRegistry(); -var _385=this._document.createElement("span"); -var _386; -if(_385.attributes.length>0){ -var _387=m.filter; -_386=function(node){ -return _387(_386.ignoreAttrFilter,node.attributes); +var _422=this._document.createElement("span"); +var _423; +if(_422&&_422.attributes&&_422.attributes.length>0){ +var _424=m.filter; +_423=function(node){ +return _424(_423.ignoreAttrFilter,node.attributes); }; -_386.ignoreAttr={}; -MochiKit.Iter.forEach(_385.attributes,function(a){ -_386.ignoreAttr[a.name]=a.value; +_423.ignoreAttr={}; +MochiKit.Iter.forEach(_422.attributes,function(a){ +_423.ignoreAttr[a.name]=a.value; }); -_386.ignoreAttrFilter=function(a){ -return (_386.ignoreAttr[a.name]!=a.value); +_423.ignoreAttrFilter=function(a){ +return (_423.ignoreAttr[a.name]!=a.value); }; -_386.compliant=false; -_386.renames={"class":"className","checked":"defaultChecked","usemap":"useMap","for":"htmlFor"}; +_423.compliant=false; +_423.renames={"class":"className","checked":"defaultChecked","usemap":"useMap","for":"htmlFor"}; }else{ -_386=function(node){ +_423=function(node){ return node.attributes; }; -_386.compliant=true; -_386.renames={}; +_423.compliant=true; +_423.renames={}; } -this.attributeArray=_386; -var _388=this.createDOMFunc; -this.UL=_388("ul"); -this.OL=_388("ol"); -this.LI=_388("li"); -this.TD=_388("td"); -this.TR=_388("tr"); -this.TBODY=_388("tbody"); -this.THEAD=_388("thead"); -this.TFOOT=_388("tfoot"); -this.TABLE=_388("table"); -this.TH=_388("th"); -this.INPUT=_388("input"); -this.SPAN=_388("span"); -this.A=_388("a"); -this.DIV=_388("div"); -this.IMG=_388("img"); -this.BUTTON=_388("button"); -this.TT=_388("tt"); -this.PRE=_388("pre"); -this.H1=_388("h1"); -this.H2=_388("h2"); -this.H3=_388("h3"); -this.BR=_388("br"); -this.HR=_388("hr"); -this.LABEL=_388("label"); -this.TEXTAREA=_388("textarea"); -this.FORM=_388("form"); -this.P=_388("p"); -this.SELECT=_388("select"); -this.OPTION=_388("option"); -this.OPTGROUP=_388("optgroup"); -this.LEGEND=_388("legend"); -this.FIELDSET=_388("fieldset"); -this.STRONG=_388("strong"); -this.CANVAS=_388("canvas"); +this.attributeArray=_423; +var _425=this.createDOMFunc; +this.UL=_425("ul"); +this.OL=_425("ol"); +this.LI=_425("li"); +this.TD=_425("td"); +this.TR=_425("tr"); +this.TBODY=_425("tbody"); +this.THEAD=_425("thead"); +this.TFOOT=_425("tfoot"); +this.TABLE=_425("table"); +this.TH=_425("th"); +this.INPUT=_425("input"); +this.SPAN=_425("span"); +this.A=_425("a"); +this.DIV=_425("div"); +this.IMG=_425("img"); +this.BUTTON=_425("button"); +this.TT=_425("tt"); +this.PRE=_425("pre"); +this.H1=_425("h1"); +this.H2=_425("h2"); +this.H3=_425("h3"); +this.BR=_425("br"); +this.HR=_425("hr"); +this.LABEL=_425("label"); +this.TEXTAREA=_425("textarea"); +this.FORM=_425("form"); +this.P=_425("p"); +this.SELECT=_425("select"); +this.OPTION=_425("option"); +this.OPTGROUP=_425("optgroup"); +this.LEGEND=_425("legend"); +this.FIELDSET=_425("fieldset"); +this.STRONG=_425("strong"); +this.CANVAS=_425("canvas"); this.hideElement=m.partial(this.setDisplayForElement,"none"); this.showElement=m.partial(this.setDisplayForElement,"block"); this.removeElement=this.swapDOM; this.$=this.getElement; this.EXPORT_TAGS={":common":this.EXPORT,":all":m.concat(this.EXPORT,this.EXPORT_OK)}; m.nameFunctions(this); -}; -MochiKit.DOM.__new__(this); +}}); +MochiKit.DOM.__new__(((typeof (window)=="undefined")?this:window)); +if(!MochiKit.__compat__){ +withWindow=MochiKit.DOM.withWindow; +withDocument=MochiKit.DOM.withDocument; +} MochiKit.Base._exportSymbols(this,MochiKit.DOM); if(typeof (dojo)!="undefined"){ dojo.provide("MochiKit.LoggingPane"); @@ -2990,41 +3281,42 @@ MochiKit.LoggingPane.NAME="MochiKit.Logg MochiKit.LoggingPane={}; } MochiKit.LoggingPane.NAME="MochiKit.LoggingPane"; -MochiKit.LoggingPane.VERSION="1.2"; +MochiKit.LoggingPane.VERSION="1.3.1"; MochiKit.LoggingPane.__repr__=function(){ return "["+this.NAME+" "+this.VERSION+"]"; }; MochiKit.LoggingPane.toString=function(){ return this.__repr__(); }; -MochiKit.LoggingPane.createLoggingPane=function(_389){ +MochiKit.LoggingPane.createLoggingPane=function(_426){ var m=MochiKit.LoggingPane; -_389=!(!_389); -if(m._loggingPane&&m._loggingPane.inline!=_389){ +_426=!(!_426); +if(m._loggingPane&&m._loggingPane.inline!=_426){ m._loggingPane.closePane(); m._loggingPane=null; } if(!m._loggingPane||m._loggingPane.closed){ -m._loggingPane=new m.LoggingPane(_389,MochiKit.Logging.logger); +m._loggingPane=new m.LoggingPane(_426,MochiKit.Logging.logger); } return m._loggingPane; }; -MochiKit.LoggingPane.LoggingPane=function(_390,_391){ -if(typeof (_391)=="undefined"||_391==null){ -_391=MochiKit.Logging.logger; +MochiKit.LoggingPane.LoggingPane=function(_427,_428){ +if(typeof (_428)=="undefined"||_428===null){ +_428=MochiKit.Logging.logger; } -this.logger=_391; -var _392=MochiKit.Base.update; -var _393=MochiKit.Base.updatetree; +this.logger=_428; +var _429=MochiKit.Base.update; +var _430=MochiKit.Base.updatetree; var bind=MochiKit.Base.bind; -var _394=MochiKit.Base.clone; +var _431=MochiKit.Base.clone; var win=window; +var uid="_MochiKit_LoggingPane"; if(typeof (MochiKit.DOM)!="undefined"){ win=MochiKit.DOM.currentWindow(); } -if(!_390){ +if(!_427){ var url=win.location.href.split("?")[0].replace(/[:\/.><&]/g,"_"); -var name="MochiKit_LoggingPane_"+url; +var name=uid+"_"+url; var nwin=win.open("",name,"dependent,resizable,height=200"); if(!nwin){ alert("Not able to open debugging window due to pop-up blocking."); @@ -3037,81 +3329,89 @@ this.doc=doc; } var doc=win.document; this.doc=doc; -var _396=doc.getElementById("_debugPane"); -if(_396&&typeof (_396.loggingPane)!="undefined"){ -_396.loggingPane.logger=this.logger; -_396.loggingPane.buildAndApplyFilter(); -return _396.loggingPane; +var _434=doc.getElementById(uid); +var _435=!!_434; +if(_434&&typeof (_434.loggingPane)!="undefined"){ +_434.loggingPane.logger=this.logger; +_434.loggingPane.buildAndApplyFilter(); +return _434.loggingPane; } -_396=doc.createElement("div"); -_396.id="_debugPane"; -_396.loggingPane=this; -var _397=doc.createElement("input"); -var _398=doc.createElement("input"); -var _399=doc.createElement("button"); -var _400=doc.createElement("button"); -var _401=doc.createElement("button"); -var _402=doc.createElement("button"); -var _403=doc.createElement("div"); -var _404=doc.createElement("div"); -var _405="_debugPaneListener"; -this.colorTable=_394(this.colorTable); -var _406=[]; -var _407=null; -var _408=function(msg){ -var _409=msg.level; -if(typeof (_409)=="number"){ -_409=MochiKit.Logging.LogLevel[_409]; +if(_435){ +var _436; +while((_436=_434.firstChild)){ +_434.removeChild(_436); } -return _409; +}else{ +_434=doc.createElement("div"); +_434.id=uid; +} +_434.loggingPane=this; +var _437=doc.createElement("input"); +var _438=doc.createElement("input"); +var _439=doc.createElement("button"); +var _440=doc.createElement("button"); +var _441=doc.createElement("button"); +var _442=doc.createElement("button"); +var _443=doc.createElement("div"); +var _444=doc.createElement("div"); +var _445=uid+"_Listener"; +this.colorTable=_431(this.colorTable); +var _446=[]; +var _447=null; +var _448=function(msg){ +var _449=msg.level; +if(typeof (_449)=="number"){ +_449=MochiKit.Logging.LogLevel[_449]; +} +return _449; }; -var _410=function(msg){ +var _450=function(msg){ return msg.info.join(" "); }; -var _411=bind(function(msg){ -var _412=_408(msg); -var text=_410(msg); -var c=this.colorTable[_412]; +var _451=bind(function(msg){ +var _452=_448(msg); +var text=_450(msg); +var c=this.colorTable[_452]; var p=doc.createElement("span"); -p.className="MochiKit-LogMessage MochiKit-LogLevel-"+_412; +p.className="MochiKit-LogMessage MochiKit-LogLevel-"+_452; p.style.cssText="margin: 0px; white-space: -moz-pre-wrap; white-space: -o-pre-wrap; white-space: pre-wrap; white-space: pre-line; word-wrap: break-word; wrap-option: emergency; color: "+c; -p.appendChild(doc.createTextNode(_412+": "+text)); -_404.appendChild(p); -_404.appendChild(doc.createElement("br")); -if(_403.offsetHeight>_403.scrollHeight){ -_403.scrollTop=0; +p.appendChild(doc.createTextNode(_452+": "+text)); +_444.appendChild(p); +_444.appendChild(doc.createElement("br")); +if(_443.offsetHeight>_443.scrollHeight){ +_443.scrollTop=0; }else{ -_403.scrollTop=_403.scrollHeight; +_443.scrollTop=_443.scrollHeight; } },this); -var _415=function(msg){ -_406[_406.length]=msg; -_411(msg); +var _454=function(msg){ +_446[_446.length]=msg; +_451(msg); }; -var _416=function(){ -var _417,infore; +var _455=function(){ +var _456,infore; try{ -_417=new RegExp(_397.value); -infore=new RegExp(_398.value); +_456=new RegExp(_437.value); +infore=new RegExp(_438.value); } catch(e){ logDebug("Error in filter regex: "+e.message); return null; } return function(msg){ -return (_417.test(_408(msg))&&infore.test(_410(msg))); +return (_456.test(_448(msg))&&infore.test(_450(msg))); }; }; -var _418=function(){ -while(_404.firstChild){ -_404.removeChild(_404.firstChild); +var _457=function(){ +while(_444.firstChild){ +_444.removeChild(_444.firstChild); } }; -var _419=function(){ -_406=[]; -_418(); +var _458=function(){ +_446=[]; +_457(); }; -var _420=bind(function(){ +var _459=bind(function(){ if(this.closed){ return; } @@ -3119,83 +3419,85 @@ MochiKit.LoggingPane._loggingPane=null; if(MochiKit.LoggingPane._loggingPane==this){ MochiKit.LoggingPane._loggingPane=null; } -this.logger.removeListener(_405); -_396.loggingPane=null; -if(_390){ -_396.parentNode.removeChild(_396); +this.logger.removeListener(_445); +_434.loggingPane=null; +if(_427){ +_434.parentNode.removeChild(_434); }else{ this.win.close(); } },this); -var _421=function(){ -_418(); -for(var i=0;i<_406.length;i++){ -var msg=_406[i]; -if(_407==null||_407(msg)){ -_411(msg); +var _460=function(){ +_457(); +for(var i=0;i<_446.length;i++){ +var msg=_446[i]; +if(_447===null||_447(msg)){ +_451(msg); } } }; this.buildAndApplyFilter=function(){ -_407=_416(); -_421(); -this.logger.removeListener(_405); -this.logger.addListener(_405,_407,_415); +_447=_455(); +_460(); +this.logger.removeListener(_445); +this.logger.addListener(_445,_447,_454); }; -var _422=bind(function(){ -_406=this.logger.getMessages(); -_421(); +var _461=bind(function(){ +_446=this.logger.getMessages(); +_460(); },this); -var _423=bind(function(_424){ -_424=_424||window.event; -key=_424.which||_424.keyCode; +var _462=bind(function(_463){ +_463=_463||window.event; +key=_463.which||_463.keyCode; if(key==13){ this.buildAndApplyFilter(); } },this); -var _425="display: block; left: 0px; bottom: 0px; position: fixed; width: 100%; background-color: white; font: "+this.logFont; -if(_390){ -_425+="; height: 10em; border-top: 2px solid black"; +var _464="display: block; z-index: 1000; left: 0px; bottom: 0px; position: fixed; width: 100%; background-color: white; font: "+this.logFont; +if(_427){ +_464+="; height: 10em; border-top: 2px solid black"; }else{ -_425+="; height: 100%;"; +_464+="; height: 100%;"; } -_396.style.cssText=_425; -doc.body.appendChild(_396); -_425={"cssText":"width: 33%; display: inline; font: "+this.logFont}; -_393(_397,{"value":"FATAL|ERROR|WARNING|INFO|DEBUG","onkeypress":_423,"style":_425}); -_396.appendChild(_397); -_393(_398,{"value":".*","onkeypress":_423,"style":_425}); -_396.appendChild(_398); -_425="width: 8%; display:inline; font: "+this.logFont; -_399.appendChild(doc.createTextNode("Filter")); -_399.onclick=bind(this.buildAndApplyFilter,this); -_399.style.cssText=_425; -_396.appendChild(_399); -_400.appendChild(doc.createTextNode("Load")); -_400.onclick=_422; -_400.style.cssText=_425; -_396.appendChild(_400); -_401.appendChild(doc.createTextNode("Clear")); -_401.onclick=_419; -_401.style.cssText=_425; -_396.appendChild(_401); -_402.appendChild(doc.createTextNode("Close")); -_402.onclick=_420; -_402.style.cssText=_425; -_396.appendChild(_402); -_403.style.cssText="overflow: auto; width: 100%"; -_404.style.cssText="width: 100%; height: "+(_390?"8em":"100%"); -_403.appendChild(_404); -_396.appendChild(_403); +_434.style.cssText=_464; +if(!_435){ +doc.body.appendChild(_434); +} +_464={"cssText":"width: 33%; display: inline; font: "+this.logFont}; +_430(_437,{"value":"FATAL|ERROR|WARNING|INFO|DEBUG","onkeypress":_462,"style":_464}); +_434.appendChild(_437); +_430(_438,{"value":".*","onkeypress":_462,"style":_464}); +_434.appendChild(_438); +_464="width: 8%; display:inline; font: "+this.logFont; +_439.appendChild(doc.createTextNode("Filter")); +_439.onclick=bind("buildAndApplyFilter",this); +_439.style.cssText=_464; +_434.appendChild(_439); +_440.appendChild(doc.createTextNode("Load")); +_440.onclick=_461; +_440.style.cssText=_464; +_434.appendChild(_440); +_441.appendChild(doc.createTextNode("Clear")); +_441.onclick=_458; +_441.style.cssText=_464; +_434.appendChild(_441); +_442.appendChild(doc.createTextNode("Close")); +_442.onclick=_459; +_442.style.cssText=_464; +_434.appendChild(_442); +_443.style.cssText="overflow: auto; width: 100%"; +_444.style.cssText="width: 100%; height: "+(_427?"8em":"100%"); +_443.appendChild(_444); +_434.appendChild(_443); this.buildAndApplyFilter(); -_422(); -if(_390){ +_461(); +if(_427){ this.win=undefined; }else{ this.win=win; } -this.inline=_390; -this.closePane=_420; +this.inline=_427; +this.closePane=_459; this.closed=false; return this; }; @@ -3228,60 +3530,60 @@ MochiKit.Color.NAME="MochiKit.Color"; MochiKit.Color={}; } MochiKit.Color.NAME="MochiKit.Color"; -MochiKit.Color.VERSION="1.2"; +MochiKit.Color.VERSION="1.3.1"; MochiKit.Color.__repr__=function(){ return "["+this.NAME+" "+this.VERSION+"]"; }; MochiKit.Color.toString=function(){ return this.__repr__(); }; -MochiKit.Color.Color=function(red,_427,blue,_429){ -if(typeof (_429)=="undefined"||_429==null){ -_429=1; +MochiKit.Color.Color=function(red,_466,blue,_468){ +if(typeof (_468)=="undefined"||_468===null){ +_468=1; } -this.rgb={r:red,g:_427,b:blue,a:_429}; +this.rgb={r:red,g:_466,b:blue,a:_468}; }; -MochiKit.Color.Color.prototype={__class__:MochiKit.Color.Color,colorWithAlpha:function(_430){ +MochiKit.Color.Color.prototype={__class__:MochiKit.Color.Color,colorWithAlpha:function(_469){ var rgb=this.rgb; var m=MochiKit.Color; -return m.Color.fromRGB(rgb.r,rgb.g,rgb.b,_430); +return m.Color.fromRGB(rgb.r,rgb.g,rgb.b,_469); },colorWithHue:function(hue){ var hsl=this.asHSL(); hsl.h=hue; var m=MochiKit.Color; return m.Color.fromHSL(hsl); -},colorWithSaturation:function(_434){ +},colorWithSaturation:function(_473){ var hsl=this.asHSL(); -hsl.s=_434; +hsl.s=_473; var m=MochiKit.Color; return m.Color.fromHSL(hsl); -},colorWithLightness:function(_435){ +},colorWithLightness:function(_474){ var hsl=this.asHSL(); -hsl.l=_435; +hsl.l=_474; var m=MochiKit.Color; return m.Color.fromHSL(hsl); -},darkerColorWithLevel:function(_436){ +},darkerColorWithLevel:function(_475){ var hsl=this.asHSL(); -hsl.l=Math.max(hsl.l-_436,0); +hsl.l=Math.max(hsl.l-_475,0); var m=MochiKit.Color; return m.Color.fromHSL(hsl); -},lighterColorWithLevel:function(_437){ +},lighterColorWithLevel:function(_476){ var hsl=this.asHSL(); -Math.min(hsl.l+_437,1); +hsl.l=Math.min(hsl.l+_476,1); var m=MochiKit.Color; return m.Color.fromHSL(hsl); -},blendedColor:function(_438,_439){ -if(typeof (_439)=="undefined"||_439==null){ -_439=0.5; +},blendedColor:function(_477,_478){ +if(typeof (_478)=="undefined"||_478===null){ +_478=0.5; } -var sf=1-_439; +var sf=1-_478; var s=this.rgb; -var d=_438.rgb; -var df=_439; +var d=_477.rgb; +var df=_478; return MochiKit.Color.Color.fromRGB((s.r*sf)+(d.r*df),(s.g*sf)+(d.g*df),(s.b*sf)+(d.b*df),(s.a*sf)+(d.a*df)); -},compareRGB:function(_442){ +},compareRGB:function(_481){ var a=this.asRGB(); -var b=_442.asRGB(); +var b=_481.asRGB(); return MochiKit.Base.compare([a.r,a.g,a.b,a.a],[b.r,b.g,b.b,b.a]); },isLight:function(){ return this.asHSL().b>0.5; @@ -3335,7 +3637,7 @@ var c=this.rgb; },asHSV:function(){ var hsv=this.hsv; var c=this.rgb; -if(typeof (hsv)=="undefined"||hsv==null){ +if(typeof (hsv)=="undefined"||hsv===null){ hsv=MochiKit.Color.rgbToHSV(this.rgb); this.hsv=hsv; } @@ -3343,7 +3645,7 @@ var c=this.rgb; },asHSL:function(){ var hsl=this.hsl; var c=this.rgb; -if(typeof (hsl)=="undefined"||hsl==null){ +if(typeof (hsl)=="undefined"||hsl===null){ hsl=MochiKit.Color.rgbToHSL(this.rgb); this.hsl=hsl; } @@ -3355,111 +3657,114 @@ return this.__class__.NAME+"("+col.join( var col=[c.r,c.g,c.b,c.a]; return this.__class__.NAME+"("+col.join(", ")+")"; }}; -MochiKit.Base.update(MochiKit.Color.Color,{fromRGB:function(red,_447,blue,_448){ -var _449=MochiKit.Color.Color; +MochiKit.Base.update(MochiKit.Color.Color,{fromRGB:function(red,_486,blue,_487){ +var _488=MochiKit.Color.Color; if(arguments.length==1){ var rgb=red; red=rgb.r; -_447=rgb.g; +_486=rgb.g; blue=rgb.b; if(typeof (rgb.a)=="undefined"){ -_448=undefined; +_487=undefined; }else{ -_448=rgb.a; +_487=rgb.a; } } -return new _449(red,_447,blue,_448); -},fromHSL:function(hue,_450,_451,_452){ +return new _488(red,_486,blue,_487); +},fromHSL:function(hue,_489,_490,_491){ var m=MochiKit.Color; return m.Color.fromRGB(m.hslToRGB.apply(m,arguments)); -},fromHSV:function(hue,_453,_454,_455){ +},fromHSV:function(hue,_492,_493,_494){ var m=MochiKit.Color; return m.Color.fromRGB(m.hsvToRGB.apply(m,arguments)); },fromName:function(name){ -var _456=MochiKit.Color.Color; -var _457=_456._namedColors[name.toLowerCase()]; -if(typeof (_457)=="string"){ -return _456.fromHexString(_457); +var _495=MochiKit.Color.Color; +if(name.charAt(0)=="\""){ +name=name.substr(1,name.length-2); +} +var _496=_495._namedColors[name.toLowerCase()]; +if(typeof (_496)=="string"){ +return _495.fromHexString(_496); }else{ if(name=="transparent"){ -return _456.transparentColor(); +return _495.transparentColor(); } } return null; -},fromString:function(_458){ +},fromString:function(_497){ var self=MochiKit.Color.Color; -var _459=_458.substr(0,3); -if(_459=="rgb"){ -return self.fromRGBString(_458); +var _498=_497.substr(0,3); +if(_498=="rgb"){ +return self.fromRGBString(_497); }else{ -if(_459=="hsl"){ -return self.fromHSLString(_458); +if(_498=="hsl"){ +return self.fromHSLString(_497); }else{ -if(_458.charAt(0)=="#"){ -return self.fromHexString(_458); +if(_497.charAt(0)=="#"){ +return self.fromHexString(_497); } } } -return self.fromName(_458); -},fromHexString:function(_460){ -if(_460.charAt(0)=="#"){ -_460=_460.substring(1); +return self.fromName(_497); +},fromHexString:function(_499){ +if(_499.charAt(0)=="#"){ +_499=_499.substring(1); } -var _461=[]; +var _500=[]; var i,hex; -if(_460.length==3){ +if(_499.length==3){ for(i=0;i<3;i++){ -hex=_460.substr(i,1); -_461.push(parseInt(hex+hex,16)/255); +hex=_499.substr(i,1); +_500.push(parseInt(hex+hex,16)/255); } }else{ for(i=0;i<6;i+=2){ -hex=_460.substr(i,2); -_461.push(parseInt(hex,16)/255); +hex=_499.substr(i,2); +_500.push(parseInt(hex,16)/255); } } -var _462=MochiKit.Color.Color; -return _462.fromRGB.apply(_462,_461); -},_fromColorString:function(pre,_464,_465,_466){ -if(_466.indexOf(pre)==0){ -_466=_466.substring(_466.indexOf("(",3)+1,_466.length-1); +var _501=MochiKit.Color.Color; +return _501.fromRGB.apply(_501,_500); +},_fromColorString:function(pre,_503,_504,_505){ +if(_505.indexOf(pre)===0){ +_505=_505.substring(_505.indexOf("(",3)+1,_505.length-1); } -var _467=_466.split(/\s*,\s*/); -var _468=[]; -for(var i=0;i<_467.length;i++){ -var c=_467[i]; +var _506=_505.split(/\s*,\s*/); +var _507=[]; +for(var i=0;i<_506.length;i++){ +var c=_506[i]; var val; -var _469=c.substring(c.length-3); +var _508=c.substring(c.length-3); if(c.charAt(c.length-1)=="%"){ val=0.01*parseFloat(c.substring(0,c.length-1)); }else{ -if(_469=="deg"){ +if(_508=="deg"){ val=parseFloat(c)/360; }else{ -if(_469=="rad"){ +if(_508=="rad"){ val=parseFloat(c)/(Math.PI*2); }else{ -val=_465[i]*parseFloat(c); +val=_504[i]*parseFloat(c); } } } -_468.push(val); +_507.push(val); } -return this[_464].apply(this,_468); -},fromComputedStyle:function(elem,_470,_471){ +return this[_503].apply(this,_507); +},fromComputedStyle:function(elem,_509,_510){ var d=MochiKit.DOM; var cls=MochiKit.Color.Color; for(elem=d.getElement(elem);elem;elem=elem.parentNode){ -var _472=d.computedStyle.apply(d,arguments); -if(!_472){ +var _511=d.computedStyle.apply(d,arguments); +if(!_511){ continue; } -var _473=cls.fromString(_472); -if(!_473){ +var _512=cls.fromString(_511); +if(!_512){ break; } -if(_473.asRGB().a>0){ -return _473; +if(_512.asRGB().a>0){ +return _512; } } return null; @@ -3472,13 +3777,13 @@ return MochiKit.Base.clone(MochiKit.Colo },namedColors:function(){ return MochiKit.Base.clone(MochiKit.Color.Color._namedColors); }}); -MochiKit.Base.update(MochiKit.Color,{clampColorComponent:function(v,_474){ -v*=_474; +MochiKit.Base.update(MochiKit.Color,{clampColorComponent:function(v,_513){ +v*=_513; if(v<0){ return 0; }else{ -if(v>_474){ -return _474; +if(v>_513){ +return _513; }else{ return v; } @@ -3506,118 +3811,118 @@ return val; } } return val; -},hsvToRGB:function(hue,_477,_478,_479){ +},hsvToRGB:function(hue,_516,_517,_518){ if(arguments.length==1){ var hsv=hue; hue=hsv.h; -_477=hsv.s; -_478=hsv.v; -_479=hsv.a; +_516=hsv.s; +_517=hsv.v; +_518=hsv.a; } var red; -var _480; +var _519; var blue; -if(_477==0){ +if(_516===0){ red=0; -_480=0; +_519=0; blue=0; }else{ var i=Math.floor(hue*6); var f=(hue*6)-i; -var p=_478*(1-_477); -var q=_478*(1-(_477*f)); -var t=_478*(1-(_477*(1-f))); +var p=_517*(1-_516); +var q=_517*(1-(_516*f)); +var t=_517*(1-(_516*(1-f))); switch(i){ case 1: red=q; -_480=_478; +_519=_517; blue=p; break; case 2: red=p; -_480=_478; +_519=_517; blue=t; break; case 3: red=p; -_480=q; -blue=_478; +_519=q; +blue=_517; break; case 4: red=t; -_480=p; -blue=_478; +_519=p; +blue=_517; break; case 5: -red=_478; -_480=p; +red=_517; +_519=p; blue=q; break; case 6: case 0: -red=_478; -_480=t; +red=_517; +_519=t; blue=p; break; } } -return {r:red,g:_480,b:blue,a:_479}; -},hslToRGB:function(hue,_482,_483,_484){ +return {r:red,g:_519,b:blue,a:_518}; +},hslToRGB:function(hue,_521,_522,_523){ if(arguments.length==1){ var hsl=hue; hue=hsl.h; -_482=hsl.s; -_483=hsl.l; -_484=hsl.a; +_521=hsl.s; +_522=hsl.l; +_523=hsl.a; } var red; -var _485; +var _524; var blue; -if(_482==0){ -red=_483; -_485=_483; -blue=_483; +if(_521===0){ +red=_522; +_524=_522; +blue=_522; }else{ var m2; -if(_483<=0.5){ -m2=_483*(1+_482); +if(_522<=0.5){ +m2=_522*(1+_521); }else{ -m2=_483+_482-(_483*_482); +m2=_522+_521-(_522*_521); } -var m1=(2*_483)-m2; +var m1=(2*_522)-m2; var f=MochiKit.Color._hslValue; var h6=hue*6; red=f(m1,m2,h6+2); -_485=f(m1,m2,h6); +_524=f(m1,m2,h6); blue=f(m1,m2,h6-2); } -return {r:red,g:_485,b:blue,a:_484}; -},rgbToHSV:function(red,_489,blue,_490){ +return {r:red,g:_524,b:blue,a:_523}; +},rgbToHSV:function(red,_528,blue,_529){ if(arguments.length==1){ var rgb=red; red=rgb.r; -_489=rgb.g; +_528=rgb.g; blue=rgb.b; -_490=rgb.a; +_529=rgb.a; } -var max=Math.max(Math.max(red,_489),blue); -var min=Math.min(Math.min(red,_489),blue); +var max=Math.max(Math.max(red,_528),blue); +var min=Math.min(Math.min(red,_528),blue); var hue; -var _493; -var _494=max; +var _532; +var _533=max; if(min==max){ hue=0; -_493=0; +_532=0; }else{ -var _495=(max-min); -_493=_495/max; +var _534=(max-min); +_532=_534/max; if(red==max){ -hue=(_489-blue)/_495; +hue=(_528-blue)/_534; }else{ -if(_489==max){ -hue=2+((blue-red)/_495); +if(_528==max){ +hue=2+((blue-red)/_534); }else{ -hue=4+((red-_489)/_495); +hue=4+((red-_528)/_534); } } hue/=6; @@ -3628,37 +3933,37 @@ hue-=1; hue-=1; } } -return {h:hue,s:_493,v:_494,a:_490}; -},rgbToHSL:function(red,_496,blue,_497){ +return {h:hue,s:_532,v:_533,a:_529}; +},rgbToHSL:function(red,_535,blue,_536){ if(arguments.length==1){ var rgb=red; red=rgb.r; -_496=rgb.g; +_535=rgb.g; blue=rgb.b; -_497=rgb.a; +_536=rgb.a; } -var max=Math.max(red,Math.max(_496,blue)); -var min=Math.min(red,Math.min(_496,blue)); +var max=Math.max(red,Math.max(_535,blue)); +var min=Math.min(red,Math.min(_535,blue)); var hue; -var _498; -var _499=(max+min)/2; -var _500=max-min; -if(_500==0){ +var _537; +var _538=(max+min)/2; +var _539=max-min; +if(_539===0){ hue=0; -_498=0; +_537=0; }else{ -if(_499<=0.5){ -_498=_500/(max+min); +if(_538<=0.5){ +_537=_539/(max+min); }else{ -_498=_500/(2-max-min); +_537=_539/(2-max-min); } if(red==max){ -hue=(_496-blue)/_500; +hue=(_535-blue)/_539; }else{ -if(_496==max){ -hue=2+((blue-red)/_500); +if(_535==max){ +hue=2+((blue-red)/_539); }else{ -hue=4+((red-_496)/_500); +hue=4+((red-_535)/_539); } } hue/=6; @@ -3669,32 +3974,33 @@ hue-=1; hue-=1; } } -return {h:hue,s:_498,l:_499,a:_497}; +return {h:hue,s:_537,l:_538,a:_536}; },toColorPart:function(num){ -var _501=Math.round(num).toString(16); +num=Math.round(num); +var _540=num.toString(16); if(num<16){ -return "0"+_501; +return "0"+_540; } -return _501; +return _540; },__new__:function(){ var m=MochiKit.Base; this.Color.fromRGBString=m.bind(this.Color._fromColorString,this.Color,"rgb","fromRGB",[1/255,1/255,1/255,1]); this.Color.fromHSLString=m.bind(this.Color._fromColorString,this.Color,"hsl","fromHSL",[1/360,0.01,0.01,1]); -var _502=1/3; -var _503={black:[0,0,0],blue:[0,0,1],brown:[0.6,0.4,0.2],cyan:[0,1,1],darkGray:[_502,_502,_502],gray:[0.5,0.5,0.5],green:[0,1,0],lightGray:[2*_502,2*_502,2*_502],magenta:[1,0,1],orange:[1,0.5,0],purple:[0.5,0,0.5],red:[1,0,0],transparent:[0,0,0,0],white:[1,1,1],yellow:[1,1,0]}; -var _504=function(name,r,g,b,a){ +var _541=1/3; +var _542={black:[0,0,0],blue:[0,0,1],brown:[0.6,0.4,0.2],cyan:[0,1,1],darkGray:[_541,_541,_541],gray:[0.5,0.5,0.5],green:[0,1,0],lightGray:[2*_541,2*_541,2*_541],magenta:[1,0,1],orange:[1,0.5,0],purple:[0.5,0,0.5],red:[1,0,0],transparent:[0,0,0,0],white:[1,1,1],yellow:[1,1,0]}; +var _543=function(name,r,g,b,a){ var rval=this.fromRGB(r,g,b,a); this[name]=function(){ return rval; }; return rval; }; -for(var k in _503){ +for(var k in _542){ var name=k+"Color"; -var _507=m.concat([_504,this.Color,name],_503[k]); -this.Color[name]=m.bind.apply(null,_507); +var _545=m.concat([_543,this.Color,name],_542[k]); +this.Color[name]=m.bind.apply(null,_545); } -var _508=function(){ +var _546=function(){ for(var i=0;i1){ +var src=MochiKit.DOM.getElement(arguments[0]); +var sig=arguments[1]; +var obj=arguments[2]; +var func=arguments[3]; +for(var i=_562.length-1;i>=0;i--){ +var o=_562[i]; +if(o[0]===src&&o[1]===sig&&o[4]===obj&&o[5]===func){ +self._disconnect(o); +_562.splice(i,1); +return true; +} +} +}else{ +var idx=m.findIdentical(_562,_561); +if(idx>=0){ +self._disconnect(_561); +_562.splice(idx,1); +return true; +} +} +return false; +},disconnectAll:function(src,sig){ +src=MochiKit.DOM.getElement(src); +var m=MochiKit.Base; +var _563=m.flattenArguments(m.extend(null,arguments,1)); +var self=MochiKit.Signal; +var _564=self._disconnect; +var _565=self._observers; +if(_563.length===0){ +for(var i=_565.length-1;i>=0;i--){ +var _566=_565[i]; +if(_566[0]===src){ +_564(_566); +_565.splice(i,1); +} +} +}else{ +var sigs={}; +for(var i=0;i<_563.length;i++){ +sigs[_563[i]]=true; +} +for(var i=_565.length-1;i>=0;i--){ +var _566=_565[i]; +if(_566[0]===src&&_566[1] in sigs){ +_564(_566); +_565.splice(i,1); +} +} +} +},signal:function(src,sig){ +var _568=MochiKit.Signal._observers; +src=MochiKit.DOM.getElement(src); +var args=MochiKit.Base.extend(null,arguments,2); +var _569=[]; +for(var i=0;i<_568.length;i++){ +var _570=_568[i]; +if(_570[0]===src&&_570[1]===sig){ +try{ +_570[2].apply(src,args); +} +catch(e){ +_569.push(e); +} +} +} +if(_569.length==1){ +throw _569[0]; +}else{ +if(_569.length>1){ +var e=new Error("Multiple errors thrown in handling 'sig', see errors property"); +e.errors=_569; +throw e; +} +} +}}); +MochiKit.Signal.EXPORT_OK=[]; +MochiKit.Signal.EXPORT=["connect","disconnect","signal","disconnectAll"]; +MochiKit.Signal.__new__=function(win){ +var m=MochiKit.Base; +this._document=document; +this._window=win; +try{ +this.connect(window,"onunload",this._unloadCache); +} +catch(e){ +} +this.EXPORT_TAGS={":common":this.EXPORT,":all":m.concat(this.EXPORT,this.EXPORT_OK)}; +m.nameFunctions(this); +}; +MochiKit.Signal.__new__(this); +if(!MochiKit.__compat__){ +connect=MochiKit.Signal.connect; +disconnect=MochiKit.Signal.disconnect; +disconnectAll=MochiKit.Signal.disconnectAll; +signal=MochiKit.Signal.signal; +} +MochiKit.Base._exportSymbols(this,MochiKit.Signal); +if(typeof (dojo)!="undefined"){ dojo.provide("MochiKit.Visual"); dojo.require("MochiKit.Base"); dojo.require("MochiKit.DOM"); @@ -3737,198 +4415,198 @@ MochiKit.Visual.NAME="MochiKit.Visual"; MochiKit.Visual={}; } MochiKit.Visual.NAME="MochiKit.Visual"; -MochiKit.Visual.VERSION="1.2"; +MochiKit.Visual.VERSION="1.3.1"; MochiKit.Visual.__repr__=function(){ return "["+this.NAME+" "+this.VERSION+"]"; }; MochiKit.Visual.toString=function(){ return this.__repr__(); }; -MochiKit.Visual._RoundCorners=function(e,_510){ +MochiKit.Visual._RoundCorners=function(e,_571){ e=MochiKit.DOM.getElement(e); -this._setOptions(_510); +this._setOptions(_571); if(this.options.__unstable__wrapElement){ e=this._doWrap(e); } -var _511=this.options.color; +var _572=this.options.color; var C=MochiKit.Color.Color; if(this.options.color=="fromElement"){ -_511=C.fromBackground(e); +_572=C.fromBackground(e); }else{ -if(!(_511 instanceof C)){ -_511=C.fromString(_511); +if(!(_572 instanceof C)){ +_572=C.fromString(_572); } } -this.isTransparent=(_511.asRGB().a<=0); -var _513=this.options.bgColor; +this.isTransparent=(_572.asRGB().a<=0); +var _574=this.options.bgColor; if(this.options.bgColor=="fromParent"){ -_513=C.fromBackground(e.offsetParent); +_574=C.fromBackground(e.offsetParent); }else{ -if(!(_513 instanceof C)){ -_513=C.fromString(_513); +if(!(_574 instanceof C)){ +_574=C.fromString(_574); } } -this._roundCornersImpl(e,_511,_513); +this._roundCornersImpl(e,_572,_574); }; MochiKit.Visual._RoundCorners.prototype={_doWrap:function(e){ -var _514=e.parentNode; +var _575=e.parentNode; var doc=MochiKit.DOM.currentDocument(); -if(typeof (doc.defaultView)=="undefined"||doc.defaultView==null){ +if(typeof (doc.defaultView)=="undefined"||doc.defaultView===null){ return e; } -var _515=doc.defaultView.getComputedStyle(e,null); -if(typeof (_515)=="undefined"||_515==null){ +var _576=doc.defaultView.getComputedStyle(e,null); +if(typeof (_576)=="undefined"||_576===null){ return e; } -var _516=MochiKit.DOM.DIV({"style":{display:"block",marginTop:_515.getPropertyValue("padding-top"),marginRight:_515.getPropertyValue("padding-right"),marginBottom:_515.getPropertyValue("padding-bottom"),marginLeft:_515.getPropertyValue("padding-left"),padding:"0px"}}); -_516.innerHTML=e.innerHTML; +var _577=MochiKit.DOM.DIV({"style":{display:"block",marginTop:_576.getPropertyValue("padding-top"),marginRight:_576.getPropertyValue("padding-right"),marginBottom:_576.getPropertyValue("padding-bottom"),marginLeft:_576.getPropertyValue("padding-left"),padding:"0px"}}); +_577.innerHTML=e.innerHTML; e.innerHTML=""; -e.appendChild(_516); +e.appendChild(_577); return e; -},_roundCornersImpl:function(e,_517,_518){ +},_roundCornersImpl:function(e,_578,_579){ if(this.options.border){ -this._renderBorder(e,_518); +this._renderBorder(e,_579); } if(this._isTopRounded()){ -this._roundTopCorners(e,_517,_518); +this._roundTopCorners(e,_578,_579); } if(this._isBottomRounded()){ -this._roundBottomCorners(e,_517,_518); +this._roundBottomCorners(e,_578,_579); } -},_renderBorder:function(el,_519){ -var _520="1px solid "+this._borderColor(_519); -var _521="border-left: "+_520; -var _522="border-right: "+_520; -var _523="style='"+_521+";"+_522+"'"; -el.innerHTML="
"+el.innerHTML+"
"; -},_roundTopCorners:function(el,_524,_525){ -var _526=this._createCorner(_525); +},_renderBorder:function(el,_580){ +var _581="1px solid "+this._borderColor(_580); +var _582="border-left: "+_581; +var _583="border-right: "+_581; +var _584="style='"+_582+";"+_583+"'"; +el.innerHTML="
"+el.innerHTML+"
"; +},_roundTopCorners:function(el,_585,_586){ +var _587=this._createCorner(_586); for(var i=0;i=0;i--){ -_529.appendChild(this._createCornerSlice(_527,_528,i,"bottom")); +_590.appendChild(this._createCornerSlice(_588,_589,i,"bottom")); } el.style.paddingBottom=0; -el.appendChild(_529); -},_createCorner:function(_530){ +el.appendChild(_590); +},_createCorner:function(_591){ var dom=MochiKit.DOM; -return dom.DIV({style:{backgroundColor:_530.toString()}}); -},_createCornerSlice:function(_531,_532,n,_533){ -var _534=MochiKit.DOM.SPAN(); -var _535=_534.style; -_535.backgroundColor=_531.toString(); -_535.display="block"; -_535.height="1px"; -_535.overflow="hidden"; -_535.fontSize="1px"; -var _536=this._borderColor(_531,_532); -if(this.options.border&&n==0){ -_535.borderTopStyle="solid"; -_535.borderTopWidth="1px"; -_535.borderLeftWidth="0px"; -_535.borderRightWidth="0px"; -_535.borderBottomWidth="0px"; -_535.height="0px"; -_535.borderColor=_536.toString(); +return dom.DIV({style:{backgroundColor:_591.toString()}}); +},_createCornerSlice:function(_592,_593,n,_594){ +var _595=MochiKit.DOM.SPAN(); +var _596=_595.style; +_596.backgroundColor=_592.toString(); +_596.display="block"; +_596.height="1px"; +_596.overflow="hidden"; +_596.fontSize="1px"; +var _597=this._borderColor(_592,_593); +if(this.options.border&&n===0){ +_596.borderTopStyle="solid"; +_596.borderTopWidth="1px"; +_596.borderLeftWidth="0px"; +_596.borderRightWidth="0px"; +_596.borderBottomWidth="0px"; +_596.height="0px"; +_596.borderColor=_597.toString(); }else{ -if(_536){ -_535.borderColor=_536.toString(); -_535.borderStyle="solid"; -_535.borderWidth="0px 1px"; +if(_597){ +_596.borderColor=_597.toString(); +_596.borderStyle="solid"; +_596.borderWidth="0px 1px"; } } if(!this.options.compact&&(n==(this.options.numSlices-1))){ -_535.height="2px"; +_596.height="2px"; } -this._setMargin(_534,n,_533); -this._setBorder(_534,n,_533); -return _534; -},_setOptions:function(_537){ +this._setMargin(_595,n,_594); +this._setBorder(_595,n,_594); +return _595; +},_setOptions:function(_598){ this.options={corners:"all",color:"fromElement",bgColor:"fromParent",blend:true,border:false,compact:false,__unstable__wrapElement:false}; -MochiKit.Base.update(this.options,_537); +MochiKit.Base.update(this.options,_598); this.options.numSlices=(this.options.compact?2:4); },_whichSideTop:function(){ -var _538=this.options.corners; -if(this._hasString(_538,"all","top")){ +var _599=this.options.corners; +if(this._hasString(_599,"all","top")){ return ""; } -var _539=(_538.indexOf("tl")!=-1); -var _540=(_538.indexOf("tr")!=-1); -if(_539&&_540){ +var _600=(_599.indexOf("tl")!=-1); +var _601=(_599.indexOf("tr")!=-1); +if(_600&&_601){ return ""; } -if(_539){ +if(_600){ return "left"; } -if(_540){ +if(_601){ return "right"; } return ""; },_whichSideBottom:function(){ -var _541=this.options.corners; -if(this._hasString(_541,"all","bottom")){ +var _602=this.options.corners; +if(this._hasString(_602,"all","bottom")){ return ""; } -var _542=(_541.indexOf("bl")!=-1); -var _543=(_541.indexOf("br")!=-1); -if(_542&&_543){ +var _603=(_602.indexOf("bl")!=-1); +var _604=(_602.indexOf("br")!=-1); +if(_603&&_604){ return ""; } -if(_542){ +if(_603){ return "left"; } -if(_543){ +if(_604){ return "right"; } return ""; -},_borderColor:function(_544,_545){ -if(_544=="transparent"){ -return _545; +},_borderColor:function(_605,_606){ +if(_605=="transparent"){ +return _606; }else{ if(this.options.border){ return this.options.border; }else{ if(this.options.blend){ -return _545.blendedColor(_544); +return _606.blendedColor(_605); } } } return ""; -},_setMargin:function(el,n,_546){ -var _547=this._marginSize(n)+"px"; -var _548=(_546=="top"?this._whichSideTop():this._whichSideBottom()); -var _549=el.style; -if(_548=="left"){ -_549.marginLeft=_547; -_549.marginRight="0px"; +},_setMargin:function(el,n,_607){ +var _608=this._marginSize(n)+"px"; +var _609=(_607=="top"?this._whichSideTop():this._whichSideBottom()); +var _610=el.style; +if(_609=="left"){ +_610.marginLeft=_608; +_610.marginRight="0px"; }else{ -if(_548=="right"){ -_549.marginRight=_547; -_549.marginLeft="0px"; +if(_609=="right"){ +_610.marginRight=_608; +_610.marginLeft="0px"; }else{ -_549.marginLeft=_547; -_549.marginRight=_547; +_610.marginLeft=_608; +_610.marginRight=_608; } } -},_setBorder:function(el,n,_550){ -var _551=this._borderSize(n)+"px"; -var _552=(_550=="top"?this._whichSideTop():this._whichSideBottom()); -var _553=el.style; -if(_552=="left"){ -_553.borderLeftWidth=_551; -_553.borderRightWidth="0px"; +},_setBorder:function(el,n,_611){ +var _612=this._borderSize(n)+"px"; +var _613=(_611=="top"?this._whichSideTop():this._whichSideBottom()); +var _614=el.style; +if(_613=="left"){ +_614.borderLeftWidth=_612; +_614.borderRightWidth="0px"; }else{ -if(_552=="right"){ -_553.borderRightWidth=_551; -_553.borderLeftWidth="0px"; +if(_613=="right"){ +_614.borderRightWidth=_612; +_614.borderLeftWidth="0px"; }else{ -_553.borderLeftWidth=_551; -_553.borderRightWidth=_551; +_614.borderLeftWidth=_612; +_614.borderRightWidth=_612; } } },_marginSize:function(n){ @@ -3937,39 +4615,39 @@ if(o.compact&&o.blend){ } var o=this.options; if(o.compact&&o.blend){ -var _554=[1,0]; -return _554[n]; +var _615=[1,0]; +return _615[n]; }else{ if(o.compact){ -var _555=[2,1]; -return _555[n]; +var _616=[2,1]; +return _616[n]; }else{ if(o.blend){ -var _556=[3,2,1,0]; -return _556[n]; +var _617=[3,2,1,0]; +return _617[n]; }else{ -var _557=[5,3,2,1]; -return _557[n]; +var _618=[5,3,2,1]; +return _618[n]; } } } },_borderSize:function(n){ var o=this.options; -var _558; +var _619; if(o.compact&&(o.blend||this.isTransparent)){ return 1; }else{ if(o.compact){ -_558=[1,0]; +_619=[1,0]; }else{ if(o.blend){ -_558=[2,1,1,1]; +_619=[2,1,1,1]; }else{ if(o.border){ -_558=[0,2,0,0]; +_619=[0,2,0,0]; }else{ if(this.isTransparent){ -_558=[5,3,2,1]; +_619=[5,3,2,1]; }else{ return 0; } @@ -3977,7 +4655,7 @@ return 0; } } } -return _558[n]; +return _619[n]; },_hasString:function(str){ for(var i=1;i"+"<"+"/script"+">"; -document.write(tag); +document.write(""); } } })(); ============================================================ --- web.py 4c396c690078ecd159e98a016dd3c9de67d63f42 +++ web.py d5e776d5df9b8a3485fed19be37f647f538ebcdf @@ -1,8 +1,10 @@ #!/usr/bin/env python """web.py: makes web apps (http://webpy.org)""" -__version__ = "0.13" -__license__ = "Affero General Public License, Version 1" +__version__ = "0.1381" +__revision__ = "$Rev: 72 $" +__license__ = "public domain" __author__ = "Aaron Swartz " +__contributors__ = "see http://webpy.org/changes" from __future__ import generators @@ -12,24 +14,34 @@ from __future__ import generators # - unit tests? # todo: -# - add db select, delete function -# - fix that silly nonce stuff in web.update +# - get rid of upvars +# - break up into separate files # - provide an option to use .write() -# - add ip:port support # - allow people to do $self.id from inside a reparam # - add sqlite support -# - make storage a subclass of dictionary # - convert datetimes, floats in WebSafe # - locks around memoize # - fix memoize to use cacheify style techniques # - merge curval query with the insert # - figure out how to handle squid, etc. for web.ctx.ip -import os, os.path, sys, time, types, traceback +import os, os.path, sys, time, types, traceback, threading import cgi, re, urllib, urlparse, Cookie, pprint from threading import currentThread -try: import datetime -except ImportError: pass +from tokenize import tokenprog +iters = (list, tuple) +if hasattr(__builtins__, 'set') or ( + hasattr(__builtins__, 'has_key') and __builtins__.has_key('set')): + iters += (set,) +try: + from sets import Set + iters += (Set,) +except ImportError: + pass +try: + import datetime, itertools +except ImportError: + pass try: from Cheetah.Compiler import Compiler from Cheetah.Filters import Filter @@ -47,145 +59,341 @@ if not hasattr(traceback, 'format_exc'): if not hasattr(traceback, 'format_exc'): from cStringIO import StringIO def format_exc(limit=None): - s = StringIO() - traceback.print_exc(limit, s) - return s.getvalue() + strbuf = StringIO() + traceback.print_exc(limit, strbuf) + return strbuf.getvalue() traceback.format_exc = format_exc -## general utils +## General Utilities def _strips(direction, text, remove): if direction == 'l': - if text.startswith(remove): return text[len(remove):] + if text.startswith(remove): + return text[len(remove):] elif direction == 'r': - if text.endswith(remove): return text[:-len(remove)] + if text.endswith(remove): + return text[:-len(remove)] else: - raise "WrongDirection", "Needs to be r or l." + raise ValueError, "Direction needs to be r or l." return text -def rstrips(a, b): return _strips('r', a, b) -def lstrips(a, b): return _strips('l', a, b) -def strips(a, b): return rstrips(lstrips(a,b),b) +def rstrips(text, remove): + """removes the string `remove` from the right of `text`""" + return _strips('r', text, remove) -def autoassign(): - locals = sys._getframe(1).f_locals - self = locals['self'] - for (k, v) in locals.iteritems(): - if k == 'self': continue - setattr(self, k, v) +def lstrips(text, remove): + """removes the string `remove` from the left of `text`""" + return _strips('l', text, remove) -class Storage: - def __init__(self, initial=None): - if initial: - for k in initial.keys(): setattr(self, k, initial[k]) - - def __getattr__(self, k): - if hasattr(self.__dict__, k) or ( - k.startswith('__') and k.endswith('__')): # special keyword - return getattr(self.__dict__, k) - raise AttributeError, repr(k) - - def __repr__(self): return '' +def strips(text, remove): + """removes the string `remove` from the both sides of `text`""" + return rstrips(lstrips(text, remove), remove) +def autoassign(self, locals): + """ + Automatically assigns local variables to `self`. + Generally used in `__init__` methods, as in: + + def __init__(self, foo, bar, baz=1): autoassign(self, locals()) + """ + #locals = sys._getframe(1).f_locals + #self = locals['self'] + for (key, value) in locals.iteritems(): + if key == 'self': + continue + setattr(self, key, value) + +class Storage(dict): + """ + A Storage object is like a dictionary except `obj.foo` can be used + instead of `obj['foo']`. Create one by doing `storage({'a':1})`. + """ + def __getattr__(self, key): + if self.has_key(key): + return self[key] + raise AttributeError, repr(key) + def __setattr__(self, key, value): + self[key] = value + def __repr__(self): + return '' + storage = Storage -def storify(f, *requireds, **defaults): - stor = Storage() +def storify(mapping, *requireds, **defaults): + """ + Creates a `storage` object from dictionary `mapping`, raising `KeyError` if + d doesn't have all of the keys in `requireds` and using the default + values for keys found in `defaults`. - for k in requireds + tuple(f.keys()): - v = f[k] - if isinstance(k, list): v = v[-1] - if hasattr(v, 'value'): v = v.value - setattr(stor, k, v) + For example, `storify({'a':1, 'c':3}, b=2, c=0)` will return the equivalent of + `storage({'a':1, 'b':2, 'c':3})`. + + If a `storify` value is a list (e.g. multiple values in a form submission), + `storify` returns the last element of the list, unless the key appears in + `defaults` as a list. Thus: + + >>> storify({'a':[1, 2]}).a + 2 + >>> storify({'a':[1, 2]}, a=[]).a + [1, 2] + >>> storify({'a':1}, a=[]).a + [1] + >>> storify({}, a=[]).a + [] + + Similarly, if the value has a `value` attribute, `storify will return _its_ + value, unless the key appears in `defaults` as a dictionary. + + >>> storify({'a':storage(value=1)}).a + 1 + >>> storify({'a':storage(value=1)}, a={}).a + + >>> storify({}, a={}).a + {} + + """ + def getvalue(x): + if hasattr(x, 'value'): + return x.value + else: + return x + + stor = Storage() + for key in requireds + tuple(mapping.keys()): + value = mapping[key] + if isinstance(value, list): + if isinstance(defaults.get(key), list): + value = [getvalue(x) for x in value] + else: + value = value[-1] + if not isinstance(defaults.get(key), dict): + value = getvalue(value) + if isinstance(defaults.get(key), list) and not isinstance(value, list): + value = [value] + setattr(stor, key, value) - for (k,v) in defaults.iteritems(): - result = v - if hasattr(stor, k): result = stor[k] - if v == () and not isinstance(result, tuple): result = (result,) - setattr(stor, k, result) + for (key, value) in defaults.iteritems(): + result = value + if hasattr(stor, key): + result = stor[key] + if value == () and not isinstance(result, tuple): + result = (result,) + setattr(stor, key, result) return stor -class memoize: - def __init__(self, func): self.func = func; self.cache = {} - def __call__(self, *a, **k): - key = (a, tuple(k.items())) - if key not in self.cache: self.cache[key] = self.func(*a, **k) +class Memoize: + """ + 'Memoizes' a function, caching its return values for each input. + """ + def __init__(self, func): + self.func = func + self.cache = {} + def __call__(self, *args, **keywords): + key = (args, tuple(keywords.items())) + if key not in self.cache: + self.cache[key] = self.func(*args, **keywords) return self.cache[key] +memoize = Memoize re_compile = memoize(re.compile) #@@ threadsafe? +re_compile.__doc__ = """ +A memoized version of re.compile. +""" -class _re_subm_proxy: - def __init__(self): self.match = None - def __call__(self, match): self.match = match; return '' +class _re_subm_proxy: + def __init__(self): + self.match = None + def __call__(self, match): + self.match = match + return '' def re_subm(pat, repl, string): - """like re.sub, but returns the replacement and the match object""" - r = re_compile(pat) + """Like re.sub, but returns the replacement _and_ the match object.""" + compiled_pat = re_compile(pat) proxy = _re_subm_proxy() - r.sub(proxy.__call__, string) - return r.sub(repl, string), proxy.match + compiled_pat.sub(proxy.__call__, string) + return compiled_pat.sub(repl, string), proxy.match def group(seq, size): - """Breaks 'seq' into a generator of lists with length 'size'.""" - if not hasattr(seq, 'next'): seq = iter(seq) - while True: yield [seq.next() for i in xrange(size)] + """ + Returns an iterator over a series of lists of length size from iterable. -class iterbetter: - def __init__(self, iterator): self.i, self.c = iterator, 0 + For example, `list(group([1,2,3,4], 2))` returns `[[1,2],[3,4]]`. + """ + if not hasattr(seq, 'next'): + seq = iter(seq) + while True: + yield [seq.next() for i in xrange(size)] + +class IterBetter: + """ + Returns an object that can be used as an iterator + but can also be used via __getitem__ (although it + cannot go backwards -- that is, you cannot request + `iterbetter[0]` after requesting `iterbetter[1]`). + """ + def __init__(self, iterator): + self.i, self.c = iterator, 0 def __iter__(self): - while 1: yield self.i.next(); self.c += 1 + while 1: + yield self.i.next() + self.c += 1 def __getitem__(self, i): #todo: slices - if i > self.c: raise KeyError, "already passed "+str(i) + if i > self.c: + raise IndexError, "already passed "+str(i) try: - while i < self.c: self.i.next(); self.c += 1 + while i < self.c: + self.i.next() + self.c += 1 # now self.c == i - self.c += 1; return self.i.next() - except StopIteration: raise KeyError, repr(i) + self.c += 1 + return self.i.next() + except StopIteration: + raise IndexError, str(i) +iterbetter = IterBetter -def dictfind(d, elt): - for (k,v) in d.iteritems(): - if elt is v: return k +def dictreverse(mapping): + """Takes a dictionary like `{1:2, 3:4}` and returns `{2:1, 4:3}`.""" + return dict([(value, key) for (key, value) in mapping.iteritems()]) -def dictincr(d, e): - d.setdefault(e, 0) - d[e] += 1 - return d[e] +def dictfind(dictionary, element): + """ + Returns a key whose value in `dictionary` is `element` + or, if none exists, None. + """ + for (key, value) in dictionary.iteritems(): + if element is value: + return key -def dictadd(a, b): +def dictfindall(dictionary, element): + """ + Returns the keys whose values in `dictionary` are `element` + or, if none exists, []. + """ + res = [] + for (key, value) in dictionary.iteritems(): + if element is value: + res.append(key) + return res + +def dictincr(dictionary, element): + """ + Increments `element` in `dictionary`, + setting it to one if it doesn't exist. + """ + dictionary.setdefault(element, 0) + dictionary[element] += 1 + return dictionary[element] + +def dictadd(dict_a, dict_b): + """ + Returns a dictionary consisting of the keys in `a` and `b`. + If they share a key, the value from b is used. + """ result = {} - result.update(a) - result.update(b) + result.update(dict_a) + result.update(dict_b) return result sumdicts = dictadd # deprecated -def listget(l, n, v=None): - if len(l)-1 < n: return v - return l[n] +def listget(lst, ind, default=None): + """Returns `lst[ind]` if it exists, `default` otherwise.""" + if len(lst)-1 < ind: + return default + return lst[ind] -def upvars(n=2): +def intget(integer, default=None): + """Returns `integer` as an int or `default` if it can't.""" + try: + return int(integer) + except (TypeError, ValueError): + return default + +def datestr(then, now=None): + """Converts a (UTC) datetime object to a nice string representation.""" + def agohence(n, what, divisor=None): + if divisor: n = n // divisor + + out = str(abs(n)) + ' ' + what # '2 day' + if abs(n) != 1: out += 's' # '2 days' + out += ' ' # '2 days ' + if n < 0: + out += 'from now' + else: + out += 'ago' + return out # '2 days ago' + + oneday = 24 * 60 * 60 + + if not now: now = datetime.datetime.utcnow() + delta = now - then + deltaseconds = int(delta.days * oneday + delta.seconds + delta.microseconds * 1e-06) + deltadays = abs(deltaseconds) // oneday + if deltaseconds < 0: deltadays *= -1 # fix for oddity of floor + + if deltadays: + if abs(deltadays) < 4: + return agohence(deltadays, 'day') + + out = then.strftime('%B %e') # e.g. 'June 13' + if then.year != now.year or deltadays < 0: + out += ', %s' % then.year + return out + + if int(deltaseconds): + if abs(deltaseconds) > (60 * 60): + return agohence(deltaseconds, 'hour', 60 * 60) + elif abs(deltaseconds) > 60: + return agohence(deltaseconds, 'minute', 60) + else: + return agohence(deltaseconds, 'second') + + deltamicroseconds = delta.microseconds + if delta.days: deltamicroseconds = int(delta.microseconds - 1e6) # datetime oddity + if abs(deltamicroseconds) > 1000: + return agohence(deltamicroseconds, 'millisecond', 1000) + + return agohence(deltamicroseconds, 'microsecond') + +def upvars(level=2): + """Guido van Rossum doesn't want you to use this function.""" return dictadd( - sys._getframe(n).f_globals, - sys._getframe(n).f_locals) + sys._getframe(level).f_globals, + sys._getframe(level).f_locals) -class capturestdout: - def __init__(self, func): self.func = func - def __call__(self, *args, **kw): +class CaptureStdout: + """ + Captures everything func prints to stdout and returns it instead. + + **WARNING:** Not threadsafe! + """ + def __init__(self, func): + self.func = func + def __call__(self, *args, **keywords): from cStringIO import StringIO # Not threadsafe! out = StringIO() oldstdout = sys.stdout sys.stdout = out - try: self.func(*args, **kw) - finally: sys.stdout = oldstdout + try: + self.func(*args, **keywords) + finally: + sys.stdout = oldstdout return out.getvalue() +capturestdout = CaptureStdout -class profile: - def __init__(self, func): self.func = func - def __call__(self, *args, **kw): - import hotshot, hotshot.stats, tempfile, time +class Profile: + """ + Profiles `func` and returns a tuple containing its output + and a string with human-readable profiling information. + """ + def __init__(self, func): + self.func = func + def __call__(self, *args): ##, **kw): kw unused + import hotshot, hotshot.stats, tempfile ##, time already imported temp = tempfile.NamedTemporaryFile() prof = hotshot.Profile(temp.name) @@ -201,51 +409,153 @@ class profile: x += capturestdout(stats.print_stats)(40) x += capturestdout(stats.print_callers)() return result, x +profile = Profile -def tryall(context): +def tryall(context, prefix=None): + """ + Tries a series of functions and prints their results. + `context` is a dictionary mapping names to values; + the value will only be tried if it's callable. + + For example, you might have a file `test/stuff.py` + with a series of functions testing various things in it. + At the bottom, have a line: + + if __name__ == "__main__": tryall(globals()) + + Then you can run `python test/stuff.py` and get the results of + all the tests. + """ context = context.copy() # vars() would update results = {} - for (k, v) in context.iteritems(): - if not hasattr(v, '__call__'): continue - print k+':', + for (key, value) in context.iteritems(): + if not hasattr(value, '__call__'): + continue + if prefix and not key.startswith(prefix): + continue + print key + ':', try: - r = v() + r = value() dictincr(results, r) print r except: print 'ERROR' dictincr(results, 'ERROR') - print ' '+'\n '.join(traceback.format_exc().split('\n')) + print ' ' + '\n '.join(traceback.format_exc().split('\n')) print '-'*40 print 'results:' - for (k, v) in results.iteritems(): - print ' '*2, str(k)+':', v + for (key, value) in results.iteritems(): + print ' '*2, str(key)+':', value -class threadeddict: - def __init__(self, d): self.__dict__['_threadeddict__d'] = d - def __getattr__(self, a): return getattr(self.__d[currentThread()], a) - def __getitem__(self, i): return self.__d[currentThread()][i] - def __setattr__(self, a, v): return setattr(self.__d[currentThread()], a, v) - def __setitem__(self, i, v): self.__d[currentThread()][i] = v - def __hash__(self): return hash(self.__d[currentThread()]) +class ThreadedDict: + """ + Takes a dictionary that maps threads to objects. + When a thread tries to get or set an attribute or item + of the threadeddict, it passes it on to the object + for that thread in dictionary. + """ + def __init__(self, dictionary): + self.__dict__['_ThreadedDict__d'] = dictionary + def __getattr__(self, attr): + return getattr(self.__d[currentThread()], attr) + def __getitem__(self, item): + return self.__d[currentThread()][item] + def __setattr__(self, attr, value): + if attr == '__doc__': + self.__dict__[attr] = value + else: + return setattr(self.__d[currentThread()], attr, value) + def __setitem__(self, item, value): + self.__d[currentThread()][item] = value + def __hash__(self): + return hash(self.__d[currentThread()]) +threadeddict = ThreadedDict -## url utils +## IP Utilities -def base(base=''): #when would you use a default base? - url = context.path.lstrip('/') - for i in xrange(url.count('/')): base += '../' - if not base: base = './' +def validipaddr(address): + """returns True if `address` is a valid IPv4 address""" + try: + octets = address.split('.') + assert len(octets) == 4 + for x in octets: + assert 0 <= int(x) <= 255 + except (AssertionError, ValueError): + return False + return True + +def validipport(port): + """returns True if `port` is a valid IPv4 port""" + try: + assert 0 <= int(port) <= 65535 + except (AssertionError, ValueError): + return False + return True + +def validip(ip, defaultaddr="0.0.0.0", defaultport=8080): + """returns `(ip_address, port)` from string `ip_addr_port`""" + addr = defaultaddr + port = defaultport + + ip = ip.split(":", 1) + if len(ip) == 1: + if not ip[0]: + pass + elif validipaddr(ip[0]): + addr = ip[0] + elif validipport(ip[0]): + port = int(ip[0]) + else: + raise ValueError, ':'.join(ip) + ' is not a valid IP address/port' + elif len(ip) == 2: + addr, port = ip + if not validipaddr(addr) and validipport(port): + raise ValueError, ':'.join(ip) + ' is not a valid IP address/port' + port = int(port) + else: + raise ValueError, ':'.join(ip) + ' is not a valid IP address/port' + return (addr, port) + +def validaddr(string_): + """returns either (ip_address, port) or "/path/to/socket" from string_""" + if '/' in string_: + return string_ + else: + return validip(string_) + +## URL Utilities + +def prefixurl(base=''): + """ + Sorry, this function is really difficult to explain. + Maybe some other time. + """ + url = ctx.path.lstrip('/') + for i in xrange(url.count('/')): + base += '../' + if not base: + base = './' return base -## formatting +def urlquote(x): return urllib.quote(websafe(x).encode('utf-8')) +## Formatting + try: from markdown import markdown # http://webpy.org/markdown.py -except ImportError: pass +except ImportError: + pass r_url = re_compile('(? + (cf. below for license) + """ + def __init__(self, text, pos): + ValueError.__init__(self) + self.text = text + self.pos = pos + def __str__(self): + return "unfinished expression in %s at char %d" % ( + repr(self.text), self.pos) + +def _interpolate(format): + """ + Takes a format string and returns a list of 2-tuples of the form + (boolean, string) where boolean says whether string should be evaled + or not. + from (public domain, Ka-Ping Yee) + """ + def matchorfail(text, pos): + match = tokenprog.match(text, pos) + if match is None: + raise _ItplError(text, pos) + return match, match.end() + + namechars = "abcdefghijklmnopqrstuvwxyz" \ + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; + chunks = [] + pos = 0 + + while 1: + dollar = format.find("$", pos) + if dollar < 0: + break + nextchar = format[dollar + 1] + + if nextchar == "{": + chunks.append((0, format[pos:dollar])) + pos, level = dollar + 2, 1 + while level: + match, pos = matchorfail(format, pos) + tstart, tend = match.regs[3] + token = format[tstart:tend] + if token == "{": + level = level + 1 + elif token == "}": + level = level - 1 + chunks.append((1, format[dollar + 2:pos - 1])) + + elif nextchar in namechars: + chunks.append((0, format[pos:dollar])) + match, pos = matchorfail(format, dollar + 1) + while pos < len(format): + if format[pos] == "." and \ + pos + 1 < len(format) and format[pos + 1] in namechars: + match, pos = matchorfail(format, pos + 1) + elif format[pos] in "([": + pos, level = pos + 1, 1 + while level: + match, pos = matchorfail(format, pos) + tstart, tend = match.regs[3] + token = format[tstart:tend] + if token[0] in "([": + level = level + 1 + elif token[0] in ")]": + level = level - 1 + else: + break + chunks.append((1, format[dollar + 1:pos])) + + else: + chunks.append((0, format[pos:dollar + 1])) + pos = dollar + 1 + (nextchar == "$") + + if pos < len(format): + chunks.append((0, format[pos:])) + return chunks + +def sqlors(left, lst): + """ + `left is a SQL clause like `tablename.arg = ` + and `lst` is a list of values. Returns a reparam-style + pair featuring the SQL that ORs together the clause + for each item in the lst. + + For example: + + web.sqlors('foo =', [1,2,3]) + + would result in: + + foo = 1 OR foo = 2 OR foo = 3 + """ + if isinstance(lst, iters): + lst = list(lst) + ln = len(lst) + if ln == 0: + return ("2+2=5", []) + if ln == 1: + lst = lst[0] + + if isinstance(lst, iters): + return '(' + left + \ + (' OR ' + left).join([aparam() for param in lst]) + ")", lst + else: + return left + aparam(), [lst] + +class UnknownParamstyle(Exception): + """raised for unsupported db paramstyles + + Currently supported: qmark,numeric, format, pyformat + """ + pass + def aparam(): - p = ctx.db_module.paramstyle - if p == 'qmark': + """Use in a SQL string to make a spot for a db value.""" + style = ctx.db_module.paramstyle + if style == 'qmark': return '?' - elif p == 'numeric': + elif style == 'numeric': return ':1' - elif p == 'format': + elif style in ['format', 'pyformat']: return '%s' - elif p == 'pyformat': - return '%s' - raise UnknownParamstyle, p + raise UnknownParamstyle, style -class UnknownDB(Exception): pass -def connect(dbn, **kw): +def reparam(string_, dictionary): + """ + Takes a string and a dictionary and interpolates the string + using values from the dictionary. Returns a 2-tuple containing + the a string with `aparam()`s in it and a list of the matching values. + + You can pass this sort of thing as a clause in any db function. + Otherwise, you can pass a dictionary to the keyword argument `vars` + and the function will call reparam for you. + """ + vals = [] + result = [] + for live, chunk in _interpolate(string_): + if live: + result.append(aparam()) + vals.append(eval(chunk, dictionary)) + else: result.append(chunk) + return ''.join(result), vals + +class UnknownDB(Exception): + """raised for unsupported dbms""" + pass +def connect(dbn, **keywords): + """ + Connects to the specified database. + db currently must be "postgres" or "mysql". + If DBUtils is installed, connection pooling will be used. + """ if dbn == "postgres": - try: import psycopg2 as db + try: + import psycopg2 as db except ImportError: - try: import psycopg as db - except ImportError: import pgdb as db - kw['password'] = kw['pw'] - del kw['pw'] - kw['database'] = kw['db'] - del kw['db'] + try: + import psycopg as db + except ImportError: + import pgdb as db + keywords['password'] = keywords['pw'] + del keywords['pw'] + keywords['database'] = keywords['db'] + del keywords['db'] elif dbn == "mysql": import MySQLdb as db - kw['passwd'] = kw['pw'] - del kw['pw'] + keywords['passwd'] = keywords['pw'] + del keywords['pw'] db.paramstyle = 'pyformat' # it's both, like psycopg - else: raise UnknownDB, dbn + elif dbn == "sqlite": + try: ## try first sqlite3 version + from pysqlite2 import dbapi2 as db + db.paramstyle = 'qmark' + except ImportError: ## else try sqlite2 + import sqlite as db + keywords['database'] = keywords['db'] + del keywords['db'] + else: + raise UnknownDB, dbn ctx.db_name = dbn ctx.db_module = db ctx.db_transaction = False if _hasPooling: - if 'db' not in globals(): globals()['db'] = PooledDB(dbapi=db, **kw) + if 'db' not in globals(): + globals()['db'] = PooledDB(dbapi=db, **keywords) ctx.db = globals()['db'].connection() else: - ctx.db = db.connect(**kw) + ctx.db = db.connect(**keywords) ctx.dbq_count = 0 if globals().get('db_printing'): - def db_execute(cur, q, d=None): + def db_execute(cur, sql_query, d=None): + """executes an sql query""" + + def sqlquote(obj): + """converts `obj` to its proper SQL version""" + + # because `1 == True and hash(1) == hash(True)` + # we have to do this the hard way... + + if obj is None: + return 'NULL' + elif obj is True: + return "'t'" + elif obj is False: + return "'f'" + elif isinstance(obj, datetime.datetime): + return repr(obj.isoformat()) + else: + return repr(obj) + ctx.dbq_count += 1 - try: outq = q % d - except: outq = q - print>>debug, str(ctx.dbq_count)+':', outq + try: + outq = sql_query % tuple(map(sqlquote, d)) + except TypeError: + outq = sql_query + print >> debug, str(ctx.dbq_count)+':', outq a = time.time() - out = cur.execute(q, d) + out = cur.execute(sql_query, d) b = time.time() - print>>debug, '(%s)' % round(b-a, 2) + print >> debug, '(%s)' % round(b - a, 2) return out ctx.db_execute = db_execute else: - ctx.db_execute = lambda cur, q, d=None: cur.execute(q, d) + ctx.db_execute = lambda cur, sql_query, d=None: \ + cur.execute(sql_query, d) return ctx.db def transact(): @@ -326,103 +802,226 @@ def commit(): ctx.db_transaction = True def commit(): + """Commits a transaction.""" ctx.db.commit() ctx.db_transaction = False def rollback(): + """Rolls back a transaction.""" ctx.db.rollback() - ctx.db_transaction = False + ctx.db_transaction = False -def query(q, v=None): - d = ctx.db.cursor() - if v is None: v = upvars() +def query(sql_query, vars=None, processed=False): + """ + Execute SQL query `sql_query` using dictionary `vars` to interpolate it. + If `processed=True`, `vars` is a `reparam`-style list to use + instead of interpolating. + """ + if vars is None: + vars = {} + db_cursor = ctx.db.cursor() - ctx.db_execute(d, reparam(q), v) - if d.description: - names = [x[0] for x in d.description] + if not processed: + sql_query, vars = reparam(sql_query, vars) + ctx.db_execute(db_cursor, sql_query, vars) + if db_cursor.description: + names = [x[0] for x in db_cursor.description] def iterwrapper(): - x = d.fetchone() - while x: - yield Storage(dict(zip(names, x))) - x = d.fetchone() + row = db_cursor.fetchone() + while row: + yield Storage(dict(zip(names, row))) + row = db_cursor.fetchone() out = iterbetter(iterwrapper()) - out.__len__ = lambda: d.rowcount + out.__len__ = lambda: int(db_cursor.rowcount) + out.list = lambda: [Storage(dict(zip(names, x))) \ + for x in db_cursor.fetchall()] else: - out = None - out = d.rowcount + out = db_cursor.rowcount - if not ctx.db_transaction: ctx.db.commit() + if not ctx.db_transaction: + ctx.db.commit() return out -def select(tablename, what='*', where=None, vars=None, **wheres): - if vars is None: vars = upvars() +def sqllist(lst): + """ + If a list, converts it to a comma-separated string. + Otherwise, returns the string. + """ + if isinstance(lst, str): + return lst + else: return ', '.join(lst) + +def sqlwhere(dictionary): + """ + Converts a `dictionary` to an SQL WHERE clause in + `reparam` format. Thus, - q = "SELECT "+what+" FROM "+tablename+" WHERE " - if where: q += where - for (k, v) in wheres.iteritems(): - where += k + '=' + nonce(v, vars) - return query(q, vvars) + {'cust_id': 2, 'order_id':3} + + would result in the equivalent of: + + 'cust_id = 2 AND order_id = 3' + + but properly quoted. + """ + + return ' AND '.join([ + '%s = %s' % (k, aparam()) for k in dictionary.keys() + ]), dictionary.values() +def select(tables, vars=None, what='*', where=None, order=None, group=None, + limit=None, offset=None): + """ + Selects `what` from `tables` with clauses `where`, `order`, + `group`, `limit`, and `offset. Uses vars to interpolate. + Otherwise, each clause can take a reparam-style list. + """ + if vars is None: + vars = {} + values = [] + qout = "" + + for (sql, val) in ( + ('SELECT', what), + ('FROM', sqllist(tables)), + ('WHERE', where), + ('GROUP BY', group), + ('ORDER BY', order), + ('LIMIT', limit), + ('OFFSET', offset)): + if isinstance(val, (int, long)): + if sql == 'WHERE': + nquery, nvalue = 'id = '+aparam(), [val] + else: + nquery, nvalue = str(val), () + elif isinstance(val, (list, tuple)) and len(val) == 2: + nquery, nvalue = val + elif val: + nquery, nvalue = reparam(val, vars) + else: + continue + qout += " " + sql + " " + nquery + values.extend(nvalue) + return query(qout, values, processed=True) + def insert(tablename, seqname=None, **values): - d = ctx.db.cursor() + """ + Inserts `values` into `tablename`. Returns current sequence ID. + Set `seqname` to the ID if it's not the default, or to `False` + if there isn't one. + """ + db_cursor = ctx.db.cursor() if values: - ctx.db_execute(d, "INSERT INTO %s (%s) VALUES (%s)" % ( + sql_query, v = "INSERT INTO %s (%s) VALUES (%s)" % ( tablename, ", ".join(values.keys()), - ', '.join([aparam() for x in values]) #@@ use nonce - ), values.values()) + ', '.join([aparam() for x in values]) + ), values.values() else: - ctx.db_execute(d, "INSERT INTO %s DEFAULT VALUES" % tablename) + sql_query, v = "INSERT INTO %s DEFAULT VALUES" % tablename, None - if ctx.db_name == "postgres" and seqname != False: - if seqname is None: seqname = tablename + "_id_seq" - ctx.db_execute(d, "SELECT currval('%s')" % seqname) - out = d.fetchone()[0] + if seqname is False: + pass + elif ctx.db_name == "postgres": + if seqname is None: + seqname = tablename + "_id_seq" + sql_query += "; SELECT currval('%s')" % seqname elif ctx.db_name == "mysql": - ctx.db_execute(d, "SELECT last_insert_id()") - out = d.fetchone()[0] + ctx.db_execute(db_cursor, sql_query, v) + sql_query = "SELECT last_insert_id()" + v = () elif ctx.db_name == "sqlite": + ctx.db_execute(db_cursor, sql_query, v) # not really the same... - ctx.db_execute(d, "SELECT last_insert_rowid()") - out = d.fetchone()[0] - else: + sql_query = "SELECT last_insert_rowid()" + v = () + + ctx.db_execute(db_cursor, sql_query, v) + try: + out = db_cursor.fetchone()[0] + except Exception: out = None - if not ctx.db_transaction: ctx.db.commit() + if not ctx.db_transaction: + ctx.db.commit() + return out -def update(tablename, where, pvars=(), **values): - pvars = list(pvars) - if isinstance(where, int): - pvars.append(where) - where = "id = "+aparam() +def update(tables, where, vars=None, **values): + """ + Update `tables` with clause `where` (interpolated using `vars`) + and setting `values`. + """ + if vars is None: + vars = {} + if isinstance(where, (int, long)): + vars = [where] + where = "id = " + aparam() + elif isinstance(where, (list, tuple)) and len(where) == 2: + where, vars = where else: - where = where #@@ need to figure out positional params + where, vars = reparam(where, vars) - d = ctx.db.cursor() - ctx.db_execute(d, "UPDATE %s SET %s WHERE %s" % ( - tablename, - ', '.join([k+'='+aparam() for k in values.keys()]), + db_cursor = ctx.db.cursor() + ctx.db_execute(db_cursor, "UPDATE %s SET %s WHERE %s" % ( + sqllist(tables), + ', '.join([k + '=' + aparam() for k in values.keys()]), where), - values.values()+pvars) + values.values() + vars) - if not ctx.db_transaction: ctx.db.commit() - return d.rowcount + if not ctx.db_transaction: + ctx.db.commit() + return db_cursor.rowcount -## request handlers +def delete(table, where, using=None, vars=None): + """ + Deletes from `table` with clauses `where` and `using`. + """ + if vars is None: + vars = {} + db_cursor = ctx.db.cursor() + if isinstance(where, (int, long)): + vars = [where] + where = "id = " + aparam() + elif isinstance(where, (list, tuple)) and len(where) == 2: + where, vars = where + else: + where, vars = reparam(where, vars) + q = 'DELETE FROM %s WHERE %s' % (table, where) + if using: + q += ' USING ' + sqllist(using) + ctx.db_execute(db_cursor, q, vars) + + if not ctx.db_transaction: + ctx.db.commit() + return db_cursor.rowcount + +## Request Handlers + def handle(mapping, fvars=None): + """ + Call the appropriate function based on the url to function mapping in `mapping`. + If no module for the function is specified, look up the function in `fvars`. If + `fvars` is empty, using the caller's context. + + `mapping` should be a tuple of paired regular expressions with function name + substitutions. `handle` will import modules as necessary. + """ for url, ofno in group(mapping, 2): - if isinstance(ofno, tuple): ofn, fna = ofno[0], list(ofno[1:]) - else: ofn, fna = ofno, [] - fn, result = re_subm('^'+url+'$', ofn, context.path) + if isinstance(ofno, tuple): + ofn, fna = ofno[0], list(ofno[1:]) + else: + ofn, fna = ofno, [] + fn, result = re_subm('^' + url + '$', ofn, ctx.path) if result: # it's a match if fn.split(' ', 1)[0] == "redirect": url = fn.split(' ', 1)[1] - if context.method == "GET": - x = context.environ.get('QUERY_STRING', '') - if x: url += '?'+x + if ctx.method == "GET": + x = ctx.env.get('QUERY_STRING', '') + if x: + url += '?' + x return redirect(url) elif '.' in fn: x = fn.split('.') @@ -432,74 +1031,211 @@ def handle(mapping, fvars=None): else: cls = fn mod = fvars or upvars() - if isinstance(mod, types.ModuleType): mod = vars(mod) - try: cls = mod[cls] - except KeyError: return notfound() + if isinstance(mod, types.ModuleType): + mod = vars(mod) + try: + cls = mod[cls] + except KeyError: + return notfound() - meth = context.method + meth = ctx.method if meth == "HEAD": - if not hasattr(cls, meth): meth = "GET" - if not hasattr(cls, meth): return nomethod(cls) + if not hasattr(cls, meth): + meth = "GET" + if not hasattr(cls, meth): + return nomethod(cls) tocall = getattr(cls(), meth) args = list(result.groups()) for d in re.findall(r'\\(\d+)', ofn): - args.pop(int(d)-1) - return tocall(*([urllib.unquote(x) for x in args]+fna)) + args.pop(int(d) - 1) + return tocall(*([urllib.unquote(x) for x in args] + fna)) return notfound() def autodelegate(prefix=''): + """ + Returns a method that takes one argument and calls the method named prefix+arg, + calling `notfound()` if there isn't one. Example: + + urls = ('/prefs/(.*)', 'prefs') + + class prefs: + GET = autodelegate('GET_') + def GET_password(self): pass + def GET_privacy(self): pass + + `GET_password` would get called for `/prefs/password` while `GET_privacy` for + `GET_privacy` gets called for `/prefs/privacy`. + + If a user visits `/prefs/password/change` then `GET_password(self, '/change')` + is called. + """ def internal(self, arg): - func = prefix+arg - if hasattr(self, func): return getattr(self, func)() - else: return notfound() + if '/' in arg: + first, rest = arg.split('/', 1) + func = prefix + first + args = ['/' + rest] + else: + func = prefix + arg + args = [] + + if hasattr(self, func): + try: + return getattr(self, func)(*args) + except TypeError: + return notfound() + else: + return notfound() return internal -## http defaults +def background(func): + """A function decorator to run a long-running function as a background thread.""" + def internal(*a, **kw): + data() # cache it + ctx = _context[currentThread()] + _context[currentThread()] = storage(ctx.copy()) + + def newfunc(): + _context[currentThread()] = ctx + func(*a, **kw) + + t = threading.Thread(target=newfunc) + background.threaddb[id(t)] = t + t.start() + ctx.headers = [] + return seeother(changequery(_t=id(t))) + return internal +background.threaddb = {} + +def backgrounder(func): + def internal(*a, **kw): + i = input(_method='get') + if '_t' in i: + try: + t = background.threaddb[int(i._t)] + except KeyError: + return notfound() + _context[currentThread()] = _context[t] + return + else: + return func(*a, **kw) + return internal + +## HTTP Functions + +def httpdate(date_obj): + """Formats a datetime object for use in HTTP headers.""" + return date_obj.strftime("%a, %d %b %Y %H:%M:%S GMT") + +def parsehttpdate(string_): + """Parses an HTTP date into a datetime object.""" + try: + t = time.strptime(string_, "%a, %d %b %Y %H:%M:%S %Z") + except ValueError: + return None + return datetime.datetime(*t[:6]) + +def expires(delta): + """ + Outputs an `Expires` header for `delta` from now. + `delta` is a `timedelta` object or a number of seconds. + """ + try: + datetime + except NameError: + raise Exception, "requires Python 2.3 or later" + if isinstance(delta, (int, long)): + delta = datetime.timedelta(seconds=delta) + date_obj = datetime.datetime.utcnow() + delta + header('Expires', httpdate(date_obj)) + +def lastmodified(date_obj): + """Outputs a `Last-Modified` header for `datetime`.""" + header('Last-Modified', httpdate(date_obj)) + +def modified(date=None, etag=None): + n = ctx.env.get('HTTP_IF_NONE_MATCH') + m = parsehttpdate(ctx.env.get('HTTP_IF_MODIFIED_SINCE', '').split(';')[0]) + validate = False + if etag: + raise NotImplementedError, "no etag support yet" + # should really be a warning + if date and m: + # we subtract a second because + # HTTP dates don't have sub-second precision + if date-datetime.timedelta(seconds=1) <= m: + validate = True + if validate: ctx.status = '304 Not Modified' + return not validate + +""" +By default, these all return simple error messages that send very short messages +(like "bad request") to the user. They can and should be overridden +to return nicer ones. +""" def redirect(url, status='301 Moved Permanently'): - newloc = urlparse.urljoin(context.home + context.path, url) - context.status = status + """ + Returns a `status` redirect to the new URL. + `url` is joined with the base URL so that things like + `redirect("about") will work properly. + """ + newloc = urlparse.urljoin(ctx.home + ctx.path, url) + ctx.status = status + ctx.output = '' header('Content-Type', 'text/html') header('Location', newloc) # seems to add a three-second delay for some reason: # output('moved permanently') -def found(url): return redirect(url, '302 Found') -def seeother(url): return redirect(url, '303 See Other') -def tempredirect(url): return redirect(url, '307 Temporary Redirect') +def found(url): + """A `302 Found` redirect.""" + return redirect(url, '302 Found') +def seeother(url): + """A `303 See Other` redirect.""" + return redirect(url, '303 See Other') + +def tempredirect(url): + """A `307 Temporary Redirect` redirect.""" + return redirect(url, '307 Temporary Redirect') + def badrequest(): - context.status = '400 Bad Request' + """Return a `400 Bad Request` error.""" + ctx.status = '400 Bad Request' header('Content-Type', 'text/html') return output('bad request') def notfound(): - context.status = '404 Not Found' + """Returns a `404 Not Found` error.""" + ctx.status = '404 Not Found' header('Content-Type', 'text/html') return output('not found') def nomethod(cls): - context.status = '405 Method Not Allowed' + """Returns a `405 Method Not Allowed` error for `cls`.""" + ctx.status = '405 Method Not Allowed' header('Content-Type', 'text/html') - header("Allow", ', '.join([x for x in ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'] if hasattr(cls, x)])) - return output('method not allowed') + header('Allow', \ + ', '.join([method for method in \ + ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'] \ + if hasattr(cls, method)])) + + # commented out for the same reason redirect is + # return output('method not allowed') def gone(): - context.status = '410 Gone' + """Returns a `410 Gone` error.""" + ctx.status = '410 Gone' header('Content-Type', 'text/html') return output("gone") -def expires(delta): - try: datetime - except NameError: raise Exception, "this function requires at least python2.3" - if isinstance(delta, (int, long)): - delta = datetime.timedelta(seconds=delta) - o = datetime.datetime.utcnow() + delta - header('Expires', o.strftime("%a, %d %b %Y %T GMT")) +def internalerror(): + """Returns a `500 Internal Server` error.""" + ctx.status = "500 Internal Server Error" + ctx.headers = [('Content-Type', 'text/html')] + ctx.output = "internal server error" -def lastmodified(d): - header('Last-Modified', d.strftime("%a, %d %b %Y %T GMT")) # adapted from Django # Copyright (c) 2005, the Lawrence Journal-World @@ -512,7 +1248,7 @@ DJANGO_500_PAGE = """#import inspect - $exception_type at $context.path + $exception_type at $ctx.path