repo
string
commit
string
message
string
diff
string
schuyler1d/cbook
c1fe0eb76360053d6fc607e0a0652b0126d13bfc
got something actually working. but unicrap seems broken
diff --git a/client/index.html b/client/index.html index 3800b64..6196ec2 100644 --- a/client/index.html +++ b/client/index.html @@ -1,205 +1,205 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <span id="decrypt_output"></span> - <form id="encode" class="sec" onsubmit="return false;"> + <form id="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> - <button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button> + <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="hide"> Share this link with all your friends. <a id="keylink" class="hide" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> </div> <a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/base.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); - var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101); + var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } - if (/encode/.test(document.location.hash)) { - document.forms['encode'].elements['txt'].focus(); - document.forms['encode'].elements['compress'].checked = ( + if (/encrypt/.test(document.location.hash)) { + document.forms['encrypt'].elements['txt'].focus(); + document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect(document.getElementById('friendkey')); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/base.js b/client/js/base.js index 6440e28..6f7f1e3 100644 --- a/client/js/base.js +++ b/client/js/base.js @@ -1,243 +1,257 @@ var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?', regex_args = ['codec','hash','iv','ciphtext'], html_regex = '<([:\\w]+)[^<]+'; var crypted_regex = new RegExp(crypted_regex_str,'g'); /* facebook: document.getElementsByClassName('uiStreamMessage') twitter: //document.activeElement to know which element has focus 15chars for IV 1char for addition 4chars for ♔.☿ (could make it 3) 'http://skyb.us/' == 15 chars 140=15+1+4+15+105 */ var global= { - encrypt_key:"99add3674eea0f3a84201b8f65017114", - encrypt_iv:"80a5c7ce51fbeb81a9bad0f44112c17408eb46b172fec9b118bfa6dd2a2772fe", - mode:0,//0:OFB,1:CFB,2:CBC - keysize:16//32 for 256, 24 for 192, 16 for 128 + FAIL_ENCODING:'Failed to decrypt message, likely due to encoding problems.<br />', + FAIL_NOKEY:'None of your saved keys could decrypt this message.<br />' } -function cryptArgs(iv) { +function cryptArgs(iv, encrypt_key_numbers) { ///see http://www.josh-davis.org/ecmascrypt ///NOTE:if CBC, then we need to save the msgsize var mode = 0; //0:OFB,1:CFB,2:CBC var keysize = 16; //32 for 256, 24 for 192, 16 for 128 - var hexkey = global.encrypt_key; - var iv = iv||global.encrypt_iv; - return [mode,ecmaScrypt.toNumbers(hexkey),keysize,iv]; + encrypt_key_numbers = encrypt_key_numbers || ecmaScrypt.toNumbers(global.encrypt_key); + return [mode, encrypt_key_numbers, keysize, iv]; } var U2N = new (function() { /* we'll need to get a lot smarter. we should be accepting/creating unicode characters within the character range that HTML considers 'character' text. http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets parseInt('10FFFF',16) - parseInt('10000',16) == 1048575 1114111 - 65536 == String.fromCharCode(85267) seems to be 'real' first character */ this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars this.compress = function(low_unicode) { var arr = []; var c = low_unicode.length; while (c--) { arr.unshift(low_unicode.charCodeAt(c)); } return this.unicode(arr); } this.decompress = function(high_unicode) { var nums = this.nums(high_unicode); var str = ''; for (var i=0;i<nums.length;i++) { str += String.fromCharCode(nums[i]); } return str; } this.lowcoding = function(cipher) { var outhex = ''; for(var i = 0;i < cipher.length;i++) { outhex += ecmaScrypt.toHex(cipher.charCodeAt(i)); } return outhex; } this.unicode = function(nums) { ///take nums array of numbers from 0-255 var u_string=''; for (var i=0;i<nums.length;i++) { var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) ); if (n>65535) { ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes throw Error('cannot deal with high chars yet'); } if (n>2299099) { throw Error('cannot deal with high unicode compression yet'); //but I think the answer is that we'll have some marker //for NON-encoded text and then // } ///random suspects: if (n==1759 || n==130) { throw Error('random suspect--not sure it is culprit'); } if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes'); //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n); } if (8192 < n && n < 8447) { //255 chars ///http://en.wikipedia.org/wiki/Unicode_control_characters ///seem to be grouped all in the 2000 -20FF range throw Error('Wide fence for control chars. we can be more picky'+n); } ///Any code D800–DFFF is invalid: UTF-16 conflict (2047 chars) try { var c = String.fromCharCode(n); encodeURIComponent(c); u_string += c; } catch(e) { throw Error('could not encode uri component for char:'+n); } } if (u_string.match(/\s/)!=null) { throw Error('FAILS BY WHITESPACE'); } return u_string; }; this.nums = function(u_string) { var nums = []; var m = u_string.length; for (var i=0;i<m;i++) { var n = u_string.charCodeAt(i)-this.min; nums.push(n%256); var x2 = parseInt(n/256,10); if (x2 != 0) nums.push(x2); } return nums; }; })();//end U2N var CBook= { + chars:{'.':'unicrap',',':'base64'}, unicrap:{ chr:'.', encrypt:function(iv,ciph) { var compressed = U2N.compress(ciph.cipher); var compressed_IV = U2N.unicode(iv); //cheat on making exceptions and just try decrypt decrypt.apply(null,CBook.unicrap.decrypt(compressed_IV,compressed)); return [compressed_IV, compressed]; }, decrypt:function(iv,ciphtext) { return [U2N.nums(iv), U2N.decompress(ciphtext)]; } }, base64:{ chr:',', encrypt:function(iv,ciph) { return [Base64.encodeBytes(iv), Base64.encode(ciph.cipher)]; }, decrypt:function(iv64,ciphtext) { return [Base64.decodeBytes(iv64), Base64.decode(ciphtext)]; } } /*,hex:{ chr:'_', encrypt:function(iv,ciph) { return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)]; }, decrypt:function(iv,ciphtext) { } }*/ };//end CBook function format_post(codec,hash,iv,ciphertext) { var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':'; //console.log(rv.length); return rv; } function test_unicode(txt,f) { f = f||function(c) { return c.match(/([\w\W])/); }; for (var i=0;i<txt.length;i++) { var r = f(String.fromCharCode(txt.charCodeAt(i))); if (r) { console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i)); } } } function decrypt_message(crypted) { var x; var retval = ''; while ((x = crypted_regex.exec(crypted)) != null) { - for (m in CBook) { - if (CBook[m].chr == x[1]) { - try { - retval += decrypt.apply(null,CBook[m].decrypt(x[3],x[4])) + '<br />'; - }catch(e) { - retval += 'Failed to decrypt message, likely due to encoding problems<br />'; - } - } + var friend_keys = Stor.getKeysByIdentifier(x[2]), + cbook_method = CBook[CBook.chars[x[1]]], + success = false; + if (!friend_keys || !friend_keys.length ) { + retval += global.FAIL_NOKEY; + continue; + } + try { + var iv_ciph = cbook_method.decrypt(x[3],x[4]); + }catch(e) { + retval += global.FAIL_ENCODING; + continue; } + var i = friend_keys.length; + while (i--) { + try { + var msg = decrypt(iv_ciph[0],iv_ciph[1],Base64.decodeBytes(friend_keys[i])); + retval += msg+ '<br />'; + success = true; + continue; + } catch(e) {/*probably, just the wrong key, keep trying*/} + } + if (!success) retval += global.FAIL_NOKEY; } return retval; } -function encrypt_message(plaintext, mode, key) { +function encrypt_message(plaintext, mode, key_and_ref) { mode = mode || 'hex'; - var tries = 200; - var comp = []; - comp.push(CBook[mode].chr, key); + var key_ref = key_and_ref.substr(0,1), + key = Base64.decodeBytes(key_and_ref.substr(2)), + tries = 200, + comp = []; while (--tries) { try { - comp.push.apply(comp, - CBook[mode].encrypt.apply(null, - encrypt(plaintext))); + comp = CBook[mode].encrypt.apply(null,encrypt(plaintext, key)); break; } catch(e) { //console.log(e); } } + + comp.unshift(CBook[mode].chr, key_ref); + if (tries == 0) { throw Error('tried too many times and failed'); } var rv = format_post.apply(null,comp); if (window.parent != window && window.postMessage) { window.parent.postMessage(rv,"*"); } return rv; } -function encrypt(plaintext) { +function encrypt(plaintext, encrypt_key_numbers) { var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128); - var crypt_args = cryptArgs(iv); + var crypt_args = cryptArgs(iv, encrypt_key_numbers); crypt_args.unshift(plaintext); return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args)]; } -function decrypt(iv,ciph_string) { - var crypt_args = cryptArgs(iv); +function decrypt(iv,ciph_string, encrypt_key_numbers) { + var crypt_args = cryptArgs(iv, encrypt_key_numbers); if (crypt_args[0]==2) throw Error('if CBC, then we need to save the msgsize'); crypt_args.unshift(ciph_string,0); var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args); return plaintext; } function update_bookmarklet() { var bk = document.getElementById('bookmarklet_source').innerHTML; var target = document.getElementById('bookmarklet'); target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")'; } function tryGenuine() { /*will try to show genuinity*/ } \ No newline at end of file diff --git a/client/js/local_session.js b/client/js/local_session.js index 49de6ae..b3ee5fa 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,152 +1,157 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } + this.getKeysByIdentifier = function(ident) { + var friends = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); + return friends[ident]; + } + this.keyList = function() { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) { for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); key_list[side]([k,secret,alias]); } } return key_list; } this.populateKeysOnSelect = function(select) { var key_list = self.keyList(); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); - o.value = k[0]+k[1]; + o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var prefix = self.getKeyIdentifier(newsecret); var alias = frm.elements['alias'].value; ///v:value, p:privacy var obj = {"alias":{"v":alias,"p":"friends"}}; self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = self.permStor.get(key); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret, self.nsPEOPLE); } this.addPrefix = function(prefix, newsecret, namespace) { var ppl = JSON.parse(self.permStor.get(namespace,'{}')); ppl[prefix] = ppl[prefix] || []; ppl[prefix].push(newsecret); self.permStor.set(namespace, JSON.stringify(ppl)); } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.backupFriends = function() { } this.restoreFriends = function(friend_str) { } } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
445d652253e1a2483ef7c8ec1474e9c61076bdf8
connecting key generation to menu
diff --git a/client/index.html b/client/index.html index a99cc7b..3800b64 100644 --- a/client/index.html +++ b/client/index.html @@ -1,205 +1,205 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <span id="decrypt_output"></span> <form id="encode" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button> for friends of - <select name="friendkey"> - <option value="s">mine</option> + <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> - <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> + <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="hide"> Share this link with all your friends. <a id="keylink" class="hide" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> </div> <a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/base.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { - document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); - var x = window.parent.location; - //window.parent.location = x+'#foooo'; + document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); + var x = window.parent.location; + //window.parent.location = x+'#foooo'; } if (/encode/.test(document.location.hash)) { - document.forms['encode'].elements['txt'].focus(); - document.forms['encode'].elements['compress'].checked = ( - /compress=true/.test(document.location.search) - ); + document.forms['encode'].elements['txt'].focus(); + document.forms['encode'].elements['compress'].checked = ( + /compress=true/.test(document.location.search) + ); + Stor.populateKeysOnSelect(document.getElementById('friendkey')); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/local_session.js b/client/js/local_session.js index 661a3ef..49de6ae 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,121 +1,152 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; - function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; - stor.setItem(this.KEYS_KEY,M.JSON.stringify(key_dict)); + stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); + } + this.deleteEveryFuckingThing = function() { + for (a in key_dict) + this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64) { ///first two bytes of the sha256 hash of the key in base64; - return Base64._keyStr[parseInt( - ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2), - 16)]; + var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); + return Base64._keyStr[Math.floor(x/4)]; } + this.keyList = function() { + var key_list = [/*me-friends divider:*/['','','---------']]; + var me = JSON.parse(self.permStor.get(self.nsME,'{}')); + var friends = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); + + for (k in friends) { + for (var i=0;i<friends[k].length;i++) { + var secret = friends[k][i]; + var alias = self.getInfo(secret).alias.v; + var side = ((secret in me) ?'unshift':'push'); + key_list[side]([k,secret,alias]); + } + } + return key_list; + } + this.populateKeysOnSelect = function(select) { + var key_list = self.keyList(); + for (var i=0;i<key_list.length;i++) { + var k=key_list[i]; + var o=document.createElement('option'); + o.value = k[0]+k[1]; + o.innerHTML = k[2]; + select.appendChild(o); + } + } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var prefix = self.getKeyIdentifier(newsecret); var alias = frm.elements['alias'].value; - var obj = {}; ///v:value, p:privacy - obj[newsecret] = {"alias":{"v":alias,"p":"friends"}}; - - self.addFriend(newsecret, obj, prefix); + var obj = {"alias":{"v":alias,"p":"friends"}}; self.addMyKey(newsecret, obj, prefix); + self.addFriend(newsecret, obj, prefix); + alert('New key generated.'); } - this.addMyKey = function(newsecret, obj, prefix) { - prefix = prefix || self.getKeyIdentifier(newsecret); - ///TODO NEXT NEXT + this.addMyKey = function(secret) { + var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); + keys[secret]=1; + self.permStor.set(self.nsME, JSON.stringify(keys)); } + this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret); var key = self.nsPERSON + newsecret; - if (key in self.permStor.keyDict()) { + if (self.permStor.hasKey(key)) { var old_person = self.permStor.get(key); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); - self.addPrefix(prefix, newsecret); + self.addPrefix(prefix, newsecret, self.nsPEOPLE); } - this.addPrefix = function(prefix, newsecret) { - var ppl = JSON.parse(self.permStor.get(self.nsPEOPLE)); + this.addPrefix = function(prefix, newsecret, namespace) { + var ppl = JSON.parse(self.permStor.get(namespace,'{}')); ppl[prefix] = ppl[prefix] || []; ppl[prefix].push(newsecret); + self.permStor.set(namespace, JSON.stringify(ppl)); + } + + this.getInfo = function(secret) { + return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.backupFriends = function() { } this.restoreFriends = function(friend_str) { } - this.people_keys = this.permStor.get(this.nsPEOPLE, {}) - } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
1de64a848b3c1af24ebe646d5b4559ad4b5890dc
addFRiend, and almost all generateKey
diff --git a/client/js/local_session.js b/client/js/local_session.js index f84af63..661a3ef 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,80 +1,121 @@ +/* + { + CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} + MY_KEYS: {"s":['{{key1}}']} + PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} + } +*/ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,M.JSON.stringify(key_dict)); } } function MyStorage() { + var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; - this.nsME = 'ME_'; + this.nsME = 'MY_KEYS'; - this.generateKey = function(frm) { - alert(frm.tagName); + this.getKeyIdentifier = function(key_base64) { + ///first two bytes of the sha256 hash of the key in base64; + return Base64._keyStr[parseInt( + ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2), + 16)]; } - this.addFriend = function() { - + this.generateKey = function(frm) { + var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); + var prefix = self.getKeyIdentifier(newsecret); + var alias = frm.elements['alias'].value; + var obj = {}; + ///v:value, p:privacy + obj[newsecret] = {"alias":{"v":alias,"p":"friends"}}; + + self.addFriend(newsecret, obj, prefix); + self.addMyKey(newsecret, obj, prefix); + } + this.addMyKey = function(newsecret, obj, prefix) { + prefix = prefix || self.getKeyIdentifier(newsecret); + ///TODO NEXT NEXT + } + this.addFriend = function(newsecret, obj, prefix) { + prefix = prefix || self.getKeyIdentifier(newsecret); + var key = self.nsPERSON + newsecret; + if (key in self.permStor.keyDict()) { + var old_person = self.permStor.get(key); + if (NOT(obj.alias && obj.alias.v) + || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { + return; + } + } + if (NOT(obj.alias && obj.alias.v)) { + return; //atm, don't support friends w/o aliases + } + self.permStor.set(key, JSON.stringify(obj)); + self.addPrefix(prefix, newsecret); } - this.addMyInfo = function() { - + this.addPrefix = function(prefix, newsecret) { + var ppl = JSON.parse(self.permStor.get(self.nsPEOPLE)); + ppl[prefix] = ppl[prefix] || []; + ppl[prefix].push(newsecret); } this.backupFriends = function() { } this.restoreFriends = function(friend_str) { } this.people_keys = this.permStor.get(this.nsPEOPLE, {}) } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
689b9ca69fdce0990b7015b0e45b00cbfce6e54c
base64 chars for URLs
diff --git a/client/index.html b/client/index.html index 7bc8428..a99cc7b 100644 --- a/client/index.html +++ b/client/index.html @@ -1,205 +1,205 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <span id="decrypt_output"></span> <form id="encode" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button> for friends of <select name="friendkey"> <option value="s">mine</option> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> - <form id="generatekey" class="sec" onsubmit="update_bookmarklet();return false;"> + <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="hide"> Share this link with all your friends. <a id="keylink" class="hide" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> </div> <a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/base.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } if (/encode/.test(document.location.hash)) { document.forms['encode'].elements['txt'].focus(); document.forms['encode'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/base.js b/client/js/base.js index a7e5e30..6440e28 100644 --- a/client/js/base.js +++ b/client/js/base.js @@ -1,249 +1,243 @@ var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?', regex_args = ['codec','hash','iv','ciphtext'], html_regex = '<([:\\w]+)[^<]+'; var crypted_regex = new RegExp(crypted_regex_str,'g'); /* facebook: document.getElementsByClassName('uiStreamMessage') twitter: //document.activeElement to know which element has focus 15chars for IV 1char for addition 4chars for ♔.☿ (could make it 3) 'http://skyb.us/' == 15 chars 140=15+1+4+15+105 */ var global= { encrypt_key:"99add3674eea0f3a84201b8f65017114", encrypt_iv:"80a5c7ce51fbeb81a9bad0f44112c17408eb46b172fec9b118bfa6dd2a2772fe", mode:0,//0:OFB,1:CFB,2:CBC keysize:16//32 for 256, 24 for 192, 16 for 128 } function cryptArgs(iv) { ///see http://www.josh-davis.org/ecmascrypt ///NOTE:if CBC, then we need to save the msgsize var mode = 0; //0:OFB,1:CFB,2:CBC var keysize = 16; //32 for 256, 24 for 192, 16 for 128 var hexkey = global.encrypt_key; var iv = iv||global.encrypt_iv; return [mode,ecmaScrypt.toNumbers(hexkey),keysize,iv]; } var U2N = new (function() { /* we'll need to get a lot smarter. we should be accepting/creating unicode characters within the character range that HTML considers 'character' text. http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets parseInt('10FFFF',16) - parseInt('10000',16) == 1048575 1114111 - 65536 == String.fromCharCode(85267) seems to be 'real' first character */ this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars this.compress = function(low_unicode) { var arr = []; var c = low_unicode.length; while (c--) { arr.unshift(low_unicode.charCodeAt(c)); } return this.unicode(arr); } this.decompress = function(high_unicode) { var nums = this.nums(high_unicode); var str = ''; for (var i=0;i<nums.length;i++) { str += String.fromCharCode(nums[i]); } return str; } this.lowcoding = function(cipher) { var outhex = ''; for(var i = 0;i < cipher.length;i++) { outhex += ecmaScrypt.toHex(cipher.charCodeAt(i)); } return outhex; } this.unicode = function(nums) { ///take nums array of numbers from 0-255 var u_string=''; for (var i=0;i<nums.length;i++) { var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) ); if (n>65535) { ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes throw Error('cannot deal with high chars yet'); } if (n>2299099) { throw Error('cannot deal with high unicode compression yet'); //but I think the answer is that we'll have some marker //for NON-encoded text and then // } ///random suspects: if (n==1759 || n==130) { throw Error('random suspect--not sure it is culprit'); } if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes'); //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n); } if (8192 < n && n < 8447) { //255 chars ///http://en.wikipedia.org/wiki/Unicode_control_characters ///seem to be grouped all in the 2000 -20FF range throw Error('Wide fence for control chars. we can be more picky'+n); } ///Any code D800–DFFF is invalid: UTF-16 conflict (2047 chars) try { var c = String.fromCharCode(n); encodeURIComponent(c); u_string += c; } catch(e) { throw Error('could not encode uri component for char:'+n); } } if (u_string.match(/\s/)!=null) { throw Error('FAILS BY WHITESPACE'); } return u_string; }; this.nums = function(u_string) { var nums = []; var m = u_string.length; for (var i=0;i<m;i++) { var n = u_string.charCodeAt(i)-this.min; nums.push(n%256); var x2 = parseInt(n/256,10); if (x2 != 0) nums.push(x2); } return nums; }; })();//end U2N var CBook= { unicrap:{ chr:'.', encrypt:function(iv,ciph) { var compressed = U2N.compress(ciph.cipher); var compressed_IV = U2N.unicode(iv); //cheat on making exceptions and just try decrypt decrypt.apply(null,CBook.unicrap.decrypt(compressed_IV,compressed)); return [compressed_IV, compressed]; }, decrypt:function(iv,ciphtext) { return [U2N.nums(iv), U2N.decompress(ciphtext)]; } }, base64:{ chr:',', encrypt:function(iv,ciph) { - var iv64 = ''; - for (var i=0;i<iv.length;i++) { - iv64 += Base64._bytes2chars(iv[i],iv[++i],iv[++i]); - } - return [iv64,Base64.encode(ciph.cipher)]; + return [Base64.encodeBytes(iv), + Base64.encode(ciph.cipher)]; }, decrypt:function(iv64,ciphtext) { - var iv = []; - for (var i=0;i<iv64.length;i+=4) { - iv.push.apply(iv,Base64._chars2bytes(iv64.substr(i,4))); - } - return [iv,Base64.decode(ciphtext)]; + return [Base64.decodeBytes(iv64), + Base64.decode(ciphtext)]; } } /*,hex:{ chr:'_', encrypt:function(iv,ciph) { return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)]; }, decrypt:function(iv,ciphtext) { } }*/ };//end CBook function format_post(codec,hash,iv,ciphertext) { var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':'; //console.log(rv.length); return rv; } function test_unicode(txt,f) { f = f||function(c) { return c.match(/([\w\W])/); }; for (var i=0;i<txt.length;i++) { var r = f(String.fromCharCode(txt.charCodeAt(i))); if (r) { console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i)); } } } function decrypt_message(crypted) { var x; var retval = ''; while ((x = crypted_regex.exec(crypted)) != null) { for (m in CBook) { if (CBook[m].chr == x[1]) { try { retval += decrypt.apply(null,CBook[m].decrypt(x[3],x[4])) + '<br />'; }catch(e) { retval += 'Failed to decrypt message, likely due to encoding problems<br />'; } } } } return retval; } function encrypt_message(plaintext, mode, key) { mode = mode || 'hex'; var tries = 200; var comp = []; comp.push(CBook[mode].chr, key); while (--tries) { try { comp.push.apply(comp, CBook[mode].encrypt.apply(null, encrypt(plaintext))); break; } catch(e) { //console.log(e); } } if (tries == 0) { throw Error('tried too many times and failed'); } var rv = format_post.apply(null,comp); if (window.parent != window && window.postMessage) { window.parent.postMessage(rv,"*"); } return rv; } function encrypt(plaintext) { var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128); var crypt_args = cryptArgs(iv); crypt_args.unshift(plaintext); return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args)]; } function decrypt(iv,ciph_string) { var crypt_args = cryptArgs(iv); if (crypt_args[0]==2) throw Error('if CBC, then we need to save the msgsize'); crypt_args.unshift(ciph_string,0); var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args); return plaintext; } function update_bookmarklet() { var bk = document.getElementById('bookmarklet_source').innerHTML; var target = document.getElementById('bookmarklet'); target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")'; } function tryGenuine() { /*will try to show genuinity*/ } \ No newline at end of file diff --git a/client/js/base64.js b/client/js/base64.js index d07d54b..832a287 100644 --- a/client/js/base64.js +++ b/client/js/base64.js @@ -1,142 +1,156 @@ /** * * Base64 encode / decode * Based off of http://www.webtoolkit.info/javascript-base64.html * **/ var Base64 = { // private property - _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/=", + _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", + encodeBytes: function(byte_ary) { + var output = ""; + for (var i=0;i<byte_ary.length;i++) { + output += Base64._bytes2chars(byte_ary[i],byte_ary[++i],byte_ary[++i]); + } + return output; + }, + decodeBytes: function(input) { + var byte_ary = []; + for (var i=0;i<input.length;i+=4) { + byte_ary.push.apply(byte_ary,Base64._chars2bytes(input.substr(i,4))); + } + return byte_ary; + }, // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); output += this._bytes2chars(chr1,chr2,chr3); } return output; }, // private method changing integers to chars _bytes2chars : function(chr1,chr2,chr3) { enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } return (this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4)); }, _chars2bytes : function(chars4) { enc1 = this._keyStr.indexOf(chars4.charAt(0)); enc2 = this._keyStr.indexOf(chars4.charAt(1)); enc3 = this._keyStr.indexOf(chars4.charAt(2)); enc4 = this._keyStr.indexOf(chars4.charAt(3)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; var rv = [chr1]; if (enc3 != 64) rv.push(chr2) if (enc4 != 64) rv.push(chr3) return rv }, // public method for decoding decode : function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(RegExp('[^'+this._keyStr+']','g'), ""); while (i < input.length) { var chr=this._chars2bytes(input.substr(i,4)); i+=4; for (var j=0;j<chr.length;j++) { output = output + String.fromCharCode(chr[j]); } } output = Base64._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } } \ No newline at end of file diff --git a/client/js/local_session.js b/client/js/local_session.js index 17ef3fa..f84af63 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,76 +1,80 @@ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,M.JSON.stringify(key_dict)); } } function MyStorage() { this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'ME_'; + this.generateKey = function(frm) { + alert(frm.tagName); + } + this.addFriend = function() { } this.addMyInfo = function() { } this.backupFriends = function() { } this.restoreFriends = function(friend_str) { } this.people_keys = this.permStor.get(this.nsPEOPLE, {}) } if (window.localStorage) { - global.EphemeralSession = new MyStorage(); - global.e = global.EphemeralSession; + global.Stor = new MyStorage(); + global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
05604d06e9b6664800ada6de763704a471d7af0d
add terminus character ":" so we can find multiple strings in the same text (backwards incompatible)
diff --git a/client/index.html b/client/index.html index 07a8276..7bc8428 100644 --- a/client/index.html +++ b/client/index.html @@ -1,194 +1,205 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <span id="decrypt_output"></span> <form id="encode" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button> for friends of <select name="friendkey"> <option value="s">mine</option> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form id="generatekey" class="sec" onsubmit="update_bookmarklet();return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="hide"> Share this link with all your friends. <a id="keylink" class="hide" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> </div> <a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/base.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; - var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+', + var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), - crypted_regex = new RegExp(crypted_regex_str); + crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); - frm.setAttribute('height', height||par.offsetHeight); + frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); - var m = textNode.data.match(crypted_regex); - var n = textNode.parentNode.parentNode.textContent.match(crypted_regex); + + var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; + var local_str = textNode.data; + var higher_str = textNode.parentNode.parentNode.textContent; + var m = crypted_regex.exec(local_str); + var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); - var frm = mkfrm(textNode.parentNode, loc+'?decrypt;mode=postMessage#decrypt='+m[0]); + do { + frm_loc += m[0]; + } while ((m = crypted_regex.exec(local_str)) != null); + var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); - var frm = mkfrm(textNode.parentNode.parentNode, loc+'?decrypt;mode=postMessage#decrypt='+n[0]); + do { + frm_loc += n[0]; + } while ((n = crypted_regex.exec(higher_str)) != null); + var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { + var key = 'value'; if (active.contenteditable) { - active.innerHTML += evt.data; + key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { - active.value = evt.data; if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } - } else { - active.value += evt.data; } } + /*add space, in to separate a possible first cmessage from the next*/ + if (active[key]) active[key]+= ' '; + active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } if (/encode/.test(document.location.hash)) { document.forms['encode'].elements['txt'].focus(); document.forms['encode'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/base.js b/client/js/base.js index 6ddbc33..a7e5e30 100644 --- a/client/js/base.js +++ b/client/js/base.js @@ -1,247 +1,249 @@ -var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+)', +var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?', regex_args = ['codec','hash','iv','ciphtext'], html_regex = '<([:\\w]+)[^<]+'; -var crypted_regex = new RegExp(crypted_regex_str); +var crypted_regex = new RegExp(crypted_regex_str,'g'); /* facebook: document.getElementsByClassName('uiStreamMessage') twitter: //document.activeElement to know which element has focus 15chars for IV 1char for addition 4chars for ♔.☿ (could make it 3) 'http://skyb.us/' == 15 chars 140=15+1+4+15+105 */ var global= { encrypt_key:"99add3674eea0f3a84201b8f65017114", encrypt_iv:"80a5c7ce51fbeb81a9bad0f44112c17408eb46b172fec9b118bfa6dd2a2772fe", mode:0,//0:OFB,1:CFB,2:CBC keysize:16//32 for 256, 24 for 192, 16 for 128 } function cryptArgs(iv) { ///see http://www.josh-davis.org/ecmascrypt ///NOTE:if CBC, then we need to save the msgsize var mode = 0; //0:OFB,1:CFB,2:CBC var keysize = 16; //32 for 256, 24 for 192, 16 for 128 var hexkey = global.encrypt_key; var iv = iv||global.encrypt_iv; return [mode,ecmaScrypt.toNumbers(hexkey),keysize,iv]; } var U2N = new (function() { /* we'll need to get a lot smarter. we should be accepting/creating unicode characters within the character range that HTML considers 'character' text. http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets parseInt('10FFFF',16) - parseInt('10000',16) == 1048575 1114111 - 65536 == String.fromCharCode(85267) seems to be 'real' first character */ this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars this.compress = function(low_unicode) { var arr = []; var c = low_unicode.length; while (c--) { arr.unshift(low_unicode.charCodeAt(c)); } return this.unicode(arr); } this.decompress = function(high_unicode) { var nums = this.nums(high_unicode); var str = ''; for (var i=0;i<nums.length;i++) { str += String.fromCharCode(nums[i]); } return str; } this.lowcoding = function(cipher) { var outhex = ''; for(var i = 0;i < cipher.length;i++) { outhex += ecmaScrypt.toHex(cipher.charCodeAt(i)); } return outhex; } this.unicode = function(nums) { ///take nums array of numbers from 0-255 var u_string=''; for (var i=0;i<nums.length;i++) { var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) ); if (n>65535) { ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes throw Error('cannot deal with high chars yet'); } if (n>2299099) { throw Error('cannot deal with high unicode compression yet'); //but I think the answer is that we'll have some marker //for NON-encoded text and then // } ///random suspects: if (n==1759 || n==130) { throw Error('random suspect--not sure it is culprit'); } if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes'); //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n); } if (8192 < n && n < 8447) { //255 chars ///http://en.wikipedia.org/wiki/Unicode_control_characters ///seem to be grouped all in the 2000 -20FF range throw Error('Wide fence for control chars. we can be more picky'+n); } ///Any code D800–DFFF is invalid: UTF-16 conflict (2047 chars) try { var c = String.fromCharCode(n); encodeURIComponent(c); u_string += c; } catch(e) { throw Error('could not encode uri component for char:'+n); } } if (u_string.match(/\s/)!=null) { throw Error('FAILS BY WHITESPACE'); } return u_string; }; this.nums = function(u_string) { var nums = []; var m = u_string.length; for (var i=0;i<m;i++) { var n = u_string.charCodeAt(i)-this.min; nums.push(n%256); var x2 = parseInt(n/256,10); if (x2 != 0) nums.push(x2); } return nums; }; })();//end U2N var CBook= { unicrap:{ chr:'.', encrypt:function(iv,ciph) { var compressed = U2N.compress(ciph.cipher); var compressed_IV = U2N.unicode(iv); //cheat on making exceptions and just try decrypt decrypt.apply(null,CBook.unicrap.decrypt(compressed_IV,compressed)); return [compressed_IV, compressed]; }, decrypt:function(iv,ciphtext) { return [U2N.nums(iv), U2N.decompress(ciphtext)]; } }, base64:{ chr:',', encrypt:function(iv,ciph) { var iv64 = ''; for (var i=0;i<iv.length;i++) { iv64 += Base64._bytes2chars(iv[i],iv[++i],iv[++i]); } return [iv64,Base64.encode(ciph.cipher)]; }, decrypt:function(iv64,ciphtext) { var iv = []; for (var i=0;i<iv64.length;i+=4) { iv.push.apply(iv,Base64._chars2bytes(iv64.substr(i,4))); } return [iv,Base64.decode(ciphtext)]; } } /*,hex:{ chr:'_', encrypt:function(iv,ciph) { return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)]; }, decrypt:function(iv,ciphtext) { } }*/ };//end CBook function format_post(codec,hash,iv,ciphertext) { - var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext; + var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':'; //console.log(rv.length); return rv; } function test_unicode(txt,f) { f = f||function(c) { return c.match(/([\w\W])/); }; for (var i=0;i<txt.length;i++) { var r = f(String.fromCharCode(txt.charCodeAt(i))); if (r) { console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i)); } } } function decrypt_message(crypted) { - var x = crypted.match(crypted_regex); - if (x != null) { + var x; + var retval = ''; + while ((x = crypted_regex.exec(crypted)) != null) { for (m in CBook) { if (CBook[m].chr == x[1]) { try { - return decrypt.apply(null,CBook[m].decrypt(x[3],x[4])); + retval += decrypt.apply(null,CBook[m].decrypt(x[3],x[4])) + '<br />'; }catch(e) { - return 'Failed to decrypt message, likely due to encoding problems'; + retval += 'Failed to decrypt message, likely due to encoding problems<br />'; } } } - } + } + return retval; } function encrypt_message(plaintext, mode, key) { mode = mode || 'hex'; var tries = 200; var comp = []; comp.push(CBook[mode].chr, key); while (--tries) { try { comp.push.apply(comp, CBook[mode].encrypt.apply(null, encrypt(plaintext))); break; } catch(e) { //console.log(e); } } if (tries == 0) { throw Error('tried too many times and failed'); } var rv = format_post.apply(null,comp); if (window.parent != window && window.postMessage) { window.parent.postMessage(rv,"*"); } return rv; } function encrypt(plaintext) { var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128); var crypt_args = cryptArgs(iv); crypt_args.unshift(plaintext); return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args)]; } function decrypt(iv,ciph_string) { var crypt_args = cryptArgs(iv); if (crypt_args[0]==2) throw Error('if CBC, then we need to save the msgsize'); crypt_args.unshift(ciph_string,0); var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args); return plaintext; } function update_bookmarklet() { var bk = document.getElementById('bookmarklet_source').innerHTML; var target = document.getElementById('bookmarklet'); target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")'; } function tryGenuine() { /*will try to show genuinity*/ } \ No newline at end of file
schuyler1d/cbook
ac5e1a1924e6bd2ac0ae4a37e464480e24c38994
encryption/bookmarklet/decryption working; TODO: create/store/load/backup friends keys
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a9ce179 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*~ +*.pyc +#* diff --git a/client/STREAM_OF_THOUGHTS b/client/STREAM_OF_THOUGHTS new file mode 100644 index 0000000..6046e52 --- /dev/null +++ b/client/STREAM_OF_THOUGHTS @@ -0,0 +1,221 @@ +tools: + see where my info can get to (from 'weakest link') + see what a certain person can see (of mine) + +site: + feed for all things for you (rss-like) + OAuth + twitter annotation +private-key per friend-group? + +----- +comm issues + friends of friends needs to know who friends are + OR have a proxy 'friend' +----- +importable +exportable +(encrypted and unencrypted) +(partial and whole) + +privacy settings (shared) + +proxies: + OAuth + persistant permission, or one-time? + http://openidconnect.com/ + +everyone, +friends of friends, (proxy) +friends, (proxy) +with-permission (you get asked) , (proxy) +private +http://developers.facebook.com/docs/authentication/permissions + +personal info + name + alias + bio + birthday (Month, Day, Year have separate permissions) + interested in/looking for + religious views + political views + photo albums + posts by me + allow friends to post on my wall + who can see my wall + posts by friends + comments on posts + +contact info + im screen name + mobile phone + other phone + current address + website + add me as a friend + send me a message + (each email address) + + web presence + +friends/tags/connections + friend list + family list + relationships + photos and videos of me + current city + current (immediate location) + hometown + education and work + activities + interests + things I like + +applications and websites + (what you share) (fb section: learn more) + what your friends can share + blocked applications + ignore application invites + activity on applications and games dashboards + instant personalization pilot program + use publicly for other websites + + sky: + +search +block list + + + +------------------------------------ +site specific + sort of like a 'friend' + attention levels (ignore X) (sites can obviously customize these things) + friend-status + friends sharing your content/etc + +application specific (with default) + what you can share + what others can share + +SITE-to-SITE + public-key + contacts + picture/icon + contact-info + + +Interface: + my keys + create new key + share with friends: (passphrase) + + friends keys + add + backup/restore + +key:name/alias:hash + +:desired privacy (friends/friends-of-friends/public/with-permission/private (not shared with anyone) ) + user email/URL + + +CBOOK_PEOPLE {"s":['key1','key2']} +*"PERSON_"+hash {key: {fof:{name,email,facebook}, friends:{} } } + +{"keys":{"s:kj3l45kj3k4j54":{"friends":{"name":"Schuyler"}}}} + + +Objects +-------------------- +Friend + URI (key, could be email address) + pubkey + groups (pubkeys) + + +POSTing to the friend URI with + shareable-with + content + uri + author(my URI) + pubkey (of which the private one is required to decrypt?) + other fields (location, comments link, ) + +GETing with Accept:text/html or whatever + public links + +GETing with Accept:application/json + digest auth + +GETing with Accept:application/foaf + should return a REDIRECT to the template URLs + for + +User Views +-------------- +status updates +where has my info gone? +where are my friends (which apps)? + +protocols for encrypted tweets: +{].2j0 k34jl5k3j4l5k34kk4k4kl3l33 +♔.☿ #K$J%#$%J#:L$KJ%# +♔,말 K$J%#$%J#:Lあ叶葉K$J%#$%J#:L +support unicode for most languages by doing a min() on the unicode chars, and +subtracting the value off from all the chars. Then put the min() in the front + +14chars for IV +1char for addition +4chars for ♔.☿ (could make it 3) +'http://skyb.us/' == 15 chars +140=17+1+4+15+103 + +ascii 61-* is ok. avoid [^<&;] + +128+12=140 + +128*128=16384 + +2299099 is last unicode char I see +but there are lots of holes + +Who do you trust? + +DEEPER levels of paranoia: +-------------------------- +your hosting company + you put your SSL private key on the host, so they can pretend to be you + + What to do: + +your web browser + certificates + +your email communication channel + Google admits they read your email. How many other companies do the same? + + What to do: use pgp encryption + +your operating system + + What to do: well, first how about trying Linux--at least, + other people can analyze the source code that it was based on + and Linux-people are hippies anyway, right? + + Actually, it's a good first step + + +your compiler + + + +your computer + Who knows what secret instructions Intel and AMD were told to add + by the NSA or China. Wait! A lot of these chip and computer + factories are IN China.... + + What to do? + Well, there's open-source hardware. You could get some eproms and + punch in the assembly by hand to the.....AHHAHHAH! diff --git a/client/TODO b/client/TODO new file mode 100644 index 0000000..53a9f69 --- /dev/null +++ b/client/TODO @@ -0,0 +1,3 @@ +1. interface for creating/removing keys, adding friends keys +2. framewalk in bookmarklet +3. \ No newline at end of file diff --git a/client/index.html b/client/index.html new file mode 100644 index 0000000..07a8276 --- /dev/null +++ b/client/index.html @@ -0,0 +1,194 @@ +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html> +<html> + <head> + <title>CBook</title> + <style type="text/css"> + body {background-color:#EDFEFF} + textarea {width:100%;} + .hide,.sec {display:none;} + .sec:target {display:block;} + .small{font-size:9px;} + a.bookmarklet { + text-decoration:none; + text-align:center; + padding:5px; + background-color:#BBBBBB; + -moz-border-radius: 8px; + -webkit-border-radius: 8px; + + } + </style> + </head> + <body> + <span id="decrypt_output"></span> + <form id="encode" class="sec" onsubmit="return false;"> + + <textarea name="txt"></textarea> + <button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button> + for friends of + <select name="friendkey"> + <option value="s">mine</option> + </select> + <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> + <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> + <p id="output"></p> + <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> + </form> + <div id="decode" class="sec"></div> + <div id="setup"> + <form id="addfriends" class="sec" action="#addfriends"> + <h4>Add Friends</h4> + Site passphrase: + <input type="text" size="30" name="passphrase" /> + <textarea rows="8" name="friendlinks"></textarea> + <input type="submit" value="Add Friends"/> + </form> + + <form id="generatekey" class="sec" onsubmit="update_bookmarklet();return false;"> + <h4>Generate Your Key</h4> + Name or Alias: + <input type="text" size="30" name="alias" /><br /> + <input type="submit" value="Generate your Friends-Key" /><br /> + <span id="keylinksec" class="hide"> + Share this link with all your friends. + <a id="keylink" class="hide" href="#foo">link for friends</a> + + </span> + <br /> + Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. + + + </form> + </div> + <a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> + + <script type="text/javascript" src="js/base64.js"></script> + <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> + <script type="text/javascript" src="js/local_session.js"></script> + <script type="text/javascript" src="js/base.js"></script> + + <script type="text/javascript" id="bookmarklet_source"> + function bookmarklet(loc,friends) { + var active = document.activeElement, + tags = {}, + nodes = [], + crown = String.fromCharCode(9812), + lt = String.fromCharCode(60), + amp = String.fromCharCode(38), + quot = String.fromCharCode(34), + laq = lt+amp+quot; + + var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+', + html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; + + var html_regex = new RegExp(html_regex_str+crypted_regex_str), + crypted_regex = new RegExp(crypted_regex_str); + + var mkfrm = function(par,src,height) { + if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { + return; + par.removeChild(par.firstChild); + } + + var frm = par.ownerDocument.createElement('iframe'); + frm.setAttribute('width', par.offsetWidth); + frm.setAttribute('height', height||par.offsetHeight); + frm.setAttribute('class','cbook'); + /*par.appendChild(frm);*/ + par.insertBefore(frm,par.firstChild); + frm.src = src; + return frm; + }; + + /* begin process */ + if (document.evaluate) { + var xPathResult = document + .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', + document.body, + null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); + for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { + var textNode = xPathResult.snapshotItem(i); + var m = textNode.data.match(crypted_regex); + var n = textNode.parentNode.parentNode.textContent.match(crypted_regex); + if (m!=null) { + nodes.push(textNode); + var frm = mkfrm(textNode.parentNode, loc+'?decrypt;mode=postMessage#decrypt='+m[0]); + } else if (n!=null) { /*for facebook, which breaks up long words*/ + nodes.push(textNode); + var frm = mkfrm(textNode.parentNode.parentNode, loc+'?decrypt;mode=postMessage#decrypt='+n[0]); + } + } + } else {/*if we ever start caring about IE*/ + var matches = document.body.innerHTML.split(html_regex); + while (matches.length > 1) { + matches.shift(); + var tag = matches.shift(); + /*coded = matches.shift();*/ + tags[tag] = []; + } + for (t in tags) { + var elts = document.getElementsByTagName(t); + for (var i=0;elts.length>i;i++) { + /*while (i--) {*/ + var m = elts[i].innerHTML.match(crypted_regex); + var dbl_parent = elts[i].innerHTML.match(html_regex); + if (m!=null) if(dbl_parent==null) { + tags[t].push(elts[i]); + var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); + } + } + } + } + if (active.tagName.toLowerCase() in {textarea:1,input:1} + || active.contenteditable + ) { + var compress = (/twitter/.test(location) ? ';compress=true' : ''); + var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101); + var w = window;/*frm.contentWindow;*/ + var listener = function(evt) { + if (evt.source == frm.contentWindow) { + if (active.contenteditable) { + active.innerHTML += evt.data; + } else { + if (active.getAttribute('placeholder')==active.value) { + active.value = evt.data; + if (active.className) {/*facebook*/ + active.className = active.className.replace('placeholder','') + } + } else { + active.value += evt.data; + } + } + } + }; + if (w.addEventListener) { + w.addEventListener('message',listener,false); + } else if (w.attachEvent) { + w.attachEvent('message',listener); + } + } + } + </script> + <script type="text/javascript"> + window.t = document.forms[0].elements["txt"]; + window.c = document.forms[0].elements["compress"]; + window.f = document.forms[0].elements["friendkey"]; + window.p = document.getElementById('output'); + var dec = document.location.hash.match(/decrypt=(.+)$/); + if (dec!=null) { + document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); + var x = window.parent.location; + //window.parent.location = x+'#foooo'; + } + + if (/encode/.test(document.location.hash)) { + document.forms['encode'].elements['txt'].focus(); + document.forms['encode'].elements['compress'].checked = ( + /compress=true/.test(document.location.search) + ); + } + update_bookmarklet(); + </script> + </body> +</html> diff --git a/client/js/base.js b/client/js/base.js new file mode 100644 index 0000000..6ddbc33 --- /dev/null +++ b/client/js/base.js @@ -0,0 +1,247 @@ +var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+)', +regex_args = ['codec','hash','iv','ciphtext'], +html_regex = '<([:\\w]+)[^<]+'; +var crypted_regex = new RegExp(crypted_regex_str); + +/* + facebook: document.getElementsByClassName('uiStreamMessage') + twitter: + //document.activeElement to know which element has focus + +15chars for IV +1char for addition +4chars for ♔.☿ (could make it 3) +'http://skyb.us/' == 15 chars +140=15+1+4+15+105 +*/ + +var global= { + encrypt_key:"99add3674eea0f3a84201b8f65017114", + encrypt_iv:"80a5c7ce51fbeb81a9bad0f44112c17408eb46b172fec9b118bfa6dd2a2772fe", + mode:0,//0:OFB,1:CFB,2:CBC + keysize:16//32 for 256, 24 for 192, 16 for 128 +} +function cryptArgs(iv) { + ///see http://www.josh-davis.org/ecmascrypt + ///NOTE:if CBC, then we need to save the msgsize + var mode = 0; //0:OFB,1:CFB,2:CBC + var keysize = 16; //32 for 256, 24 for 192, 16 for 128 + var hexkey = global.encrypt_key; + var iv = iv||global.encrypt_iv; + return [mode,ecmaScrypt.toNumbers(hexkey),keysize,iv]; +} + +var U2N = new (function() { + /* we'll need to get a lot smarter. + we should be accepting/creating unicode characters within the + character range that HTML considers 'character' text. + http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets + parseInt('10FFFF',16) - parseInt('10000',16) == 1048575 + 1114111 - 65536 == + String.fromCharCode(85267) seems to be 'real' first character + */ + this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars + this.compress = function(low_unicode) { + var arr = []; + var c = low_unicode.length; + while (c--) { + arr.unshift(low_unicode.charCodeAt(c)); + } + return this.unicode(arr); + } + this.decompress = function(high_unicode) { + var nums = this.nums(high_unicode); + var str = ''; + for (var i=0;i<nums.length;i++) { + str += String.fromCharCode(nums[i]); + } + return str; + } + this.lowcoding = function(cipher) { + var outhex = ''; + for(var i = 0;i < cipher.length;i++) { + outhex += ecmaScrypt.toHex(cipher.charCodeAt(i)); + } + return outhex; + } + this.unicode = function(nums) { + ///take nums array of numbers from 0-255 + var u_string=''; + for (var i=0;i<nums.length;i++) { + var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) ); + if (n>65535) { + ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes + throw Error('cannot deal with high chars yet'); + } + if (n>2299099) { + throw Error('cannot deal with high unicode compression yet'); + //but I think the answer is that we'll have some marker + //for NON-encoded text and then + // + } + ///random suspects: + if (n==1759 || n==130) { + throw Error('random suspect--not sure it is culprit'); + } + if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars + //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes'); + //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n); + } + if (8192 < n && n < 8447) { //255 chars + ///http://en.wikipedia.org/wiki/Unicode_control_characters + ///seem to be grouped all in the 2000 -20FF range + throw Error('Wide fence for control chars. we can be more picky'+n); + } + ///Any code D800–DFFF is invalid: UTF-16 conflict (2047 chars) + try { + var c = String.fromCharCode(n); + encodeURIComponent(c); + u_string += c; + } catch(e) { + throw Error('could not encode uri component for char:'+n); + } + + } + if (u_string.match(/\s/)!=null) { + throw Error('FAILS BY WHITESPACE'); + } + return u_string; + }; + + this.nums = function(u_string) { + var nums = []; + var m = u_string.length; + for (var i=0;i<m;i++) { + var n = u_string.charCodeAt(i)-this.min; + nums.push(n%256); + var x2 = parseInt(n/256,10); + if (x2 != 0) nums.push(x2); + } + return nums; + }; + +})();//end U2N + +var CBook= { + unicrap:{ + chr:'.', + encrypt:function(iv,ciph) { + var compressed = U2N.compress(ciph.cipher); + var compressed_IV = U2N.unicode(iv); + //cheat on making exceptions and just try decrypt + decrypt.apply(null,CBook.unicrap.decrypt(compressed_IV,compressed)); + return [compressed_IV, compressed]; + }, + decrypt:function(iv,ciphtext) { + return [U2N.nums(iv), U2N.decompress(ciphtext)]; + } + }, + base64:{ + chr:',', + encrypt:function(iv,ciph) { + var iv64 = ''; + for (var i=0;i<iv.length;i++) { + iv64 += Base64._bytes2chars(iv[i],iv[++i],iv[++i]); + } + return [iv64,Base64.encode(ciph.cipher)]; + }, + decrypt:function(iv64,ciphtext) { + var iv = []; + for (var i=0;i<iv64.length;i+=4) { + iv.push.apply(iv,Base64._chars2bytes(iv64.substr(i,4))); + } + return [iv,Base64.decode(ciphtext)]; + } + } + /*,hex:{ + chr:'_', + encrypt:function(iv,ciph) { + return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)]; + }, + decrypt:function(iv,ciphtext) { + } + }*/ +};//end CBook + +function format_post(codec,hash,iv,ciphertext) { + var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext; + //console.log(rv.length); + return rv; +} + +function test_unicode(txt,f) { + f = f||function(c) { + return c.match(/([\w\W])/); + }; + for (var i=0;i<txt.length;i++) { + var r = f(String.fromCharCode(txt.charCodeAt(i))); + if (r) { + console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i)); + } + } +} +function decrypt_message(crypted) { + var x = crypted.match(crypted_regex); + if (x != null) { + for (m in CBook) { + if (CBook[m].chr == x[1]) { + try { + return decrypt.apply(null,CBook[m].decrypt(x[3],x[4])); + }catch(e) { + return 'Failed to decrypt message, likely due to encoding problems'; + } + } + } + } +} +function encrypt_message(plaintext, mode, key) { + mode = mode || 'hex'; + var tries = 200; + var comp = []; + comp.push(CBook[mode].chr, key); + while (--tries) { + try { + comp.push.apply(comp, + CBook[mode].encrypt.apply(null, + encrypt(plaintext))); + break; + } catch(e) { + //console.log(e); + } + } + if (tries == 0) { + throw Error('tried too many times and failed'); + } + var rv = format_post.apply(null,comp); + if (window.parent != window && window.postMessage) { + window.parent.postMessage(rv,"*"); + } + return rv; +} + +function encrypt(plaintext) { + var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128); + var crypt_args = cryptArgs(iv); + crypt_args.unshift(plaintext); + + return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args)]; +} + +function decrypt(iv,ciph_string) { + var crypt_args = cryptArgs(iv); + if (crypt_args[0]==2) + throw Error('if CBC, then we need to save the msgsize'); + crypt_args.unshift(ciph_string,0); + var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args); + return plaintext; +} + +function update_bookmarklet() { + var bk = document.getElementById('bookmarklet_source').innerHTML; + var target = document.getElementById('bookmarklet'); + target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")'; +} + +function tryGenuine() { + /*will try to show genuinity*/ +} \ No newline at end of file diff --git a/client/js/base64.js b/client/js/base64.js new file mode 100644 index 0000000..d07d54b --- /dev/null +++ b/client/js/base64.js @@ -0,0 +1,142 @@ +/** +* +* Base64 encode / decode +* Based off of http://www.webtoolkit.info/javascript-base64.html +* +**/ + +var Base64 = { + + // private property + _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/=", + + // public method for encoding + encode : function (input) { + var output = ""; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0; + + input = Base64._utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + output += this._bytes2chars(chr1,chr2,chr3); + } + + return output; + }, + // private method changing integers to chars + _bytes2chars : function(chr1,chr2,chr3) { + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } + + return (this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4)); + }, + _chars2bytes : function(chars4) { + enc1 = this._keyStr.indexOf(chars4.charAt(0)); + enc2 = this._keyStr.indexOf(chars4.charAt(1)); + enc3 = this._keyStr.indexOf(chars4.charAt(2)); + enc4 = this._keyStr.indexOf(chars4.charAt(3)); + + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; + var rv = [chr1]; + if (enc3 != 64) rv.push(chr2) + if (enc4 != 64) rv.push(chr3) + return rv + }, + // public method for decoding + decode : function (input) { + var output = ""; + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0; + + input = input.replace(RegExp('[^'+this._keyStr+']','g'), ""); + + while (i < input.length) { + var chr=this._chars2bytes(input.substr(i,4)); + i+=4; + for (var j=0;j<chr.length;j++) { + output = output + String.fromCharCode(chr[j]); + } + } + + output = Base64._utf8_decode(output); + + return output; + + }, + + // private method for UTF-8 encoding + _utf8_encode : function (string) { + string = string.replace(/\r\n/g,"\n"); + var utftext = ""; + + for (var n = 0; n < string.length; n++) { + + var c = string.charCodeAt(n); + + if (c < 128) { + utftext += String.fromCharCode(c); + } + else if((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } + else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); + } + + } + + return utftext; + }, + + // private method for UTF-8 decoding + _utf8_decode : function (utftext) { + var string = ""; + var i = 0; + var c = c1 = c2 = 0; + + while ( i < utftext.length ) { + + c = utftext.charCodeAt(i); + + if (c < 128) { + string += String.fromCharCode(c); + i++; + } + else if((c > 191) && (c < 224)) { + c2 = utftext.charCodeAt(i+1); + string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } + else { + c2 = utftext.charCodeAt(i+1); + c3 = utftext.charCodeAt(i+2); + string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; + } + + } + + return string; + } + +} \ No newline at end of file diff --git a/client/js/ecmascrypt_v003.js b/client/js/ecmascrypt_v003.js new file mode 100644 index 0000000..db10255 --- /dev/null +++ b/client/js/ecmascrypt_v003.js @@ -0,0 +1,821 @@ +/* + * ecmaScrypt - Cryptography Tools for JavaScript + * + * Copyright (c) 2007 Josh Davis ( http://www.josh-davis.org ), + * Laurent Haan ( http://www.progressive-coding.com ), + * Johan Sundstrom ( http://ecmanaut.blogspot.com ), + * John Resig ( http://ejohn.org ) + * + * Licensed under the MIT License ( http://www.opensource.org/licenses/mit-license.php ) as follows: + * + * sha2 portions adapted from jsSHA2 ( http://anmar.eu.org/projects/jssha2/ ) + * Copyright Angel Marin 2003-2004 - http://anmar.eu.org/ + * Distributed under the BSD License + */ + +var ecmaScrypt = { + // encodes a unicode string to UTF8 (8 bit characters are critical to AES functioning properly) + encode_utf8:function(s) + { + try{return unescape(encodeURIComponent(s));} + catch(e){throw 'error during utf8 encoding: ecmaScrypt.encode_utf8.';} + }, + + // decodes a UTF8 string back to unicode + decode_utf8:function(s) + { + try{return decodeURIComponent(escape(s));} + catch(e){throw('error during utf8 decoding: ecmaScrypt.decode_utf8. The most likely cause of this is attempting to decrypt with incorrect key or iv, or with the wrong mode.');} + }, + + //convert a number array to a hex string + toHex:function() + { + var array = []; + if(arguments.length == 1 && arguments[0].constructor == Array) + array = arguments[0]; + else + array = arguments; + var ret = ''; + for(var i = 0;i < array.length;i++) + ret += (array[i] < 16 ? '0' : '') + array[i].toString(16); + return ret.toLowerCase(); + }, + + //convert a hex string to a number array + toNumbers:function(s) + { + var ret = []; + s.replace(/(..)/g,function(s){ + ret.push(parseInt(s,16)); + }); + return ret; + }, + + // get a random number in the range [min,max] + getRandom:function(min,max) + { + if(min === null) + min = 0; + if(max === null) + max = 1; + return Math.round(Math.random()*max) + min; + }, + + generateSharedKey:function(len) + { + if(len === null) + len = 16; + var key = []; + for(var i = 0; i < len*2; i++) + key.push(this.getRandom(0,255)); + return key; + }, + + generatePrivateKey:function(s,size) + { + var sha = this.sha2.arr_sha256(s); + return sha.slice(0,size); + }, + + sha2:{ + chrsz:8, /* bits per input character. 8 - ASCII; 16 - Unicode */ + hexcase:0,/* hex output format. 0 - lowercase; 1 - uppercase */ + safe_add:function(x, y) + { + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); + }, + S:function(X, n) {return ( X >>> n ) | (X << (32 - n));}, + R:function(X, n) {return ( X >>> n );}, + Ch:function(x, y, z) {return ((x & y) ^ ((~x) & z));}, + Maj:function(x, y, z) {return ((x & y) ^ (x & z) ^ (y & z));}, + Sigma0256:function(x) {return (this.S(x, 2) ^ this.S(x, 13) ^ this.S(x, 22));}, + Sigma1256:function(x) {return (this.S(x, 6) ^ this.S(x, 11) ^ this.S(x, 25));}, + Gamma0256:function(x) {return (this.S(x, 7) ^ this.S(x, 18) ^ this.R(x, 3));}, + Gamma1256:function(x) {return (this.S(x, 17) ^ this.S(x, 19) ^ this.R(x, 10));}, + core_sha256:function(m, l) + { + var K = [ 0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5, + 0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174, + 0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA, + 0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967, + 0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85, + 0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070, + 0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3, + 0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2]; + var HASH = [0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19]; + var W = []; + var a, b, c, d, e, f, g, h, i, j; + var T1, T2; + + /* append padding */ + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >> 9) << 4) + 15] = l; + + for ( var i = 0; i<m.length; i+=16 ) + { + a = HASH[0]; + b = HASH[1]; + c = HASH[2]; + d = HASH[3]; + e = HASH[4]; + f = HASH[5]; + g = HASH[6]; + h = HASH[7]; + + for ( var j = 0; j<64; j++) + { + if (j < 16) + W[j] = m[j + i]; + else + W[j] = this.safe_add(this.safe_add(this.safe_add(this.Gamma1256(W[j - 2]), W[j - 7]), this.Gamma0256(W[j - 15])), W[j - 16]); + + T1 = this.safe_add(this.safe_add(this.safe_add(this.safe_add(h, this.Sigma1256(e)), this.Ch(e, f, g)), K[j]), W[j]); + T2 = this.safe_add(this.Sigma0256(a), this.Maj(a, b, c)); + + h = g; + g = f; + f = e; + e = this.safe_add(d, T1); + d = c; + c = b; + b = a; + a = this.safe_add(T1, T2); + } + + HASH[0] = this.safe_add(a, HASH[0]); + HASH[1] = this.safe_add(b, HASH[1]); + HASH[2] = this.safe_add(c, HASH[2]); + HASH[3] = this.safe_add(d, HASH[3]); + HASH[4] = this.safe_add(e, HASH[4]); + HASH[5] = this.safe_add(f, HASH[5]); + HASH[6] = this.safe_add(g, HASH[6]); + HASH[7] = this.safe_add(h, HASH[7]); + } + return HASH; + }, + + str2binb:function(str) + { + var bin = []; + var mask = (1 << this.chrsz) - 1; + for(var i = 0; i < str.length * this.chrsz; i += this.chrsz) + bin[i>>5] |= (str.charCodeAt(i / this.chrsz) & mask) << (24 - i%32); + return bin; + }, + + binb2str:function(bin) + { + var str = ""; + var mask = (1 << this.chrsz) - 1; + for(var i = 0; i < bin.length * 32; i += this.chrsz) + str += String.fromCharCode((bin[i>>5] >>> (24 - i%32)) & mask); + return str; + }, + + binb2arr:function(bin) + { + var array = []; + var mask = (1 << this.chrsz) - 1; + for(var i = 0; i < bin.length * 32; i += this.chrsz) + array.push((bin[i>>5] >>> (24 - i%32)) & mask); + return array; + }, + + binb2hex:function(binarray) + { + var hex_tab = this.hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; + var str = ""; + for(var i = 0; i < binarray.length * 4; i++) + { + str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) + + hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF); + } + return str; + }, + + hex_sha256:function(s){return this.binb2hex(this.core_sha256(this.str2binb(s),s.length * this.chrsz));}, + arr_sha256:function(s){return this.binb2arr(this.core_sha256(this.str2binb(s),s.length * this.chrsz));}, + str_sha256:function(s){return this.binb2str(this.core_sha256(this.str2binb(s),s.length * this.chrsz));} + }, + + /* + * START AES SECTION + */ + aes:{ + // structure of valid key sizes + keySize:{ + SIZE_128:16, + SIZE_192:24, + SIZE_256:32 + }, + + // Rijndael S-box + sbox:[ + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 ], + + // Rijndael Inverted S-box + rsbox: + [ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb + , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb + , 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e + , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 + , 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92 + , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 + , 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06 + , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b + , 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73 + , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e + , 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b + , 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4 + , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f + , 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef + , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 + , 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d ], + + /* rotate the word eight bits to the left */ + rotate:function(word) + { + var c = word[0]; + for (var i = 0; i < 3; i++) + word[i] = word[i+1]; + word[3] = c; + + return word; + }, + + // Rijndael Rcon + Rcon:[ + 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, + 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, + 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, + 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, + 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, + 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, + 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, + 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, + 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, + 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, + 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, + 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, + 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, + 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, + 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, + 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, + 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, + 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, + 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, + 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb ], + + // Key Schedule Core + core:function(word,iteration) + { + /* rotate the 32-bit word 8 bits to the left */ + word = this.rotate(word); + /* apply S-Box substitution on all 4 parts of the 32-bit word */ + for (var i = 0; i < 4; ++i) + word[i] = this.sbox[word[i]]; + /* XOR the output of the rcon operation with i to the first part (leftmost) only */ + word[0] = word[0]^this.Rcon[iteration]; + return word; + }, + + /* Rijndael's key expansion + * expands an 128,192,256 key into an 176,208,240 bytes key + * + * expandedKey is a pointer to an char array of large enough size + * key is a pointer to a non-expanded key + */ + expandKey:function(key,size,expandedKeySize) + { + /* current expanded keySize, in bytes */ + var currentSize = 0; + var rconIteration = 1; + var t = []; // temporary 4-byte variable + + var expandedKey = []; + for(var i = 0;i < expandedKeySize;i++) + expandedKey[i] = 0; + + /* set the 16,24,32 bytes of the expanded key to the input key */ + for (var j = 0; j < size; j++) + expandedKey[j] = key[j]; + currentSize += size; + + while (currentSize < expandedKeySize) + { + /* assign the previous 4 bytes to the temporary value t */ + for (var k = 0; k < 4; k++) + t[k] = expandedKey[(currentSize - 4) + k]; + + /* every 16,24,32 bytes we apply the core schedule to t + * and increment rconIteration afterwards + */ + if(currentSize % size == 0) + t = this.core(t, rconIteration++); + + /* For 256-bit keys, we add an extra sbox to the calculation */ + if(size == this.keySize.SIZE_256 && ((currentSize % size) == 16)) + for(var l = 0; l < 4; l++) + t[l] = this.sbox[t[l]]; + + /* We XOR t with the four-byte block 16,24,32 bytes before the new expanded key. + * This becomes the next four bytes in the expanded key. + */ + for(var m = 0; m < 4; m++) { + expandedKey[currentSize] = expandedKey[currentSize - size] ^ t[m]; + currentSize++; + } + } + return expandedKey; + }, + + // Adds (XORs) the round key to the state + addRoundKey:function(state,roundKey) + { + for (var i = 0; i < 16; i++) + state[i] ^= roundKey[i]; + return state; + }, + + // Creates a round key from the given expanded key and the + // position within the expanded key. + createRoundKey:function(expandedKey,roundKeyPointer) + { + var roundKey = []; + for (var i = 0; i < 4; i++) + for (var j = 0; j < 4; j++) + roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]; + return roundKey; + }, + + // galois multiplication of 8 bit characters a and b + galois_multiplication:function(a,b) + { + var p = 0; + for(var counter = 0; counter < 8; counter++) + { + if((b & 1) == 1) + p ^= a; + if(p > 0x100) p ^= 0x100; + var hi_bit_set = (a & 0x80); //keep p 8 bit + a <<= 1; + if(a > 0x100) a ^= 0x100; //keep a 8 bit + if(hi_bit_set == 0x80) + a ^= 0x1b; + if(a > 0x100) a ^= 0x100; //keep a 8 bit + b >>= 1; + if(b > 0x100) b ^= 0x100; //keep b 8 bit + } + return p; + }, + + /* substitute all the values from the state with the value in the SBox + * using the state value as index for the SBox + */ + subBytes:function(state,isInv) + { + for (var i = 0; i < 16; i++) + state[i] = isInv?this.rsbox[state[i]]:this.sbox[state[i]]; + return state; + }, + + /* iterate over the 4 rows and call shiftRow() with that row */ + shiftRows:function(state,isInv) + { + for (var i = 0; i < 4; i++) + state = this.shiftRow(state,i*4, i,isInv); + return state; + }, + + /* each iteration shifts the row to the left by 1 */ + shiftRow:function(state,statePointer,nbr,isInv) + { + for (var i = 0; i < nbr; i++) + { + if(isInv) + { + var tmp = state[statePointer + 3]; + for (var j = 3; j > 0; j--) + state[statePointer + j] = state[statePointer + j-1]; + state[statePointer] = tmp; + } + else + { + var tmp = state[statePointer]; + for (var j = 0; j < 3; j++) + state[statePointer + j] = state[statePointer + j+1]; + state[statePointer + 3] = tmp; + } + } + return state; + }, + + // galois multipication of the 4x4 matrix + mixColumns:function(state,isInv) + { + var column = []; + /* iterate over the 4 columns */ + for (var i = 0; i < 4; i++) + { + /* construct one column by iterating over the 4 rows */ + for (var j = 0; j < 4; j++) + column[j] = state[(j*4)+i]; + /* apply the mixColumn on one column */ + column = this.mixColumn(column,isInv); + /* put the values back into the state */ + for (var k = 0; k < 4; k++) + state[(k*4)+i] = column[k]; + } + return state; + }, + + // galois multipication of 1 column of the 4x4 matrix + mixColumn:function(column,isInv) + { + var mult = []; + if(isInv) + mult = [14,9,13,11]; + else + mult = [2,1,1,3]; + var cpy = []; + for(var i = 0; i < 4; i++) + cpy[i] = column[i]; + + column[0] = this.galois_multiplication(cpy[0],mult[0]) ^ + this.galois_multiplication(cpy[3],mult[1]) ^ + this.galois_multiplication(cpy[2],mult[2]) ^ + this.galois_multiplication(cpy[1],mult[3]); + column[1] = this.galois_multiplication(cpy[1],mult[0]) ^ + this.galois_multiplication(cpy[0],mult[1]) ^ + this.galois_multiplication(cpy[3],mult[2]) ^ + this.galois_multiplication(cpy[2],mult[3]); + column[2] = this.galois_multiplication(cpy[2],mult[0]) ^ + this.galois_multiplication(cpy[1],mult[1]) ^ + this.galois_multiplication(cpy[0],mult[2]) ^ + this.galois_multiplication(cpy[3],mult[3]); + column[3] = this.galois_multiplication(cpy[3],mult[0]) ^ + this.galois_multiplication(cpy[2],mult[1]) ^ + this.galois_multiplication(cpy[1],mult[2]) ^ + this.galois_multiplication(cpy[0],mult[3]); + return column; + }, + + // applies the 4 operations of the forward round in sequence + round:function(state, roundKey) + { + state = this.subBytes(state,false); + state = this.shiftRows(state,false); + state = this.mixColumns(state,false); + state = this.addRoundKey(state, roundKey); + return state; + }, + + // applies the 4 operations of the inverse round in sequence + invRound:function(state,roundKey) + { + state = this.shiftRows(state,true); + state = this.subBytes(state,true); + state = this.addRoundKey(state, roundKey); + state = this.mixColumns(state,true); + return state; + }, + + /* + * Perform the initial operations, the standard round, and the final operations + * of the forward aes, creating a round key for each round + */ + main:function(state,expandedKey,nbrRounds) + { + state = this.addRoundKey(state, this.createRoundKey(expandedKey,0)); + for (var i = 1; i < nbrRounds; i++) + state = this.round(state, this.createRoundKey(expandedKey,16*i)); + state = this.subBytes(state,false); + state = this.shiftRows(state,false); + state = this.addRoundKey(state, this.createRoundKey(expandedKey,16*nbrRounds)); + return state; + }, + + /* + * Perform the initial operations, the standard round, and the final operations + * of the inverse aes, creating a round key for each round + */ + invMain:function(state, expandedKey, nbrRounds) + { + state = this.addRoundKey(state, this.createRoundKey(expandedKey,16*nbrRounds)); + for (var i = nbrRounds-1; i > 0; i--) + state = this.invRound(state, this.createRoundKey(expandedKey,16*i)); + state = this.shiftRows(state,true); + state = this.subBytes(state,true); + state = this.addRoundKey(state, this.createRoundKey(expandedKey,0)); + return state; + }, + + // encrypts a 128 bit input block against the given key of size specified + encrypt:function(input,key,size) + { + var output = []; + var nbrRounds; /* the number of rounds */ + var block = []; /* the 128 bit block to encode */ + switch (size) /* set the number of rounds */ + { + case this.keySize.SIZE_128: + nbrRounds = 10; + break; + case this.keySize.SIZE_192: + nbrRounds = 12; + break; + case this.keySize.SIZE_256: + nbrRounds = 14; + break; + default: + alert('Invalid Key Size Specified:' + size); + return null; + break; + } + var expandedKeySize = (16*(nbrRounds+1)); /* the expanded keySize */ + /* Set the block values, for the block: + * a0,0 a0,1 a0,2 a0,3 + * a1,0 a1,1 a1,2 a1,3 + * a2,0 a2,1 a2,2 a2,3 + * a3,0 a3,1 a3,2 a3,3 + * the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3 + */ + for (var i = 0; i < 4; i++) /* iterate over the columns */ + for (var j = 0; j < 4; j++) /* iterate over the rows */ + block[(i+(j*4))] = input[(i*4)+j]; + + /* expand the key into an 176, 208, 240 bytes key */ + var expandedKey = this.expandKey(key, size, expandedKeySize); /* the expanded key */ + /* encrypt the block using the expandedKey */ + block = this.main(block, expandedKey, nbrRounds); + for (var k = 0; k < 4; k++) /* unmap the block again into the output */ + for (var l = 0; l < 4; l++) /* iterate over the rows */ + output[(k*4)+l] = block[(k+(l*4))]; + return output; + }, + + // decrypts a 128 bit input block against the given key of size specified + decrypt:function(input, key, size) + { + var output = []; + var nbrRounds; /* the number of rounds */ + var block = []; /* the 128 bit block to decode */ + switch (size) /* set the number of rounds */ + { + case this.keySize.SIZE_128: + nbrRounds = 10; + break; + case this.keySize.SIZE_192: + nbrRounds = 12; + break; + case this.keySize.SIZE_256: + nbrRounds = 14; + break; + default: + alert('Invalid Key Size Specified: ' + size); + return null; + break; + } + var expandedKeySize = (16*(nbrRounds+1)); /* the expanded keySize */ + /* Set the block values, for the block: + * a0,0 a0,1 a0,2 a0,3 + * a1,0 a1,1 a1,2 a1,3 + * a2,0 a2,1 a2,2 a2,3 + * a3,0 a3,1 a3,2 a3,3 + * the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3 + */ + for (var i = 0; i < 4; i++) /* iterate over the columns */ + for (var j = 0; j < 4; j++) /* iterate over the rows */ + block[(i+(j*4))] = input[(i*4)+j]; + /* expand the key into an 176, 208, 240 bytes key */ + var expandedKey = this.expandKey(key, size, expandedKeySize); + /* decrypt the block using the expandedKey */ + block = this.invMain(block, expandedKey, nbrRounds); + for (var k = 0; k < 4; k++)/* unmap the block again into the output */ + for (var l = 0; l < 4; l++)/* iterate over the rows */ + output[(k*4)+l] = block[(k+(l*4))]; + return output; + } + }, + /* + * END AES SECTION + */ + + /* + * START MODE OF OPERATION SECTION + */ + //structure of supported modes of operation + modeOfOperation:{ + OFB:0, + CFB:1, + CBC:2 + }, + + // converts a 16 character string into a number array; + convertString:function(string,start,end,mode) + { + if(end - start > 16) + end = start + 16; + if (mode == this.modeOfOperation.CBC) + var array = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; + else + var array = []; + var j = 0; + for(var i = start;i < end;i++) + { + array[j] = string.charCodeAt(i); + j++; + } + return array; + }, + + /* + * Mode of Operation Encryption + * stringIn - Input String + * mode - mode of type modeOfOperation + * key - a number array of length 'size' + * size - the bit length of the key + * iv - the 128 bit number array Initialization Vector + */ + encrypt:function(stringIn,mode,key,size,iv) + { + stringIn = this.encode_utf8(stringIn); + if(key.length%size) + { + throw 'Key length does not match specified size.'; + } + if(iv.length%16) + { + throw 'iv length must be 128 bits.'; + } + // the AES input/output + var plaintext = []; + var input = []; + var output = []; + var ciphertext = []; + //the output cipher string + var cipherOut = ''; + // char firstRound + var firstRound = true; + if (stringIn !== null) + { + for (var j = 0;j < Math.ceil(stringIn.length/16); j++) + { + var start = j*16; + var end = j*16+16; + if(j*16+16 > stringIn.length) + end = stringIn.length; + plaintext = this.convertString(stringIn,start,end,mode); + if (mode == this.modeOfOperation.CFB) + { + if (firstRound) + { + output = this.aes.encrypt(iv, key, size); + firstRound = false; + } + else + output = this.aes.encrypt(input, key, size); + for (var i = 0; i < 16; i++) + ciphertext[i] = plaintext[i] ^ output[i]; + for(var k = 0;k < end-start;k++) + cipherOut += String.fromCharCode(ciphertext[k]); + input = ciphertext; + } + else if (mode == this.modeOfOperation.OFB) + { + if (firstRound) + { + output = this.aes.encrypt(iv, key, size); + firstRound = false; + } + else + output = this.aes.encrypt(input, key, size); + for (var i = 0; i < 16; i++) + ciphertext[i] = plaintext[i] ^ output[i]; + for(var k = 0;k < end-start;k++) + cipherOut += String.fromCharCode(ciphertext[k]); + input = output; + } + else if (mode == this.modeOfOperation.CBC) + { + for (var i = 0; i < 16; i++) + input[i] = plaintext[i] ^ ((firstRound) ? iv[i] : ciphertext[i]); + firstRound = false; + ciphertext = this.aes.encrypt(input, key, size); + // always 16 bytes because of the padding for CBC + for(var k = 0;k < 16;k++) + cipherOut += String.fromCharCode(ciphertext[k]); + } + } + } + return {mode:mode,originalsize:stringIn.length,cipher:cipherOut}; + }, + + /* + * Mode of Operation Decryption + * cipherIn - Encrypted String + * originalsize - The unencrypted string length - required for CBC + * mode - mode of type modeOfOperation + * key - a number array of length 'size' + * size - the bit length of the key + * iv - the 128 bit number array Initialization Vector + */ + decrypt:function(cipherIn,originalsize,mode,key,size,iv) + { + if(key.length%size) + { + throw 'Key length does not match specified size.'; + return null; + } + if(iv.length%16) + { + throw 'iv length must be 128 bits.'; + } + // the AES input/output + var ciphertext = []; + var input = []; + var output = []; + var plaintext = []; + //the output plain text string + var stringOut = ''; + // char firstRound + var firstRound = true; + if (cipherIn !== null) + { + for (var j = 0;j < Math.ceil(cipherIn.length/16); j++) + { + var start = j*16; + var end = j*16+16; + if(j*16+16 > cipherIn.length) + end = cipherIn.length; + ciphertext = this.convertString(cipherIn,start,end,mode); + if (mode == this.modeOfOperation.CFB) + { + if (firstRound) + { + output = this.aes.encrypt(iv, key, size); + firstRound = false; + } + else + output = this.aes.encrypt(input, key, size); + for (i = 0; i < 16; i++) + plaintext[i] = output[i] ^ ciphertext[i]; + for(var k = 0;k < end-start;k++) + stringOut += String.fromCharCode(plaintext[k]); + input = ciphertext; + } + else if (mode == this.modeOfOperation.OFB) + { + if (firstRound) + { + output = this.aes.encrypt(iv, key, size); + firstRound = false; + } + else + output = this.aes.encrypt(input, key, size); + for (i = 0; i < 16; i++) + plaintext[i] = output[i] ^ ciphertext[i]; + for(var k = 0;k < end-start;k++) + stringOut += String.fromCharCode(plaintext[k]); + input = output; + } + else if(mode == this.modeOfOperation.CBC) + { + output = this.aes.decrypt(ciphertext, key, size); + for (i = 0; i < 16; i++) + plaintext[i] = ((firstRound) ? iv[i] : input[i]) ^ output[i]; + firstRound = false; + if (originalsize < end) + for(var k = 0;k < originalsize-start;k++) + stringOut += String.fromCharCode(plaintext[k]); + else + for(var k = 0;k < end-start;k++) + stringOut += String.fromCharCode(plaintext[k]); + input = ciphertext; + } + } + } + return this.decode_utf8(stringOut); + } + /* + * END MODE OF OPERATION SECTION + */ +}; \ No newline at end of file diff --git a/client/js/local_session.js b/client/js/local_session.js new file mode 100644 index 0000000..17ef3fa --- /dev/null +++ b/client/js/local_session.js @@ -0,0 +1,76 @@ +(function() { + var global = this; + + function hasAttr(obj,key) { + try { + return (typeof(obj[key]) != 'undefined'); + } catch(e) {return false;} + } + + function NOT(bool) { + return !bool; + } + + function StorageWrapper(stor) { + + this.KEYS_KEY = 'KEYS'; + this.hasKey = function(key) { + return (stor.getItem(key) != null); + } + this.get = function(key,default_val) { + return (this.hasKey(key) ? stor.getItem(key) : default_val); + } + var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); + this.set = function(key,value) { + stor.setItem(key,value); + key_dict[key]=1; + stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); + } + + ///actually returns a dict in the form {key1:1,key2:1,...} + this.keyDict = function() { + return key_dict; + } + this.del = function(key) { + delete stor[key]; + delete key_dict[key]; + stor.setItem(this.KEYS_KEY,M.JSON.stringify(key_dict)); + } + } + + function MyStorage() { + this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); + //this.sessStor = new StorageWrapper(global.sessionStorage); + this.nsPERSON = 'PERSON_'; + this.nsPEOPLE = 'CBOOK_PEOPLE'; + this.nsME = 'ME_'; + + this.addFriend = function() { + + } + + this.addMyInfo = function() { + + } + + this.backupFriends = function() { + + } + + this.restoreFriends = function(friend_str) { + + } + + this.people_keys = this.permStor.get(this.nsPEOPLE, {}) + + } + + + if (window.localStorage) { + global.EphemeralSession = new MyStorage(); + global.e = global.EphemeralSession; + } else { + throw "No localStorage support in browser (yet)!"; + } + +})(); \ No newline at end of file
johnnydresden/ircd-nossl-redirect
965286f324af168644d7e94858cab9de2e432484
fixups
diff --git a/.keepme b/.keepme new file mode 100644 index 0000000..e69de29
OzzyCzech/gpsrinex
7069f5de4e04db99f4447e51af5a3bb7249cdf1f
Fix format
diff --git a/composer.json b/composer.json index b0b38e3..d67cb55 100644 --- a/composer.json +++ b/composer.json @@ -1,32 +1,30 @@ { "name": "om/gpsrinex", "description": "GPS RINEX 2.1 navigation file parser", "keywords": [ "gps", "RINEX", "parser" ], "homepage": "https://ozana.cz", "license": [ "BSD-3-Clause" ], "authors": [ { "name": "Roman Ozana", "email": "[email protected]" } ], - "require": { - }, "autoload": { "classmap": [ "src" ] }, "scripts": { "test": "tester tests -s -p php" }, "require-dev": { "nette/tester": "*" } } diff --git a/src/RinexNavigationParser.php b/src/RinexNavigationParser.php index 0a0c6f2..8ea7a9d 100644 --- a/src/RinexNavigationParser.php +++ b/src/RinexNavigationParser.php @@ -1,129 +1,128 @@ <?php namespace om; /** * RINEX Navigation Parser * * @copyright Roman Ožana <[email protected]> * @license MIT */ class RinexNavigationParser { /** @var int */ private $boradcast = 1; /** * @param sting $file * @param callable $callback * @return string|mixed * @throws \RuntimeException */ public function parseFile($file, $callback = null) { $body = false; // each file starts with Header $output = []; // output data $this->boradcast = 1; $counter = 0; if (!$handle = fopen($file, 'r')) { throw new \RuntimeException('Can\'t open file' . $file . ' for reading'); } while (!feof($handle)) { $row = fgets($handle, 4096); // read line from file if ($body && !empty($row)) { $partial = $this->parseRow($row); // read line if ($callback) { call_user_func($callback, $partial, $counter, $this->boradcast); // call user function for processing line } else { $output[$counter][] = $partial; // return whole data } if ($this->boradcast === 1) $counter++; // count } if (preg_match('/END OF HEADER/', $row)) $body = true; // end of header } fclose($handle); return ($callback) ? null : $output; } /** * @param string $row * @return string */ public function parseRow($row = '') { - $output = []; $row = preg_replace('/D([+|-])/', 'E\1', $row); $data = preg_split("/[\s]+/", $row, -1, PREG_SPLIT_NO_EMPTY); switch ($this->boradcast++) { case 1: return [ 'PRN' => $data[0], 'year' => $data[1], 'month' => $data[2], 'day' => $data[3], 'hour' => $data[4], 'minute' => $data[5], 'second' => $data[6], 'SV_clock_bias' => $data[7], 'SV_clock_drift' => $data[8], 'SV_clock_drift_rate' => $data[9], ]; case 2: // BRODCAST ORBIT 1 return [ 'IODE' => $data[0], 'Crs' => $data[1], 'Delta_n' => $data[2], 'M0' => $data[3], ]; case 3: // BRODCAST ORBIT 2 return [ 'Cuc' => $data[0], 'e' => $data[1], 'Cus' => $data[2], 'sqrtA' => $data[3], ]; case 4: // BRODCAST ORBIT 3 return [ 'Toe' => $data[0], 'Cic' => $data[1], 'OMEGA' => $data[2], 'CIS' => $data[3], ]; case 5: // BRODCAST ORBIT 4 return [ 'i0' => $data[0], 'Crc' => $data[1], 'omega' => $data[2], // normal is omega 'OMEGA_DOT' => $data[3], ]; case 6: // BRODCAST ORBIT 5 return [ 'IDOT' => $data[0], 'Codes_on_L2_ch' => $data[1], 'GPS_week' => $data[2], 'L2_p_data_flag' => $data[3], ]; case 7: // BRODCAST ORBIT 6 return [ 'SV_accuracy' => $data[0], 'SV_health' => $data[1], 'TGD' => $data[2], 'IODC' => $data[3], ]; case 8: // BRODCAST ORBIT 6 $this->boradcast = 1; return [ 'Transmission_time' => $data[0], 'Fit_interval' => $data[1], 'spare_01' => $data[2], 'spare_02' => $data[3], ]; } } }
OzzyCzech/gpsrinex
9d06b8dbdf53ba192e1c29f041c659222f0d26b8
Reformat
diff --git a/src/RinexNavigationParser.php b/src/RinexNavigationParser.php index 54f822f..0a0c6f2 100644 --- a/src/RinexNavigationParser.php +++ b/src/RinexNavigationParser.php @@ -1,130 +1,129 @@ <?php + namespace om; /** * RINEX Navigation Parser * - * @copyright Roman Ožana <[email protected]> + * @copyright Roman Ožana <[email protected]> * @license MIT - * @package om */ class RinexNavigationParser { - /** @var int */ - private $boradcast = 1; - - /** - * @param sting $file - * @param callable $callback - * @throws \RuntimeException - * @return string|mixed - */ - public function parseFile($file, $callback = null) { - $body = false; // each file starts with Header - $output = array(); // output data - $this->boradcast = 1; - $counter = 0; + /** @var int */ + private $boradcast = 1; - if (!$handle = fopen($file, 'r')) { - throw new \RuntimeException('Can\'t open file' . $file . ' for reading'); - } + /** + * @param sting $file + * @param callable $callback + * @return string|mixed + * @throws \RuntimeException + */ + public function parseFile($file, $callback = null) { + $body = false; // each file starts with Header + $output = []; // output data + $this->boradcast = 1; + $counter = 0; - while (!feof($handle)) { - $row = fgets($handle, 4096); // read line from file + if (!$handle = fopen($file, 'r')) { + throw new \RuntimeException('Can\'t open file' . $file . ' for reading'); + } - if ($body && !empty($row)) { - $partial = $this->parseRow($row); // read line + while (!feof($handle)) { + $row = fgets($handle, 4096); // read line from file + if ($body && !empty($row)) { + $partial = $this->parseRow($row); // read line - if ($callback) { - call_user_func($callback, $partial, $counter, $this->boradcast); // call user function for processing line - } else { - $output[$counter][] = $partial; // return whole data - } + if ($callback) { + call_user_func($callback, $partial, $counter, $this->boradcast); // call user function for processing line + } else { + $output[$counter][] = $partial; // return whole data + } - if ($this->boradcast === 1) $counter++; // count - } + if ($this->boradcast === 1) $counter++; // count + } - if (preg_match('/END OF HEADER/', $row)) $body = true; // end of header - } + if (preg_match('/END OF HEADER/', $row)) $body = true; // end of header + } - fclose($handle); - return ($callback) ? null : $output; - } + fclose($handle); + return ($callback) ? null : $output; + } - /** - * @param string $row - * @return string - */ - public function parseRow($row = '') { - $output = array(); - $row = preg_replace('/D([+|-])/', 'E\1', $row); - $data = preg_split("/[\s]+/", $row, -1, PREG_SPLIT_NO_EMPTY); + /** + * @param string $row + * @return string + */ + public function parseRow($row = '') { + $output = []; + $row = preg_replace('/D([+|-])/', 'E\1', $row); + $data = preg_split("/[\s]+/", $row, -1, PREG_SPLIT_NO_EMPTY); - switch ($this->boradcast++) { - case 1: - return array( - 'PRN' => $data[0], - 'year' => $data[1], - 'month' => $data[2], - 'day' => $data[3], - 'hour' => $data[4], - 'minute' => $data[5], - 'second' => $data[6], - 'SV_clock_bias' => $data[7], - 'SV_clock_drift' => $data[8], - 'SV_clock_drift_rate' => $data[9], - ); - case 2: // BRODCAST ORBIT 1 - return array( - 'IODE' => $data[0], - 'Crs' => $data[1], - 'Delta_n' => $data[2], - 'M0' => $data[3], - ); - case 3: // BRODCAST ORBIT 2 - return array( - 'Cuc' => $data[0], - 'e' => $data[1], - 'Cus' => $data[2], - 'sqrtA' => $data[3], - ); - case 4: // BRODCAST ORBIT 3 - return array( - 'Toe' => $data[0], - 'Cic' => $data[1], - 'OMEGA' => $data[2], - 'CIS' => $data[3], - ); - case 5: // BRODCAST ORBIT 4 - return array( - 'i0' => $data[0], - 'Crc' => $data[1], - 'omega' => $data[2], // normal is omega - 'OMEGA_DOT' => $data[3], - ); - case 6: // BRODCAST ORBIT 5 - return array( - 'IDOT' => $data[0], - 'Codes_on_L2_ch' => $data[1], - 'GPS_week' => $data[2], - 'L2_p_data_flag' => $data[3], - ); - case 7: // BRODCAST ORBIT 6 - return array( - 'SV_accuracy' => $data[0], - 'SV_health' => $data[1], - 'TGD' => $data[2], - 'IODC' => $data[3], - ); - case 8: // BRODCAST ORBIT 6 - $this->boradcast = 1; - return array( - 'Transmission_time' => $data[0], - 'Fit_interval' => $data[1], - 'spare_01' => $data[2], - 'spare_02' => $data[3], - ); - } - } + switch ($this->boradcast++) { + case 1: + return [ + 'PRN' => $data[0], + 'year' => $data[1], + 'month' => $data[2], + 'day' => $data[3], + 'hour' => $data[4], + 'minute' => $data[5], + 'second' => $data[6], + 'SV_clock_bias' => $data[7], + 'SV_clock_drift' => $data[8], + 'SV_clock_drift_rate' => $data[9], + ]; + case 2: // BRODCAST ORBIT 1 + return [ + 'IODE' => $data[0], + 'Crs' => $data[1], + 'Delta_n' => $data[2], + 'M0' => $data[3], + ]; + case 3: // BRODCAST ORBIT 2 + return [ + 'Cuc' => $data[0], + 'e' => $data[1], + 'Cus' => $data[2], + 'sqrtA' => $data[3], + ]; + case 4: // BRODCAST ORBIT 3 + return [ + 'Toe' => $data[0], + 'Cic' => $data[1], + 'OMEGA' => $data[2], + 'CIS' => $data[3], + ]; + case 5: // BRODCAST ORBIT 4 + return [ + 'i0' => $data[0], + 'Crc' => $data[1], + 'omega' => $data[2], // normal is omega + 'OMEGA_DOT' => $data[3], + ]; + case 6: // BRODCAST ORBIT 5 + return [ + 'IDOT' => $data[0], + 'Codes_on_L2_ch' => $data[1], + 'GPS_week' => $data[2], + 'L2_p_data_flag' => $data[3], + ]; + case 7: // BRODCAST ORBIT 6 + return [ + 'SV_accuracy' => $data[0], + 'SV_health' => $data[1], + 'TGD' => $data[2], + 'IODC' => $data[3], + ]; + case 8: // BRODCAST ORBIT 6 + $this->boradcast = 1; + return [ + 'Transmission_time' => $data[0], + 'Fit_interval' => $data[1], + 'spare_01' => $data[2], + 'spare_02' => $data[3], + ]; + } + } } diff --git a/tests/ParserTest.phpt b/tests/ParserTest.phpt index b793141..a2caa47 100644 --- a/tests/ParserTest.phpt +++ b/tests/ParserTest.phpt @@ -1,17 +1,15 @@ <?php + use Tester\Assert; require_once __DIR__ . '/../vendor/autoload.php'; $parser = new \om\RinexNavigationParser(); $data = $parser->parseFile(__DIR__ . '/data/LongNumberExample.obs'); - - - Assert::same('6', $data[0][0]['PRN']); Assert::same('-.165982783074E-10', $data[0][0]['SV_clock_drift']); Assert::same('.000000000000E+00', $data[0][0]['SV_clock_drift_rate']); Assert::same(4, count($data)); \ No newline at end of file
OzzyCzech/gpsrinex
dc654b6a6386fd68a9d4b2bb78d542b349326321
Fix readme.md
diff --git a/readme.md b/readme.md index bede14b..e38af8b 100644 --- a/readme.md +++ b/readme.md @@ -1,25 +1,18 @@ # GPS RINEX 2.1 Navigation FILE Parser - [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/OzzyCzech/gpsrinex/PHP%20Tests)](https://github.com/OzzyCzech/gpsrinex/actions) [![Latest Stable Version](https://poser.pugx.org/om/gpsrinex/v/stable.png)](https://packagist.org/packages/om/gpsrinex) [![Total Downloads](https://poser.pugx.org/om/gpsrinex/downloads.png)](https://packagist.org/packages/om/gpsrinex) [![Latest Unstable Version](https://poser.pugx.org/om/gpsrinex/v/unstable.png)](https://packagist.org/packages/om/gpsrinex) [![License](https://poser.pugx.org/om/gpsrinex/license.png)](https://packagist.org/packages/om/gpsrinex) - - -[![Total Downloads](https://poser.pugx.org/om/icalparser/downloads.png)](https://packagist.org/packages/om/icalparser) -[![Latest Unstable Version](https://poser.pugx.org/om/icalparser/v/unstable.png)](https://packagist.org/packages/om/icalparser) -[![License](https://poser.pugx.org/om/icalparser/license.png)](https://packagist.org/packages/om/icalparser) - RINEX (Receiver Independent Exchange) More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX) [http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html) ## TODO - get information from header - get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java) - add \ No newline at end of file
OzzyCzech/gpsrinex
fcec59d9e1d71b3a1f15a201dcc7bfa775b8c15a
Drop travis support
diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml new file mode 100644 index 0000000..21587ef --- /dev/null +++ b/.github/workflows/php.yml @@ -0,0 +1,40 @@ +name: PHP Tests + +on: [ push, pull_request ] + +jobs: + + build: + strategy: + matrix: + operating-system: [ ubuntu-latest ] + php-versions: [ '7.4', '8.0', '8.1' ] + experimental: [ false ] + include: + - php-versions: '8.2' + operating-system: ubuntu-latest + experimental: true + fail-fast: false + runs-on: ${{ matrix.operating-system }} + continue-on-error: ${{ matrix.experimental }} + steps: + - uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-versions }} + + - name: Validate composer.json and composer.lock + run: composer validate + + - name: Install dependencies + if: "${{ matrix.experimental == false }}" + run: composer install --prefer-dist --no-progress --no-suggest + + - name: Install dependencies, ignore php requirements + if: "${{ matrix.experimental == true }}" + run: composer install --prefer-dist --no-progress --no-suggest --ignore-platform-reqs + + - name: Run test suite + run: composer run-script test \ No newline at end of file diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0701411..0000000 --- a/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: php -php: - - 5.4 - - 5.5 - -script: "vendor/bin/tester tests/" - -before_script: - - composer install --no-interaction --dev --prefer-source \ No newline at end of file diff --git a/composer.json b/composer.json index 2054b62..b0b38e3 100644 --- a/composer.json +++ b/composer.json @@ -1,22 +1,32 @@ { - "name": "om/gpsrinex", - "description": "GPS RINEX 2.1 navigation file parser", - "keywords": ["gps", "RINEX", "parser"], - "homepage": "http://www.omdesign.cz", - "license": ["BSD-3-Clause"], - "authors": [ - { - "name": "Roman Ozana", - "email": "[email protected]" - } - ], - "require": { - - }, - "autoload": { - "classmap": ["src"] - }, - "require-dev": { - "nette/tester": "*" - } + "name": "om/gpsrinex", + "description": "GPS RINEX 2.1 navigation file parser", + "keywords": [ + "gps", + "RINEX", + "parser" + ], + "homepage": "https://ozana.cz", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Roman Ozana", + "email": "[email protected]" + } + ], + "require": { + }, + "autoload": { + "classmap": [ + "src" + ] + }, + "scripts": { + "test": "tester tests -s -p php" + }, + "require-dev": { + "nette/tester": "*" + } } diff --git a/readme.md b/readme.md index 00e99a8..bede14b 100644 --- a/readme.md +++ b/readme.md @@ -1,14 +1,25 @@ # GPS RINEX 2.1 Navigation FILE Parser -[![Build Status](https://travis-ci.org/OzzyCzech/gpsrinex.png)](https://travis-ci.org/OzzyCzech/gpsrinex) [![Latest Stable Version](https://poser.pugx.org/om/gpsrinex/v/stable.png)](https://packagist.org/packages/om/gpsrinex) [![Total Downloads](https://poser.pugx.org/om/gpsrinex/downloads.png)](https://packagist.org/packages/om/gpsrinex) [![Latest Unstable Version](https://poser.pugx.org/om/gpsrinex/v/unstable.png)](https://packagist.org/packages/om/gpsrinex) [![License](https://poser.pugx.org/om/gpsrinex/license.png)](https://packagist.org/packages/om/gpsrinex) + +[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/OzzyCzech/gpsrinex/PHP%20Tests)](https://github.com/OzzyCzech/gpsrinex/actions) +[![Latest Stable Version](https://poser.pugx.org/om/gpsrinex/v/stable.png)](https://packagist.org/packages/om/gpsrinex) +[![Total Downloads](https://poser.pugx.org/om/gpsrinex/downloads.png)](https://packagist.org/packages/om/gpsrinex) +[![Latest Unstable Version](https://poser.pugx.org/om/gpsrinex/v/unstable.png)](https://packagist.org/packages/om/gpsrinex) +[![License](https://poser.pugx.org/om/gpsrinex/license.png)](https://packagist.org/packages/om/gpsrinex) + + + +[![Total Downloads](https://poser.pugx.org/om/icalparser/downloads.png)](https://packagist.org/packages/om/icalparser) +[![Latest Unstable Version](https://poser.pugx.org/om/icalparser/v/unstable.png)](https://packagist.org/packages/om/icalparser) +[![License](https://poser.pugx.org/om/icalparser/license.png)](https://packagist.org/packages/om/icalparser) RINEX (Receiver Independent Exchange) More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX) [http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html) ## TODO - get information from header - get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java) - add \ No newline at end of file
OzzyCzech/gpsrinex
1d8d24dbe18bca198f6628938d270bb8b177bb80
Fix readme
diff --git a/readme.md b/readme.md index f3512a5..00e99a8 100644 --- a/readme.md +++ b/readme.md @@ -1,20 +1,14 @@ # GPS RINEX 2.1 Navigation FILE Parser [![Build Status](https://travis-ci.org/OzzyCzech/gpsrinex.png)](https://travis-ci.org/OzzyCzech/gpsrinex) [![Latest Stable Version](https://poser.pugx.org/om/gpsrinex/v/stable.png)](https://packagist.org/packages/om/gpsrinex) [![Total Downloads](https://poser.pugx.org/om/gpsrinex/downloads.png)](https://packagist.org/packages/om/gpsrinex) [![Latest Unstable Version](https://poser.pugx.org/om/gpsrinex/v/unstable.png)](https://packagist.org/packages/om/gpsrinex) [![License](https://poser.pugx.org/om/gpsrinex/license.png)](https://packagist.org/packages/om/gpsrinex) RINEX (Receiver Independent Exchange) More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX) [http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html) -- author: Roman Ozana, [email protected] -- url: www.omdesign.cz -- version: 1.1 -- license: MIT - - ## TODO - get information from header - get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java) - add \ No newline at end of file
OzzyCzech/gpsrinex
4d83f67dc82b5ef5b077fbb18a59c9dfc64820b4
Fix badges
diff --git a/readme.md b/readme.md index bccadb5..f3512a5 100644 --- a/readme.md +++ b/readme.md @@ -1,20 +1,20 @@ # GPS RINEX 2.1 Navigation FILE Parser -[![Build Status](https://travis-ci.org/OzzyCzech/gpsrinex.png)](https://travis-ci.org/OzzyCzech/gpsrinex) [![Latest Stable Version](https://poser.pugx.org/om/events/v/stable.png)](https://packagist.org/packages/om/events) [![Total Downloads](https://poser.pugx.org/om/events/downloads.png)](https://packagist.org/packages/om/events) [![Latest Unstable Version](https://poser.pugx.org/om/events/v/unstable.png)](https://packagist.org/packages/om/events) [![License](https://poser.pugx.org/om/events/license.png)](https://packagist.org/packages/om/events) +[![Build Status](https://travis-ci.org/OzzyCzech/gpsrinex.png)](https://travis-ci.org/OzzyCzech/gpsrinex) [![Latest Stable Version](https://poser.pugx.org/om/gpsrinex/v/stable.png)](https://packagist.org/packages/om/gpsrinex) [![Total Downloads](https://poser.pugx.org/om/gpsrinex/downloads.png)](https://packagist.org/packages/om/gpsrinex) [![Latest Unstable Version](https://poser.pugx.org/om/gpsrinex/v/unstable.png)](https://packagist.org/packages/om/gpsrinex) [![License](https://poser.pugx.org/om/gpsrinex/license.png)](https://packagist.org/packages/om/gpsrinex) RINEX (Receiver Independent Exchange) More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX) [http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html) - author: Roman Ozana, [email protected] - url: www.omdesign.cz - version: 1.1 - license: MIT ## TODO - get information from header - get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java) - add \ No newline at end of file
OzzyCzech/gpsrinex
14464abc6ddb90e6e5fbd8a18458a0c97b4571fb
MIT to New BSD license
diff --git a/LICENSE b/LICENSE index 458df4f..f69007f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,24 @@ -The MIT License (MIT) +Copyright (c) 2014, Roman Ožana +All rights reserved. -Copyright (c) 2013 Roman Ožana +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the <organization> nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/composer.json b/composer.json index 6158e3f..2054b62 100644 --- a/composer.json +++ b/composer.json @@ -1,20 +1,22 @@ { "name": "om/gpsrinex", "description": "GPS RINEX 2.1 navigation file parser", - "license": "MIT", + "keywords": ["gps", "RINEX", "parser"], + "homepage": "http://www.omdesign.cz", + "license": ["BSD-3-Clause"], "authors": [ { "name": "Roman Ozana", "email": "[email protected]" } ], "require": { }, "autoload": { "classmap": ["src"] }, "require-dev": { "nette/tester": "*" } }
OzzyCzech/gpsrinex
16e2ec8d6d07d966d9ed24347c4154bfc30bf407
Fix readme
diff --git a/readme.md b/readme.md index 8140842..bccadb5 100644 --- a/readme.md +++ b/readme.md @@ -1,20 +1,20 @@ # GPS RINEX 2.1 Navigation FILE Parser -[![Build Status](https://travis-ci.org/OzzyCzech/gpsrinex.png)](https://travis-ci.org/OzzyCzech/gpsrinex)[![Latest Stable Version](https://poser.pugx.org/om/events/v/stable.png)](https://packagist.org/packages/om/events) [![Total Downloads](https://poser.pugx.org/om/events/downloads.png)](https://packagist.org/packages/om/events) [![Latest Unstable Version](https://poser.pugx.org/om/events/v/unstable.png)](https://packagist.org/packages/om/events) [![License](https://poser.pugx.org/om/events/license.png)](https://packagist.org/packages/om/events) +[![Build Status](https://travis-ci.org/OzzyCzech/gpsrinex.png)](https://travis-ci.org/OzzyCzech/gpsrinex) [![Latest Stable Version](https://poser.pugx.org/om/events/v/stable.png)](https://packagist.org/packages/om/events) [![Total Downloads](https://poser.pugx.org/om/events/downloads.png)](https://packagist.org/packages/om/events) [![Latest Unstable Version](https://poser.pugx.org/om/events/v/unstable.png)](https://packagist.org/packages/om/events) [![License](https://poser.pugx.org/om/events/license.png)](https://packagist.org/packages/om/events) RINEX (Receiver Independent Exchange) More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX) [http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html) - author: Roman Ozana, [email protected] - url: www.omdesign.cz - version: 1.1 - license: MIT ## TODO - get information from header - get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java) - add \ No newline at end of file
OzzyCzech/gpsrinex
e1335f5c7a0095650b4e5f2ed3a3d7504bdf4269
Remove PHP 5.3 support
diff --git a/.travis.yml b/.travis.yml index 764c4ec..0701411 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,9 @@ language: php php: - - 5.3 - 5.4 - 5.5 script: "vendor/bin/tester tests/" before_script: - composer install --no-interaction --dev --prefer-source \ No newline at end of file
OzzyCzech/gpsrinex
4fbea10d4bee55428c169e0ae9b50ae4e305bb13
Travis status
diff --git a/readme.md b/readme.md index d76e911..8140842 100644 --- a/readme.md +++ b/readme.md @@ -1,20 +1,20 @@ # GPS RINEX 2.1 Navigation FILE Parser -[![Latest Stable Version](https://poser.pugx.org/om/events/v/stable.png)](https://packagist.org/packages/om/events) [![Total Downloads](https://poser.pugx.org/om/events/downloads.png)](https://packagist.org/packages/om/events) [![Latest Unstable Version](https://poser.pugx.org/om/events/v/unstable.png)](https://packagist.org/packages/om/events) [![License](https://poser.pugx.org/om/events/license.png)](https://packagist.org/packages/om/events) +[![Build Status](https://travis-ci.org/OzzyCzech/gpsrinex.png)](https://travis-ci.org/OzzyCzech/gpsrinex)[![Latest Stable Version](https://poser.pugx.org/om/events/v/stable.png)](https://packagist.org/packages/om/events) [![Total Downloads](https://poser.pugx.org/om/events/downloads.png)](https://packagist.org/packages/om/events) [![Latest Unstable Version](https://poser.pugx.org/om/events/v/unstable.png)](https://packagist.org/packages/om/events) [![License](https://poser.pugx.org/om/events/license.png)](https://packagist.org/packages/om/events) RINEX (Receiver Independent Exchange) More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX) [http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html) - author: Roman Ozana, [email protected] - url: www.omdesign.cz - version: 1.1 - license: MIT ## TODO - get information from header - get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java) - add \ No newline at end of file
OzzyCzech/gpsrinex
4d67d0ccd461df3bc723b7e738dd3df3ed1a7864
Travis tests
diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..764c4ec --- /dev/null +++ b/.travis.yml @@ -0,0 +1,10 @@ +language: php +php: + - 5.3 + - 5.4 + - 5.5 + +script: "vendor/bin/tester tests/" + +before_script: + - composer install --no-interaction --dev --prefer-source \ No newline at end of file diff --git a/readme.md b/readme.md index 6db9b8d..d76e911 100644 --- a/readme.md +++ b/readme.md @@ -1,18 +1,20 @@ # GPS RINEX 2.1 Navigation FILE Parser +[![Latest Stable Version](https://poser.pugx.org/om/events/v/stable.png)](https://packagist.org/packages/om/events) [![Total Downloads](https://poser.pugx.org/om/events/downloads.png)](https://packagist.org/packages/om/events) [![Latest Unstable Version](https://poser.pugx.org/om/events/v/unstable.png)](https://packagist.org/packages/om/events) [![License](https://poser.pugx.org/om/events/license.png)](https://packagist.org/packages/om/events) + RINEX (Receiver Independent Exchange) More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX) [http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html) - author: Roman Ozana, [email protected] - url: www.omdesign.cz - version: 1.1 - license: MIT ## TODO - get information from header - get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java) - add \ No newline at end of file
OzzyCzech/gpsrinex
dba7d60b8c975750749e8129116b26c307384d07
Parser finish
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..82d55ce --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.DS_Store +.DS_Store? +._* +*~ +*.MD5 +*.mwb.bak +.idea +/vendor/ +composer.lock diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..6158e3f --- /dev/null +++ b/composer.json @@ -0,0 +1,20 @@ +{ + "name": "om/gpsrinex", + "description": "GPS RINEX 2.1 navigation file parser", + "license": "MIT", + "authors": [ + { + "name": "Roman Ozana", + "email": "[email protected]" + } + ], + "require": { + + }, + "autoload": { + "classmap": ["src"] + }, + "require-dev": { + "nette/tester": "*" + } +} diff --git a/readme.md b/readme.md index ee11250..6db9b8d 100644 --- a/readme.md +++ b/readme.md @@ -1,8 +1,18 @@ -# THIS IS GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER +# GPS RINEX 2.1 Navigation FILE Parser + +RINEX (Receiver Independent Exchange) +More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX) [http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html) - author: Roman Ozana, [email protected] - url: www.omdesign.cz - version: 1.1 -- license: MIT \ No newline at end of file +- license: MIT + + +## TODO + +- get information from header +- get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java) +- add \ No newline at end of file diff --git a/rinexparser.php b/rinexparser.php deleted file mode 100644 index 028063d..0000000 --- a/rinexparser.php +++ /dev/null @@ -1,288 +0,0 @@ -<?php -/** - Copyright (c) <2009> <Roman Ozana, [email protected]> - - Permission is hereby granted, free of charge, to any person - obtaining a copy of this software and associated documentation - files (the "Software"), to deal in the Software without - restriction, including without limitation the rights to use, - copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the - Software is furnished to do so, subject to the following - conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - */ - -/** - * - * GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER - * - * (http://gps.wva.net/html.common/rinex.html) - * @author Roman Ozana, [email protected] - * @url www.omdesign.cz - * @version 1.2 - */ - -/* -Use example : - -require_once('rinexparser.php'); - -$rinex = new rinexparser(); - -$rinex->makelist('./data28'); - -if ($_GET['load']) // is file load -{ - $data = $rinex->load_file($_GET['load']); // add data - $rinex->parse($data); // parse data - $rinex->print_menu(); // printing menu -} - -for ($i=0;$i<$rinex->counter;$i++) // printing RINEX File Navigation data -{ - $rinex->print_navi($i); -} -*/ - -class rinexparser { - public $output = ''; - public $counter = 0; - - public function load_file($file) { - $file_text = file_get_content($file); //load file - return $file_text; - } - - public function makelist($dir = "") { - $handle = opendir($dir); // open dir handle - while ( ($file = readdir($handle)) != false ) { - if ( ($file != '..') && ($file != '.') && (substr($file, -1, 1) == 'N') ) { - $files[] = $file; - } - } - if (!empty($files)) { - sort($files); - echo '<ol>'; - for($i=0;$i<count($files);$i++) { - echo '<li><a href="'.$_SERVER['PHP_SELF'].'?load='.$dir.'/'.$files[$i].'">'.$files[$i].'</a></li>'; - } - echo '</ol>'; - } - } - - - public function parse($data = '') { - $this->output = ''; - $data = ereg_replace("D([+|-])", "E\\1", $data); - $data = spliti("\n",$data); - - $header_end = false; - - foreach ($data as $row) { - if ($header_end == true and !empty($row)) // read only data - { - $vars = preg_split("/[\s]+/", $row,-1, PREG_SPLIT_NO_EMPTY); // parse text file - //echo '<pre>';print_r($vars);echo '</pre>'; - switch ($brodcast_counter) { - case 0: - $this->output[$this->counter]['prn'] = $vars[0]; - $this->output[$this->counter]['year'] = $vars[1]; - $this->output[$this->counter]['month'] = $vars[2]; - $this->output[$this->counter]['day'] = $vars[3]; - $this->output[$this->counter]['hour'] = $vars[4]; - $this->output[$this->counter]['minute'] = $vars[5]; - $this->output[$this->counter]['second'] = $vars[6]; - $this->output[$this->counter]['SV_clock_bias'] = $vars[7]; - $this->output[$this->counter]['SV_clock_drift'] = $vars[8]; - $this->output[$this->counter]['SV_clock_drift_rate'] = $vars[9]; - break; - case 1: // BRODCAST ORBIT 1 - $this->output[$this->counter]['IODE'] = $vars[0]; - $this->output[$this->counter]['Crs'] = $vars[1]; - $this->output[$this->counter]['Delta_n'] = $vars[2]; - $this->output[$this->counter]['M0'] = $vars[3]; - break; - case 2: // BRODCAST ORBIT 2 - $this->output[$this->counter]['Cuc'] = $vars[0]; - $this->output[$this->counter]['e'] = $vars[1]; - $this->output[$this->counter]['Cus'] = $vars[2]; - $this->output[$this->counter]['sqrtA'] = $vars[3]; - break; - case 3: // BRODCAST ORBIT 3 - $this->output[$this->counter]['Toe'] = $vars[0]; - $this->output[$this->counter]['Cic'] = $vars[1]; - $this->output[$this->counter]['OMEGA'] = $vars[2]; - $this->output[$this->counter]['CIS'] = $vars[3]; - break; - case 4: // BRODCAST ORBIT 4 - $this->output[$this->counter]['i0'] = $vars[0]; - $this->output[$this->counter]['Crc'] = $vars[1]; - $this->output[$this->counter]['omega'] = $vars[2]; // normal is omega - $this->output[$this->counter]['OMEGA_DOT'] = $vars[3]; - break; - case 5: // BRODCAST ORBIT 5 - $this->output[$this->counter]['IDOT'] = $vars[0]; - $this->output[$this->counter]['Codes_on_L2_ch'] = $vars[1]; - $this->output[$this->counter]['GPS_week']= $vars[2]; - $this->output[$this->counter]['L2_p_data_flag'] = $vars[3]; - break; - case 6: // BRODCAST ORBIT 6 - $this->output[$this->counter]['SV_accuracy'] = $vars[0]; - $this->output[$this->counter]['SV_health'] = $vars[1]; - $this->output[$this->counter]['TGD'] = $vars[2]; - $this->output[$this->counter]['IODC'] = $vars[3]; - break; - case 7: // BRODCAST ORBIT 6 - $this->output[$this->counter]['Transmission_time'] = $vars[0]; - $this->output[$this->counter]['Fit_interval'] = $vars[1]; - $this->output[$this->counter]['spare_01'] = $vars[2]; - $this->output[$this->counter]['spare_02'] = $vars[3]; - $this->counter++; - $brodcast_counter = -1; // don't forget clear counter - break; - default: - break; - } - $brodcast_counter++; // number of brodcast - } // is after head ?? - read data - if (stristr($row,'END OF HEADER')) { - $header_end = true; // end of header - $brodcast_counter = 0; - } - } - // echo '<pre>';print_r($this->output);echo '</pre>'; - return $this->output; - } - - public function print_menu() { - echo '<ol>'; - for($i=0;$i<$this->counter;$i++) { - $gps = $this->output[$i]; - echo '<li><a href="#gps'.$i.$gps['prn'].'">GPS '.$gps['prn'].'</a> - '.$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute'].'</li>'; - } - echo '</ol>'; - } - - public function print_navi($number = 0) { - if (count($this->output) < $number) { - return; - } - $gps = $this->output[$number]; - - echo '<h2><a name="gps'.$number.$gps['prn'].'"></a>Navigacni informace GPS : '.$gps['prn'].'</h2>'; - echo '<table border="1" cellspacing="0" cellpadding="7" width="80%">'; - // PRN info - $this->add_lin('Promenna','Hodnota','Jednotky','th'); - $this->add_lin('GPS',$gps['prn']); - $this->add_lin('Epocha : Datum a cas',$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute']); - $this->add_lin('SV clock bias',$gps['SV_clock_bias'],'sec'); - $this->add_lin('SV clock drift',$gps['SV_clock_drift'],'sec/sec'); - $this->add_lin('SV clock drift rate',$gps['SV_clock_drift_rate'],'sec/sec<sup>2</sup>'); - // BRODCAST 01 - $this->add_lin('','&nbsp;',''); - $this->add_lin('IODE Issue of data',$gps['IODE']); - $this->add_lin('C<sub>rs</sub>',$gps['Crs'],'m'); - $this->add_lin('Delta n',$gps['Delta_n'],'radiany/sec'); - $this->add_lin('M<sub>0</sub>',$gps['M0'],'radiany'); - // BRODCAST 02 - $this->add_lin('','&nbsp;',''); - $this->add_lin('C<sub>uc</sub>',$gps['Cuc'],'radiany'); - $this->add_lin('Excentricita e',$gps['e'],'-'); - $this->add_lin('C<sub>us</sub>',$gps['Cus'],'radiany'); - $this->add_lin('sqrt(A)',$gps['sqrtA'],'sqrt(m)'); - // BRODCAST 03 - $this->add_lin('','&nbsp;',''); - $this->add_lin('T<sub>oe</sub>',$gps['Toe'],'sec of GPS week'); - $this->add_lin('C<sub>ic</sub>',$gps['Cic'],'radiany'); - $this->add_lin('OMEGA',$gps['OMEGA'],'radiany'); - $this->add_lin('CIS',$gps['CIS'],'radiany'); - // BRODCAST 04 - $this->add_lin('','&nbsp;',''); - $this->add_lin('i<sub>0</sub>',$gps['i0'],'radiany'); - $this->add_lin('C<sub>rc</sub>',$gps['Crc'],'radiany'); - $this->add_lin('omega',$gps['omega'],'radiany'); - $this->add_lin('OMEGA DOT',$gps['OMEGA_DOT'],'radiany/sec'); - // BRODCAST 05 - $this->add_lin('','&nbsp;',''); - $this->add_lin('IDOT',$gps['IDOT'],'radiany/sec'); - $this->add_lin('Codes on L2 channel',$gps['Codes_on_L2_ch']); - $this->add_lin('GPS week',$gps['GPS_week']); - $this->add_lin('L2 p data flag',$gps['L2_p_data_flag']); - // BRODCAST 06 - $this->add_lin('','&nbsp;',''); - $this->add_lin('SV accuracy',$gps['SV_accuracy'],'metry'); - $this->add_lin('SV health',$gps['SV_health']); - $this->add_lin('TGD',$gps['TGD'],'sec'); - $this->add_lin('IODC Issue of Data, Clock',$gps['IODC']); - // BRODCAST 07 - $this->add_lin('','&nbsp;',''); - $this->add_lin('Transmission time of message',$gps['Transmission_time'],'radiany'); - $this->add_lin('Fit interval',$gps['Fit_interval'],'hodin'); - $this->add_lin('Spare',$gps['spare_01']); - $this->add_lin('Spare',$gps['spare_02']); - echo '</table>'; - } - - public function add_lin($coment, $value, $unit = '',$td = 'td') { - if (!empty($unit) and $td == 'td') { - $unit = '('.$unit.')'; - } - echo "<tr><$td style=&qout;text-align:right;&qout;>$coment</$td><$td>$value</$td><$td>$unit</$td></tr>\n"; - } - /* - RINEX file upload not work yet - some errors i don't know - function storefile($var, $location, $filename=NULL, $maxfilesize=NULL) { - $ok = false; - - // Check file - $mime = $_FILES[$var]["type"]; - if($mime=="image/jpeg" || $mime=="image/pjpeg") { - // Mime type is correct - // Check extension - $name = $_FILES[$var]["name"]; - $array = explode(".", $name); - $nr = count($array); - $ext = $array[$nr-1]; - if($ext=="jpg" || $ext=="jpeg") { - $ok = true; - } - } - - if(isset($maxfilesize)) { - if($_FILES[$var]["size"] > $maxfilesize) { - $ok = false; - } - } - - if($ok==true) { - $tempname = $_FILES[$var]['tmp_name']; - if(isset($filename)) { - $uploadpath = $location.$filename; - } else { - $uploadpath = $location.$_FILES[$var]['name']; - } - if(is_uploaded_file($_FILES[$var]['tmp_name'])) { - while(move_uploaded_file($tempname, $uploadpath)) { - // Wait for the script to finish its upload - } - } - return true; - } else { - return false; - } - } - */ - -} \ No newline at end of file diff --git a/src/RinexNavigationParser.php b/src/RinexNavigationParser.php new file mode 100644 index 0000000..a3ee9a7 --- /dev/null +++ b/src/RinexNavigationParser.php @@ -0,0 +1,130 @@ +<?php +namespace om; + +/** + * RINEX Navigation Parser + * + * @copyright Roman Ožana <[email protected]> + * @license MIT + * @package om + */ +class RinexNavigationParser { + + /** @var int */ + private $boradcast = 1; + + /** + * @param sting $file + * @param callable $callback + * @throws \RuntimeException + * @return string|mixed + */ + public function parseFile($file, $callback = null) { + $body = false; // each file starts with Header + $output = array(); // output data + $this->boradcast = 1; + $counter = 0; + + if (!$handle = fopen($file, "r")) { + throw new \RuntimeException('Can\'t open file' . $file . ' fore reading'); + } + + while (!feof($handle)) { + $row = fgets($handle, 4096); // read line from file + + if ($body && !empty($row)) { + $partial = $this->parseRow($row); // read line + + + if ($callback) { + call_user_func($callback, $partial, $counter, $this->boradcast); // call user function for processing line + } else { + $output[$counter][] = $partial; // return whole data + } + + if ($this->boradcast === 1) $counter++; // count + } + + if (preg_match('/END OF HEADER/', $row)) $body = true; // end of header + } + + fclose($handle); + return ($callback) ? null : $output; + } + + /** + * @param string $row + * @return string + */ + public function parseRow($row = '') { + $output = array(); + $row = preg_replace('/D([+|-])/', 'E\1', $row); + $data = preg_split("/[\s]+/", $row, -1, PREG_SPLIT_NO_EMPTY); + + switch ($this->boradcast++) { + case 1: + return array( + 'PRN' => $data[0], + 'year' => $data[1], + 'month' => $data[2], + 'day' => $data[3], + 'hour' => $data[4], + 'minute' => $data[5], + 'second' => $data[6], + 'SV_clock_bias' => $data[7], + 'SV_clock_drift' => $data[8], + 'SV_clock_drift_rate' => $data[9], + ); + case 2: // BRODCAST ORBIT 1 + return array( + 'IODE' => $data[0], + 'Crs' => $data[1], + 'Delta_n' => $data[2], + 'M0' => $data[3], + ); + case 3: // BRODCAST ORBIT 2 + return array( + 'Cuc' => $data[0], + 'e' => $data[1], + 'Cus' => $data[2], + 'sqrtA' => $data[3], + ); + case 4: // BRODCAST ORBIT 3 + return array( + 'Toe' => $data[0], + 'Cic' => $data[1], + 'OMEGA' => $data[2], + 'CIS' => $data[3], + ); + case 5: // BRODCAST ORBIT 4 + return array( + 'i0' => $data[0], + 'Crc' => $data[1], + 'omega' => $data[2], // normal is omega + 'OMEGA_DOT' => $data[3], + ); + case 6: // BRODCAST ORBIT 5 + return array( + 'IDOT' => $data[0], + 'Codes_on_L2_ch' => $data[1], + 'GPS_week' => $data[2], + 'L2_p_data_flag' => $data[3], + ); + case 7: // BRODCAST ORBIT 6 + return array( + 'SV_accuracy' => $data[0], + 'SV_health' => $data[1], + 'TGD' => $data[2], + 'IODC' => $data[3], + ); + case 8: // BRODCAST ORBIT 6 + $this->boradcast = 1; + return array( + 'Transmission_time' => $data[0], + 'Fit_interval' => $data[1], + 'spare_01' => $data[2], + 'spare_02' => $data[3], + ); + } + } +} \ No newline at end of file diff --git a/tests/ParserTest.phpt b/tests/ParserTest.phpt new file mode 100644 index 0000000..b793141 --- /dev/null +++ b/tests/ParserTest.phpt @@ -0,0 +1,17 @@ +<?php +use Tester\Assert; + +require_once __DIR__ . '/../vendor/autoload.php'; + +$parser = new \om\RinexNavigationParser(); + +$data = $parser->parseFile(__DIR__ . '/data/LongNumberExample.obs'); + + + + +Assert::same('6', $data[0][0]['PRN']); +Assert::same('-.165982783074E-10', $data[0][0]['SV_clock_drift']); +Assert::same('.000000000000E+00', $data[0][0]['SV_clock_drift_rate']); + +Assert::same(4, count($data)); \ No newline at end of file diff --git a/tests/data/LongNumberExample.obs b/tests/data/LongNumberExample.obs new file mode 100644 index 0000000..37e0639 --- /dev/null +++ b/tests/data/LongNumberExample.obs @@ -0,0 +1,40 @@ + 2.10 N: GPS NAV DATA RINEX VERSION / TYPE +XXRINEXN V2.10 AIUB 3-SEP-99 15:22 PGM / RUN BY / DATE +EXAMPLE OF VERSION 2.10 FORMAT COMMENT + .1676D-07 .2235D-07 -.1192D-06 -.1192D-06 ION ALPHA + .1208D+06 .1310D+06 -.1310D+06 -.1966D+06 ION BETA + .133179128170D-06 .107469588780D-12 552960 1025 DELTA-UTC: A0,A1,T,W + 13 LEAP SECONDS + END OF HEADER + 6 99 9 2 17 51 44.0 -.839701388031D-03 -.165982783074D-10 .000000000000D+00 + .910000000000D+02 .934062500000D+02 .116040547840D-08 .162092304801D+00 + .484101474285D-05 .626740418375D-02 .652112066746D-05 .515365489006D+04 + .409904000000D+06 -.242143869400D-07 .329237003460D+00 -.596046447754D-07 + .111541663136D+01 .326593750000D+03 .206958726335D+01 -.638312302555D-08 + .307155651409D-09 .000000000000D+00 .102500000000D+04 .000000000000D+00 + .000000000000D+00 .000000000000D+00 .000000000000D+00 .910000000000D+02 + .406800000000D+06 .000000000000D+00 +13 99 9 2 19 0 0.0 .490025617182D-03 .204636307899D-11 .000000000000D+00 + .133000000000D+03 -.963125000000D+02 .146970407622D-08 .292961152146D+01 + -.498816370964D-05 .200239347760D-02 .928156077862D-05 .515328476143D+04 + .414000000000D+06 -.279396772385D-07 .243031939942D+01 -.558793544769D-07 + .110192796930D+01 .271187500000D+03 -.232757915425D+01 -.619632953057D-08 + -.785747015231D-11 .000000000000D+00 .102500000000D+04 .000000000000D+00 + .000000000000D+00 .000000000000D+00 .000000000000D+00 .389000000000D+03 + .410400000000D+06 .000000000000D+00 + 6 99 9 2 17 51 44.0 -.839701388031D-03 -.165982783074D-10 .000000000000D+00 + .910000000000D+02 .934062500000D+02 .116040547840D-08 .162092304801D+00 + .484101474285D-05 .626740418375D-02 .652112066746D-05 .515365489006D+04 + .409904000000D+06 -.242143869400D-07 .329237003460D+00 -.596046447754D-07 + .111541663136D+01 .326593750000D+03 .206958726335D+01 -.638312302555D-08 + .307155651409D-09 .000000000000D+00 .102500000000D+04 .000000000000D+00 + .000000000000D+00 .000000000000D+00 .000000000000D+00 .910000000000D+02 + .406800000000D+06 .000000000000D+00 +13 99 9 2 19 0 0.0 .490025617182D-03 .204636307899D-11 .000000000000D+00 + .133000000000D+03 -.963125000000D+02 .146970407622D-08 .292961152146D+01 + -.498816370964D-05 .200239347760D-02 .928156077862D-05 .515328476143D+04 + .414000000000D+06 -.279396772385D-07 .243031939942D+01 -.558793544769D-07 + .110192796930D+01 .271187500000D+03 -.232757915425D+01 -.619632953057D-08 + -.785747015231D-11 .000000000000D+00 .102500000000D+04 .000000000000D+00 + .000000000000D+00 .000000000000D+00 .000000000000D+00 .389000000000D+03 + .410400000000D+06 .000000000000D+00 \ No newline at end of file
OzzyCzech/gpsrinex
b1bfc3f2ce59c6ccbb09f591a420f21fd5698687
Add license
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..458df4f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 Roman Ožana + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE.
OzzyCzech/gpsrinex
2035bbb98166c71909592bf62f4fffb97bb99879
Fix readme
diff --git a/README b/README deleted file mode 100644 index 708da39..0000000 --- a/README +++ /dev/null @@ -1,7 +0,0 @@ -THIS IS GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER -(http://gps.wva.net/html.common/rinex.html) - -author: Roman Ozana, [email protected] -url: www.omdesign.cz -version: 1.1 -license: MIT \ No newline at end of file diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..ee11250 --- /dev/null +++ b/readme.md @@ -0,0 +1,8 @@ +# THIS IS GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER + +[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html) + +- author: Roman Ozana, [email protected] +- url: www.omdesign.cz +- version: 1.1 +- license: MIT \ No newline at end of file
OzzyCzech/gpsrinex
0b67571ce3ba1fe9f6f4d3ba9797eaf7c65a526b
add public before every function
diff --git a/README b/README index 98b893b..708da39 100644 --- a/README +++ b/README @@ -1 +1,7 @@ -THIS IS GPS RINEX FILE PARSER \ No newline at end of file +THIS IS GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER +(http://gps.wva.net/html.common/rinex.html) + +author: Roman Ozana, [email protected] +url: www.omdesign.cz +version: 1.1 +license: MIT \ No newline at end of file diff --git a/rinexparser.php b/rinexparser.php index 5d3f468..028063d 100644 --- a/rinexparser.php +++ b/rinexparser.php @@ -1,298 +1,288 @@ <?php -################################################################################ -# DATE : 06.03.2006 # -# Short description : # -# # -# GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER # -# (http://gps.wva.net/html.common/rinex.html) # -# # -# Version info : # -# # -# rinexparser CLASS VERSION 1.0 # -# # -# Author info : # -# # -# ROMAN OŽANA (c) 2006 # -# ICQ (99950132) # -# WWW (www.nabito.net) # -# E-mail ([email protected] ) # -# # -# Country: # -# # -# CZECH REPUBLIC # -# # -# Licence: # -# # -# IF YOU WANT USE THIS CODE PLEASE CONNECT AUTHOR, Thank You # -# # -# it was written in SCITE # -################################################################################ +/** + Copyright (c) <2009> <Roman Ozana, [email protected]> + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * + * GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER + * + * (http://gps.wva.net/html.common/rinex.html) + * @author Roman Ozana, [email protected] + * @url www.omdesign.cz + * @version 1.2 + */ + /* - Use example : - - require_once('rinexparser.php'); - - $rinex = new rinexparser(); - - $rinex->makelist('./data28'); - - if ($_GET['load']) // is file load - { - $data = $rinex->load_file($_GET['load']); // add data - $rinex->parse($data); // parse data - $rinex->print_menu(); // printing menu - } - - for ($i=0;$i<$rinex->counter;$i++) // printing RINEX File Navigation data - { - $rinex->print_navi($i); - } +Use example : + +require_once('rinexparser.php'); + +$rinex = new rinexparser(); + +$rinex->makelist('./data28'); + +if ($_GET['load']) // is file load +{ + $data = $rinex->load_file($_GET['load']); // add data + $rinex->parse($data); // parse data + $rinex->print_menu(); // printing menu +} + +for ($i=0;$i<$rinex->counter;$i++) // printing RINEX File Navigation data +{ + $rinex->print_navi($i); +} */ - class rinexparser - { - public $output = ''; - public $counter = 0; - - function load_file($file) - { - $file_text = join ("", file ($file)); //load file - return $file_text; - } - - function makelist($dir = "") - { - $handle = opendir($dir); // open dir handle - while ( ($file = readdir($handle)) != false ) - { - if ( ($file != '..') && ($file != '.') && (substr($file, -1, 1) == 'N') ) - { - $files[] = $file; - } - } - if (!empty($files)) - { - sort($files); - echo '<ol>'; - for($i=0;$i<count($files);$i++) - { - echo '<li><a href="'.$_SERVER['PHP_SELF'].'?load='.$dir.'/'.$files[$i].'">'.$files[$i].'</a></li>'; - } - echo '</ol>'; - } - } - - - function parse($data = '') - { - $this->output = ''; - $data = ereg_replace("D([+|-])", "E\\1", $data); - $data = spliti("\n",$data); - - $header_end = false; - - foreach ($data as $row) - { - if ($header_end == true and !empty($row)) // read only data - { - $vars = preg_split("/[\s]+/", $row,-1, PREG_SPLIT_NO_EMPTY); // parse text file - //echo '<pre>';print_r($vars);echo '</pre>'; - switch ($brodcast_counter) - { - case 0: - $this->output[$this->counter]['prn'] = $vars[0]; - $this->output[$this->counter]['year'] = $vars[1]; - $this->output[$this->counter]['month'] = $vars[2]; - $this->output[$this->counter]['day'] = $vars[3]; - $this->output[$this->counter]['hour'] = $vars[4]; - $this->output[$this->counter]['minute'] = $vars[5]; - $this->output[$this->counter]['second'] = $vars[6]; - $this->output[$this->counter]['SV_clock_bias'] = $vars[7]; - $this->output[$this->counter]['SV_clock_drift'] = $vars[8]; - $this->output[$this->counter]['SV_clock_drift_rate'] = $vars[9]; - break; - case 1: // BRODCAST ORBIT 1 - $this->output[$this->counter]['IODE'] = $vars[0]; - $this->output[$this->counter]['Crs'] = $vars[1]; - $this->output[$this->counter]['Delta_n'] = $vars[2]; - $this->output[$this->counter]['M0'] = $vars[3]; - break; - case 2: // BRODCAST ORBIT 2 - $this->output[$this->counter]['Cuc'] = $vars[0]; - $this->output[$this->counter]['e'] = $vars[1]; - $this->output[$this->counter]['Cus'] = $vars[2]; - $this->output[$this->counter]['sqrtA'] = $vars[3]; - break; - case 3: // BRODCAST ORBIT 3 - $this->output[$this->counter]['Toe'] = $vars[0]; - $this->output[$this->counter]['Cic'] = $vars[1]; - $this->output[$this->counter]['OMEGA'] = $vars[2]; - $this->output[$this->counter]['CIS'] = $vars[3]; - break; - case 4: // BRODCAST ORBIT 4 - $this->output[$this->counter]['i0'] = $vars[0]; - $this->output[$this->counter]['Crc'] = $vars[1]; - $this->output[$this->counter]['omega'] = $vars[2]; // normal is omega - $this->output[$this->counter]['OMEGA_DOT'] = $vars[3]; - break; - case 5: // BRODCAST ORBIT 5 - $this->output[$this->counter]['IDOT'] = $vars[0]; - $this->output[$this->counter]['Codes_on_L2_ch'] = $vars[1]; - $this->output[$this->counter]['GPS_week']= $vars[2]; - $this->output[$this->counter]['L2_p_data_flag'] = $vars[3]; - break; - case 6: // BRODCAST ORBIT 6 - $this->output[$this->counter]['SV_accuracy'] = $vars[0]; - $this->output[$this->counter]['SV_health'] = $vars[1]; - $this->output[$this->counter]['TGD'] = $vars[2]; - $this->output[$this->counter]['IODC'] = $vars[3]; - break; - case 7: // BRODCAST ORBIT 6 - $this->output[$this->counter]['Transmission_time'] = $vars[0]; - $this->output[$this->counter]['Fit_interval'] = $vars[1]; - $this->output[$this->counter]['spare_01'] = $vars[2]; - $this->output[$this->counter]['spare_02'] = $vars[3]; - $this->counter++; - $brodcast_counter = -1; // don't forget clear counter - break; - default: - break; - } - $brodcast_counter++; // number of brodcast - } // is after head ?? - read data - if (stristr($row,'END OF HEADER')) - { - $header_end = true; // end of header - $brodcast_counter = 0; - } - } - // echo '<pre>';print_r($this->output);echo '</pre>'; - return $this->output; - } - - function print_menu() - { - echo '<ol>'; - for($i=0;$i<$this->counter;$i++) - { - $gps = $this->output[$i]; - echo '<li><a href="#gps'.$i.$gps['prn'].'">GPS '.$gps['prn'].'</a> - '.$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute'].'</li>'; - } - echo '</ol>'; - } - - function print_navi($number = 0) - { - if (count($this->output) < $number) - { - return; - } - $gps = $this->output[$number]; - - echo '<h2><a name="gps'.$number.$gps['prn'].'"></a>Navigacni informace GPS : '.$gps['prn'].'</h2>'; - echo '<table border="1" cellspacing="0" cellpadding="7" width="80%">'; - // PRN info - $this->add_lin('Promenna','Hodnota','Jednotky','th'); - $this->add_lin('GPS',$gps['prn']); - $this->add_lin('Epocha : Datum a cas',$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute']); - $this->add_lin('SV clock bias',$gps['SV_clock_bias'],'sec'); - $this->add_lin('SV clock drift',$gps['SV_clock_drift'],'sec/sec'); - $this->add_lin('SV clock drift rate',$gps['SV_clock_drift_rate'],'sec/sec<sup>2</sup>'); - // BRODCAST 01 - $this->add_lin('','&nbsp;',''); - $this->add_lin('IODE Issue of data',$gps['IODE']); - $this->add_lin('C<sub>rs</sub>',$gps['Crs'],'m'); - $this->add_lin('Delta n',$gps['Delta_n'],'radiany/sec'); - $this->add_lin('M<sub>0</sub>',$gps['M0'],'radiany'); - // BRODCAST 02 - $this->add_lin('','&nbsp;',''); - $this->add_lin('C<sub>uc</sub>',$gps['Cuc'],'radiany'); - $this->add_lin('Excentricita e',$gps['e'],'-'); - $this->add_lin('C<sub>us</sub>',$gps['Cus'],'radiany'); - $this->add_lin('sqrt(A)',$gps['sqrtA'],'sqrt(m)'); - // BRODCAST 03 - $this->add_lin('','&nbsp;',''); - $this->add_lin('T<sub>oe</sub>',$gps['Toe'],'sec of GPS week'); - $this->add_lin('C<sub>ic</sub>',$gps['Cic'],'radiany'); - $this->add_lin('OMEGA',$gps['OMEGA'],'radiany'); - $this->add_lin('CIS',$gps['CIS'],'radiany'); - // BRODCAST 04 - $this->add_lin('','&nbsp;',''); - $this->add_lin('i<sub>0</sub>',$gps['i0'],'radiany'); - $this->add_lin('C<sub>rc</sub>',$gps['Crc'],'radiany'); - $this->add_lin('omega',$gps['omega'],'radiany'); - $this->add_lin('OMEGA DOT',$gps['OMEGA_DOT'],'radiany/sec'); - // BRODCAST 05 - $this->add_lin('','&nbsp;',''); - $this->add_lin('IDOT',$gps['IDOT'],'radiany/sec'); - $this->add_lin('Codes on L2 channel',$gps['Codes_on_L2_ch']); - $this->add_lin('GPS week',$gps['GPS_week']); - $this->add_lin('L2 p data flag',$gps['L2_p_data_flag']); - // BRODCAST 06 - $this->add_lin('','&nbsp;',''); - $this->add_lin('SV accuracy',$gps['SV_accuracy'],'metry'); - $this->add_lin('SV health',$gps['SV_health']); - $this->add_lin('TGD',$gps['TGD'],'sec'); - $this->add_lin('IODC Issue of Data, Clock',$gps['IODC']); - // BRODCAST 07 - $this->add_lin('','&nbsp;',''); - $this->add_lin('Transmission time of message',$gps['Transmission_time'],'radiany'); - $this->add_lin('Fit interval',$gps['Fit_interval'],'hodin'); - $this->add_lin('Spare',$gps['spare_01']); - $this->add_lin('Spare',$gps['spare_02']); - echo '</table>'; - } - - function add_lin($coment, $value, $unit = '',$td = 'td') - { - if (!empty($unit) and $td == 'td') - { - $unit = '('.$unit.')'; - } - echo "<tr><$td style=&qout;text-align:right;&qout;>$coment</$td><$td>$value</$td><$td>$unit</$td></tr>\n"; - } + +class rinexparser { + public $output = ''; + public $counter = 0; + + public function load_file($file) { + $file_text = file_get_content($file); //load file + return $file_text; + } + + public function makelist($dir = "") { + $handle = opendir($dir); // open dir handle + while ( ($file = readdir($handle)) != false ) { + if ( ($file != '..') && ($file != '.') && (substr($file, -1, 1) == 'N') ) { + $files[] = $file; + } + } + if (!empty($files)) { + sort($files); + echo '<ol>'; + for($i=0;$i<count($files);$i++) { + echo '<li><a href="'.$_SERVER['PHP_SELF'].'?load='.$dir.'/'.$files[$i].'">'.$files[$i].'</a></li>'; + } + echo '</ol>'; + } + } + + + public function parse($data = '') { + $this->output = ''; + $data = ereg_replace("D([+|-])", "E\\1", $data); + $data = spliti("\n",$data); + + $header_end = false; + + foreach ($data as $row) { + if ($header_end == true and !empty($row)) // read only data + { + $vars = preg_split("/[\s]+/", $row,-1, PREG_SPLIT_NO_EMPTY); // parse text file + //echo '<pre>';print_r($vars);echo '</pre>'; + switch ($brodcast_counter) { + case 0: + $this->output[$this->counter]['prn'] = $vars[0]; + $this->output[$this->counter]['year'] = $vars[1]; + $this->output[$this->counter]['month'] = $vars[2]; + $this->output[$this->counter]['day'] = $vars[3]; + $this->output[$this->counter]['hour'] = $vars[4]; + $this->output[$this->counter]['minute'] = $vars[5]; + $this->output[$this->counter]['second'] = $vars[6]; + $this->output[$this->counter]['SV_clock_bias'] = $vars[7]; + $this->output[$this->counter]['SV_clock_drift'] = $vars[8]; + $this->output[$this->counter]['SV_clock_drift_rate'] = $vars[9]; + break; + case 1: // BRODCAST ORBIT 1 + $this->output[$this->counter]['IODE'] = $vars[0]; + $this->output[$this->counter]['Crs'] = $vars[1]; + $this->output[$this->counter]['Delta_n'] = $vars[2]; + $this->output[$this->counter]['M0'] = $vars[3]; + break; + case 2: // BRODCAST ORBIT 2 + $this->output[$this->counter]['Cuc'] = $vars[0]; + $this->output[$this->counter]['e'] = $vars[1]; + $this->output[$this->counter]['Cus'] = $vars[2]; + $this->output[$this->counter]['sqrtA'] = $vars[3]; + break; + case 3: // BRODCAST ORBIT 3 + $this->output[$this->counter]['Toe'] = $vars[0]; + $this->output[$this->counter]['Cic'] = $vars[1]; + $this->output[$this->counter]['OMEGA'] = $vars[2]; + $this->output[$this->counter]['CIS'] = $vars[3]; + break; + case 4: // BRODCAST ORBIT 4 + $this->output[$this->counter]['i0'] = $vars[0]; + $this->output[$this->counter]['Crc'] = $vars[1]; + $this->output[$this->counter]['omega'] = $vars[2]; // normal is omega + $this->output[$this->counter]['OMEGA_DOT'] = $vars[3]; + break; + case 5: // BRODCAST ORBIT 5 + $this->output[$this->counter]['IDOT'] = $vars[0]; + $this->output[$this->counter]['Codes_on_L2_ch'] = $vars[1]; + $this->output[$this->counter]['GPS_week']= $vars[2]; + $this->output[$this->counter]['L2_p_data_flag'] = $vars[3]; + break; + case 6: // BRODCAST ORBIT 6 + $this->output[$this->counter]['SV_accuracy'] = $vars[0]; + $this->output[$this->counter]['SV_health'] = $vars[1]; + $this->output[$this->counter]['TGD'] = $vars[2]; + $this->output[$this->counter]['IODC'] = $vars[3]; + break; + case 7: // BRODCAST ORBIT 6 + $this->output[$this->counter]['Transmission_time'] = $vars[0]; + $this->output[$this->counter]['Fit_interval'] = $vars[1]; + $this->output[$this->counter]['spare_01'] = $vars[2]; + $this->output[$this->counter]['spare_02'] = $vars[3]; + $this->counter++; + $brodcast_counter = -1; // don't forget clear counter + break; + default: + break; + } + $brodcast_counter++; // number of brodcast + } // is after head ?? - read data + if (stristr($row,'END OF HEADER')) { + $header_end = true; // end of header + $brodcast_counter = 0; + } + } + // echo '<pre>';print_r($this->output);echo '</pre>'; + return $this->output; + } + + public function print_menu() { + echo '<ol>'; + for($i=0;$i<$this->counter;$i++) { + $gps = $this->output[$i]; + echo '<li><a href="#gps'.$i.$gps['prn'].'">GPS '.$gps['prn'].'</a> - '.$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute'].'</li>'; + } + echo '</ol>'; + } + + public function print_navi($number = 0) { + if (count($this->output) < $number) { + return; + } + $gps = $this->output[$number]; + + echo '<h2><a name="gps'.$number.$gps['prn'].'"></a>Navigacni informace GPS : '.$gps['prn'].'</h2>'; + echo '<table border="1" cellspacing="0" cellpadding="7" width="80%">'; + // PRN info + $this->add_lin('Promenna','Hodnota','Jednotky','th'); + $this->add_lin('GPS',$gps['prn']); + $this->add_lin('Epocha : Datum a cas',$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute']); + $this->add_lin('SV clock bias',$gps['SV_clock_bias'],'sec'); + $this->add_lin('SV clock drift',$gps['SV_clock_drift'],'sec/sec'); + $this->add_lin('SV clock drift rate',$gps['SV_clock_drift_rate'],'sec/sec<sup>2</sup>'); + // BRODCAST 01 + $this->add_lin('','&nbsp;',''); + $this->add_lin('IODE Issue of data',$gps['IODE']); + $this->add_lin('C<sub>rs</sub>',$gps['Crs'],'m'); + $this->add_lin('Delta n',$gps['Delta_n'],'radiany/sec'); + $this->add_lin('M<sub>0</sub>',$gps['M0'],'radiany'); + // BRODCAST 02 + $this->add_lin('','&nbsp;',''); + $this->add_lin('C<sub>uc</sub>',$gps['Cuc'],'radiany'); + $this->add_lin('Excentricita e',$gps['e'],'-'); + $this->add_lin('C<sub>us</sub>',$gps['Cus'],'radiany'); + $this->add_lin('sqrt(A)',$gps['sqrtA'],'sqrt(m)'); + // BRODCAST 03 + $this->add_lin('','&nbsp;',''); + $this->add_lin('T<sub>oe</sub>',$gps['Toe'],'sec of GPS week'); + $this->add_lin('C<sub>ic</sub>',$gps['Cic'],'radiany'); + $this->add_lin('OMEGA',$gps['OMEGA'],'radiany'); + $this->add_lin('CIS',$gps['CIS'],'radiany'); + // BRODCAST 04 + $this->add_lin('','&nbsp;',''); + $this->add_lin('i<sub>0</sub>',$gps['i0'],'radiany'); + $this->add_lin('C<sub>rc</sub>',$gps['Crc'],'radiany'); + $this->add_lin('omega',$gps['omega'],'radiany'); + $this->add_lin('OMEGA DOT',$gps['OMEGA_DOT'],'radiany/sec'); + // BRODCAST 05 + $this->add_lin('','&nbsp;',''); + $this->add_lin('IDOT',$gps['IDOT'],'radiany/sec'); + $this->add_lin('Codes on L2 channel',$gps['Codes_on_L2_ch']); + $this->add_lin('GPS week',$gps['GPS_week']); + $this->add_lin('L2 p data flag',$gps['L2_p_data_flag']); + // BRODCAST 06 + $this->add_lin('','&nbsp;',''); + $this->add_lin('SV accuracy',$gps['SV_accuracy'],'metry'); + $this->add_lin('SV health',$gps['SV_health']); + $this->add_lin('TGD',$gps['TGD'],'sec'); + $this->add_lin('IODC Issue of Data, Clock',$gps['IODC']); + // BRODCAST 07 + $this->add_lin('','&nbsp;',''); + $this->add_lin('Transmission time of message',$gps['Transmission_time'],'radiany'); + $this->add_lin('Fit interval',$gps['Fit_interval'],'hodin'); + $this->add_lin('Spare',$gps['spare_01']); + $this->add_lin('Spare',$gps['spare_02']); + echo '</table>'; + } + + public function add_lin($coment, $value, $unit = '',$td = 'td') { + if (!empty($unit) and $td == 'td') { + $unit = '('.$unit.')'; + } + echo "<tr><$td style=&qout;text-align:right;&qout;>$coment</$td><$td>$value</$td><$td>$unit</$td></tr>\n"; + } /* RINEX file upload not work yet - some errors i don't know function storefile($var, $location, $filename=NULL, $maxfilesize=NULL) { $ok = false; // Check file $mime = $_FILES[$var]["type"]; if($mime=="image/jpeg" || $mime=="image/pjpeg") { // Mime type is correct // Check extension $name = $_FILES[$var]["name"]; $array = explode(".", $name); $nr = count($array); $ext = $array[$nr-1]; if($ext=="jpg" || $ext=="jpeg") { $ok = true; } } if(isset($maxfilesize)) { if($_FILES[$var]["size"] > $maxfilesize) { $ok = false; } } if($ok==true) { $tempname = $_FILES[$var]['tmp_name']; if(isset($filename)) { $uploadpath = $location.$filename; } else { $uploadpath = $location.$_FILES[$var]['name']; } if(is_uploaded_file($_FILES[$var]['tmp_name'])) { while(move_uploaded_file($tempname, $uploadpath)) { // Wait for the script to finish its upload } } return true; } else { return false; } } */ - - } -?> \ No newline at end of file + +} \ No newline at end of file
OzzyCzech/gpsrinex
8f49a400da2039e304d8fc5b2edf75530d6ef737
Add parser
diff --git a/README b/README index e69de29..98b893b 100644 --- a/README +++ b/README @@ -0,0 +1 @@ +THIS IS GPS RINEX FILE PARSER \ No newline at end of file diff --git a/rinexparser.php b/rinexparser.php new file mode 100644 index 0000000..5d3f468 --- /dev/null +++ b/rinexparser.php @@ -0,0 +1,298 @@ +<?php +################################################################################ +# DATE : 06.03.2006 # +# Short description : # +# # +# GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER # +# (http://gps.wva.net/html.common/rinex.html) # +# # +# Version info : # +# # +# rinexparser CLASS VERSION 1.0 # +# # +# Author info : # +# # +# ROMAN OŽANA (c) 2006 # +# ICQ (99950132) # +# WWW (www.nabito.net) # +# E-mail ([email protected] ) # +# # +# Country: # +# # +# CZECH REPUBLIC # +# # +# Licence: # +# # +# IF YOU WANT USE THIS CODE PLEASE CONNECT AUTHOR, Thank You # +# # +# it was written in SCITE # +################################################################################ +/* + Use example : + + require_once('rinexparser.php'); + + $rinex = new rinexparser(); + + $rinex->makelist('./data28'); + + if ($_GET['load']) // is file load + { + $data = $rinex->load_file($_GET['load']); // add data + $rinex->parse($data); // parse data + $rinex->print_menu(); // printing menu + } + + for ($i=0;$i<$rinex->counter;$i++) // printing RINEX File Navigation data + { + $rinex->print_navi($i); + } +*/ + class rinexparser + { + public $output = ''; + public $counter = 0; + + function load_file($file) + { + $file_text = join ("", file ($file)); //load file + return $file_text; + } + + function makelist($dir = "") + { + $handle = opendir($dir); // open dir handle + while ( ($file = readdir($handle)) != false ) + { + if ( ($file != '..') && ($file != '.') && (substr($file, -1, 1) == 'N') ) + { + $files[] = $file; + } + } + if (!empty($files)) + { + sort($files); + echo '<ol>'; + for($i=0;$i<count($files);$i++) + { + echo '<li><a href="'.$_SERVER['PHP_SELF'].'?load='.$dir.'/'.$files[$i].'">'.$files[$i].'</a></li>'; + } + echo '</ol>'; + } + } + + + function parse($data = '') + { + $this->output = ''; + $data = ereg_replace("D([+|-])", "E\\1", $data); + $data = spliti("\n",$data); + + $header_end = false; + + foreach ($data as $row) + { + if ($header_end == true and !empty($row)) // read only data + { + $vars = preg_split("/[\s]+/", $row,-1, PREG_SPLIT_NO_EMPTY); // parse text file + //echo '<pre>';print_r($vars);echo '</pre>'; + switch ($brodcast_counter) + { + case 0: + $this->output[$this->counter]['prn'] = $vars[0]; + $this->output[$this->counter]['year'] = $vars[1]; + $this->output[$this->counter]['month'] = $vars[2]; + $this->output[$this->counter]['day'] = $vars[3]; + $this->output[$this->counter]['hour'] = $vars[4]; + $this->output[$this->counter]['minute'] = $vars[5]; + $this->output[$this->counter]['second'] = $vars[6]; + $this->output[$this->counter]['SV_clock_bias'] = $vars[7]; + $this->output[$this->counter]['SV_clock_drift'] = $vars[8]; + $this->output[$this->counter]['SV_clock_drift_rate'] = $vars[9]; + break; + case 1: // BRODCAST ORBIT 1 + $this->output[$this->counter]['IODE'] = $vars[0]; + $this->output[$this->counter]['Crs'] = $vars[1]; + $this->output[$this->counter]['Delta_n'] = $vars[2]; + $this->output[$this->counter]['M0'] = $vars[3]; + break; + case 2: // BRODCAST ORBIT 2 + $this->output[$this->counter]['Cuc'] = $vars[0]; + $this->output[$this->counter]['e'] = $vars[1]; + $this->output[$this->counter]['Cus'] = $vars[2]; + $this->output[$this->counter]['sqrtA'] = $vars[3]; + break; + case 3: // BRODCAST ORBIT 3 + $this->output[$this->counter]['Toe'] = $vars[0]; + $this->output[$this->counter]['Cic'] = $vars[1]; + $this->output[$this->counter]['OMEGA'] = $vars[2]; + $this->output[$this->counter]['CIS'] = $vars[3]; + break; + case 4: // BRODCAST ORBIT 4 + $this->output[$this->counter]['i0'] = $vars[0]; + $this->output[$this->counter]['Crc'] = $vars[1]; + $this->output[$this->counter]['omega'] = $vars[2]; // normal is omega + $this->output[$this->counter]['OMEGA_DOT'] = $vars[3]; + break; + case 5: // BRODCAST ORBIT 5 + $this->output[$this->counter]['IDOT'] = $vars[0]; + $this->output[$this->counter]['Codes_on_L2_ch'] = $vars[1]; + $this->output[$this->counter]['GPS_week']= $vars[2]; + $this->output[$this->counter]['L2_p_data_flag'] = $vars[3]; + break; + case 6: // BRODCAST ORBIT 6 + $this->output[$this->counter]['SV_accuracy'] = $vars[0]; + $this->output[$this->counter]['SV_health'] = $vars[1]; + $this->output[$this->counter]['TGD'] = $vars[2]; + $this->output[$this->counter]['IODC'] = $vars[3]; + break; + case 7: // BRODCAST ORBIT 6 + $this->output[$this->counter]['Transmission_time'] = $vars[0]; + $this->output[$this->counter]['Fit_interval'] = $vars[1]; + $this->output[$this->counter]['spare_01'] = $vars[2]; + $this->output[$this->counter]['spare_02'] = $vars[3]; + $this->counter++; + $brodcast_counter = -1; // don't forget clear counter + break; + default: + break; + } + $brodcast_counter++; // number of brodcast + } // is after head ?? - read data + if (stristr($row,'END OF HEADER')) + { + $header_end = true; // end of header + $brodcast_counter = 0; + } + } + // echo '<pre>';print_r($this->output);echo '</pre>'; + return $this->output; + } + + function print_menu() + { + echo '<ol>'; + for($i=0;$i<$this->counter;$i++) + { + $gps = $this->output[$i]; + echo '<li><a href="#gps'.$i.$gps['prn'].'">GPS '.$gps['prn'].'</a> - '.$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute'].'</li>'; + } + echo '</ol>'; + } + + function print_navi($number = 0) + { + if (count($this->output) < $number) + { + return; + } + $gps = $this->output[$number]; + + echo '<h2><a name="gps'.$number.$gps['prn'].'"></a>Navigacni informace GPS : '.$gps['prn'].'</h2>'; + echo '<table border="1" cellspacing="0" cellpadding="7" width="80%">'; + // PRN info + $this->add_lin('Promenna','Hodnota','Jednotky','th'); + $this->add_lin('GPS',$gps['prn']); + $this->add_lin('Epocha : Datum a cas',$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute']); + $this->add_lin('SV clock bias',$gps['SV_clock_bias'],'sec'); + $this->add_lin('SV clock drift',$gps['SV_clock_drift'],'sec/sec'); + $this->add_lin('SV clock drift rate',$gps['SV_clock_drift_rate'],'sec/sec<sup>2</sup>'); + // BRODCAST 01 + $this->add_lin('','&nbsp;',''); + $this->add_lin('IODE Issue of data',$gps['IODE']); + $this->add_lin('C<sub>rs</sub>',$gps['Crs'],'m'); + $this->add_lin('Delta n',$gps['Delta_n'],'radiany/sec'); + $this->add_lin('M<sub>0</sub>',$gps['M0'],'radiany'); + // BRODCAST 02 + $this->add_lin('','&nbsp;',''); + $this->add_lin('C<sub>uc</sub>',$gps['Cuc'],'radiany'); + $this->add_lin('Excentricita e',$gps['e'],'-'); + $this->add_lin('C<sub>us</sub>',$gps['Cus'],'radiany'); + $this->add_lin('sqrt(A)',$gps['sqrtA'],'sqrt(m)'); + // BRODCAST 03 + $this->add_lin('','&nbsp;',''); + $this->add_lin('T<sub>oe</sub>',$gps['Toe'],'sec of GPS week'); + $this->add_lin('C<sub>ic</sub>',$gps['Cic'],'radiany'); + $this->add_lin('OMEGA',$gps['OMEGA'],'radiany'); + $this->add_lin('CIS',$gps['CIS'],'radiany'); + // BRODCAST 04 + $this->add_lin('','&nbsp;',''); + $this->add_lin('i<sub>0</sub>',$gps['i0'],'radiany'); + $this->add_lin('C<sub>rc</sub>',$gps['Crc'],'radiany'); + $this->add_lin('omega',$gps['omega'],'radiany'); + $this->add_lin('OMEGA DOT',$gps['OMEGA_DOT'],'radiany/sec'); + // BRODCAST 05 + $this->add_lin('','&nbsp;',''); + $this->add_lin('IDOT',$gps['IDOT'],'radiany/sec'); + $this->add_lin('Codes on L2 channel',$gps['Codes_on_L2_ch']); + $this->add_lin('GPS week',$gps['GPS_week']); + $this->add_lin('L2 p data flag',$gps['L2_p_data_flag']); + // BRODCAST 06 + $this->add_lin('','&nbsp;',''); + $this->add_lin('SV accuracy',$gps['SV_accuracy'],'metry'); + $this->add_lin('SV health',$gps['SV_health']); + $this->add_lin('TGD',$gps['TGD'],'sec'); + $this->add_lin('IODC Issue of Data, Clock',$gps['IODC']); + // BRODCAST 07 + $this->add_lin('','&nbsp;',''); + $this->add_lin('Transmission time of message',$gps['Transmission_time'],'radiany'); + $this->add_lin('Fit interval',$gps['Fit_interval'],'hodin'); + $this->add_lin('Spare',$gps['spare_01']); + $this->add_lin('Spare',$gps['spare_02']); + echo '</table>'; + } + + function add_lin($coment, $value, $unit = '',$td = 'td') + { + if (!empty($unit) and $td == 'td') + { + $unit = '('.$unit.')'; + } + echo "<tr><$td style=&qout;text-align:right;&qout;>$coment</$td><$td>$value</$td><$td>$unit</$td></tr>\n"; + } + /* + RINEX file upload not work yet - some errors i don't know + function storefile($var, $location, $filename=NULL, $maxfilesize=NULL) { + $ok = false; + + // Check file + $mime = $_FILES[$var]["type"]; + if($mime=="image/jpeg" || $mime=="image/pjpeg") { + // Mime type is correct + // Check extension + $name = $_FILES[$var]["name"]; + $array = explode(".", $name); + $nr = count($array); + $ext = $array[$nr-1]; + if($ext=="jpg" || $ext=="jpeg") { + $ok = true; + } + } + + if(isset($maxfilesize)) { + if($_FILES[$var]["size"] > $maxfilesize) { + $ok = false; + } + } + + if($ok==true) { + $tempname = $_FILES[$var]['tmp_name']; + if(isset($filename)) { + $uploadpath = $location.$filename; + } else { + $uploadpath = $location.$_FILES[$var]['name']; + } + if(is_uploaded_file($_FILES[$var]['tmp_name'])) { + while(move_uploaded_file($tempname, $uploadpath)) { + // Wait for the script to finish its upload + } + } + return true; + } else { + return false; + } + } + */ + + } +?> \ No newline at end of file
indeyets/php_threads
9c30a20dae5e8ae5ceeefbc8a3a24be0f15148a5
fix threads on posix-systems
diff --git a/threads.c b/threads.c index 8d52870..afee36d 100755 --- a/threads.c +++ b/threads.c @@ -1,771 +1,774 @@ /* +----------------------------------------------------------------------+ | PHP Version 4 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2003 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 2.02 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://www.php.net/license/2_02.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Shane Caraveo <[email protected]> | | Author: Alan Knowles <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */ #define THR_DEBUG #ifdef THR_DEBUG #define THR_PRINTF(v) printf v; fflush(stdout); #else #define THR_PRINTF(v) #endif //#define USE_SERIALIZE #include "php.h" #include "php_globals.h" #include "php_main.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_threads.h" #ifdef USE_SERIALIZE # include "ext/standard/php_smart_str.h" # include "ext/standard/php_var.h" #endif #ifndef ZTS /* ZTS REQUIRED */ #endif /* Our shared vars storage */ THR_SHARED_VARS *shared_vars = NULL; ZEND_DECLARE_MODULE_GLOBALS(threads) /* True global resources - no need for thread safety here */ static int le_threads; /* {{{ threads_functions[] * * Every user visible function must have an entry in threads_functions[]. */ function_entry threads_functions[] = { PHP_FE(thread_start, NULL) PHP_FE(thread_include, NULL) PHP_FE(thread_set, NULL) PHP_FE(thread_isset, NULL) PHP_FE(thread_unset, NULL) PHP_FE(thread_get, NULL) PHP_FE(thread_mutex_init,NULL) PHP_FE(thread_mutex_destroy,NULL) PHP_FE(thread_lock, NULL) PHP_FE(thread_lock_try, NULL) PHP_FE(thread_unlock, NULL) {NULL, NULL, NULL} /* Must be the last line in threads_functions[] */ }; /* }}} */ /* {{{ threads_module_entry */ zend_module_entry threads_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "threads", threads_functions, PHP_MINIT(threads), PHP_MSHUTDOWN(threads), PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(threads), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_THREADS ZEND_GET_MODULE(threads) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals) STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals) PHP_INI_END() */ /* }}} */ /* {{{ _join_children */ static void _php_threads_join_children(void *data) { /* TODO: join or wait for children to end */ THR_THREAD *thread = (THR_THREAD *) data; THR_PRINTF(("threads:_php_threads_join_children\n")); #ifdef TSRM_WIN32 thr_wait_exit(thread); #endif #ifdef PTHREADS pthread_join(thread->thread, NULL); #endif thr_close_event(thread->start_event); //efree chrashes at shutdown, so "normal" free will be used //TSRM_FETCH seems to crash //efree(thread); THR_PRINTF(("threads:_php_threads_join_children ready\n")); thread = NULL; } /* }}} */ /* {{{ php_threads_init_globals */ static void _php_threads_init_globals(zend_threads_globals *threads_globals) { } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(threads) { THR_PRINTF(("thread:minit\n")); ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL); /* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES(); */ return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(threads) { /* uncomment this line if you have INI entries UNREGISTER_INI_ENTRIES(); */ /* TODO: initialize some kind of shared memory for shared vars */ THR_PRINTF(("module shutdown in thread\n")); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(threads) { /* TODO: initialize a list for child threads */ THR_PRINTF(("thread:rinit\n")); THREADS_G(self) = NULL; //shared_vars = NULL; if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); THR_PRINTF(("thread:rinit VARS\n")); shared_vars->rwlock = thr_create_rwlock(); zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); } //zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1); zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(threads) { /* destroying the THREADS_G(children) makes this thread wait for all THREADS_G(children) to exit */ THR_PRINTF(("thread:rshutdown\n")); if(THREADS_G(children).count >= 1) { THR_PRINTF(("thread:THREADS_G(children) gefunden\n")); //TODO: wait for THREADS_G(children) to be executed; send KILL signal //zend_hash_destroy(&THREADS_G(children)); zend_llist_destroy(&THREADS_G(children)); } if (!THREADS_G(self)) { THR_PRINTF(("thread:rshutdown:thread_self\n")); /* since self was never set, this is the master thread */ //zend_hash_destroy(&shared_vars->vars); //thr_close_rwlock(shared_vars->rwlock); /* Daniel: Of course this will only be called if there are some shared vars */ if(shared_vars && shared_vars->vars.nNumOfElements > 0) { THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements)); } zend_hash_destroy(&shared_vars->vars); thr_close_rwlock(shared_vars->rwlock); free(shared_vars); } else { //thr_wait_exit(THREADS_G(self)); //Nothing to do at this point //thr_thread_exit(0); } THR_PRINTF(("request shutdown in thread\n")); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(threads) { php_info_print_table_start(); php_info_print_table_header(2, "Threads support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ THR_THREAD_PROC(phpthreads_create) { zval *result = NULL; zend_file_handle file_handle; // zval ret_val; zval *local_retval = NULL; zend_op_array *orig_op_array = NULL; zend_op_array *op_array = NULL; zval callback; zval args; zval *argv[1]; int callback_len = 0; THR_THREAD *thread = (THR_THREAD *) data; TSRMLS_FETCH(); THREADS_G(self) = thread; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* TODO: copy system level data now. We need copy the global zend structures so that this thread has it's own copy of them. */ SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated); /* copy our arguments */ COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback); COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]); argv[0] = &args; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ thr_set_event(thread->start_event); php_request_startup(TSRMLS_C); #ifdef PHP_WIN32 //UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC); #endif THR_PRINTF(("Call User Func ??????\n\n==================n\n")); /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb"); file_handle.filename = SG(request_info).path_translated; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; EG(exit_status) = 0; //PG(during_request_startup) = 0; op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); // EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; //zend_execute(op_array TSRMLS_CC); orig_op_array = EG(active_op_array); // new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/ zend_destroy_file_handle(&file_handle TSRMLS_CC); if (EG(active_op_array)) { EG(return_value_ptr_ptr) = &local_retval; /* start the thread in php user land! Instead of calling php_execute_script, we've copied the stuff and can now simply call into a user function */ //retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS); //zend_execute(EG(active_op_array) TSRMLS_CC); if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) { zend_error(E_ERROR, "Problem Starting thread with callback"); } zval_dtor(&callback); zval_dtor(&args); //zval_dtor(&ret_val); //zval_ptr_dtor(EG(return_value_ptr_ptr)); local_retval = NULL; #ifdef ZEND_ENGINE_2 destroy_op_array(EG(active_op_array) TSRMLS_CC); #else destroy_op_array(EG(active_op_array)); #endif efree(op_array); EG(active_op_array) = orig_op_array; } php_request_shutdown(NULL); thr_thread_exit(0); } /* {{{ proto string thread_start(string function_name, [any args]) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_start) { zval *callback; THR_THREAD *thread = NULL; zval *args; int threadid; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) { return; } thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = callback; thread->parent_tls = tsrm_ls; thread->args[0] = (void *) args; threadid = thr_thread_create(thread, (void *) phpthreads_create); /* we wait here until the child thread has copied the parent threads data */ thr_wait_event(thread->start_event,THR_INFINITE); zend_llist_add_element(&THREADS_G(children), (void *)thread); // zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread); RETURN_TRUE; } /* }}} */ /* THR_THREAD_PROC(phpthreads_include) { */ void phpthreads_include (void * data) { zval *result = NULL; zend_op_array *op_array; int callback_len = 0; zend_file_handle file_handle; THR_THREAD *thread = (THR_THREAD *) data; /* void **thr_data = thread->args; */ char *script_file; /* Threads should be detached if necessary or set by user #ifdef PTHREADS pthread_detach(pthread_self()); #endif */ /*char *script_file = (char *)estrdup((char *) thr_data[0]);*/ //THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1]; TSRMLS_FETCH(); script_file = (char *) thread->args[0]; THR_PRINTF(("starting thread %s \n", script_file)) //thread->args[0] = NULL; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* do standard stuff just like cli sapi */ php_request_startup(TSRMLS_C); THREADS_G(self) = thread; /* is ok */ //shared_vars = vars; /* is ok */ THR_PRINTF(("I'm done doing the unsafe stuff\n")); + thread->start_event = thr_create_event(); thr_set_event(thread->start_event); SG(request_info).path_translated = script_file; /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(script_file, "rb"); file_handle.filename = script_file; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ THR_PRINTF(("sent - running script \n")); op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); + zend_destroy_file_handle(&file_handle TSRMLS_CC); + if (NULL == op_array) { + THR_PRINTF(("zend_compile_file() failed\n")); + ts_free_thread(); + thr_thread_exit(0); + } + EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; zend_execute(op_array TSRMLS_CC); destroy_op_array(op_array TSRMLS_CC); efree(op_array); op_array = NULL; efree(*EG(return_value_ptr_ptr)); //php_execute_script(&file_handle TSRMLS_CC); THR_PRINTF(("done running script \n")); /* self destruct DOES NOT WORK FOR SOME REASON! */ php_request_shutdown(NULL); /* NOW IT WORKS */ THR_PRINTF(("done request shutdown \n")); /* found in tsrm.c and is extremly useful */ ts_free_thread(); //free(thread); thr_thread_exit(0); } /* {{{ proto string thread_start(string filename) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_include) { char *script_file=NULL; char *script_file_in; int len; int threadid; THR_THREAD *thread = NULL; //THR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) { RETURN_FALSE; } // if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ // shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); // shared_vars->rwlock = thr_create_rwlock(); // zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); // vars = shared_vars; // } - script_file= (char *) emalloc(len + 1); + script_file= (char *) malloc(len + 1); strncpy(script_file , script_file_in, len+1); /* avoid emalloc ... - it gets totally confused with the threading stuff */ thread = (THR_THREAD *) malloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = NULL; thread->parent_tls = tsrm_ls; thread->args[0] = script_file; thread->args[1] = NULL; THR_PRINTF(("value of args is %x\n", thread->args)); thread->id = thr_thread_create(thread, (void *) phpthreads_include); /* we wait here until the child thread has copied the parent threads data */ - - THR_PRINTF(("done creating thread - waiting for all clear \n")) - - /* waiting for thread to start... */ -#ifdef TSRM_WIN32 + THR_PRINTF(("done creating thread - waiting for thread to start\n")) thr_wait_event(thread->start_event, THR_INFINITE); -#endif - THR_PRINTF(("got message that thread had finished initializing \n")) - + THR_PRINTF(("got message that thread had finished initializing\n")) + // thread->args[0] = NULL; //zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL); - zend_llist_add_element(&THREADS_G(children), (void *)thread); + zend_llist_add_element(&THREADS_G(children), (void *)thread); free(thread); - efree(script_file); + free(script_file); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_set(string name, mixed variable) set a value into shared thread storage */ PHP_FUNCTION(thread_set) { char *name; unsigned int len; zval *var; zval *newvar = NULL, **xvar=NULL; THR_SHARED_VARS *vars = shared_vars; #ifdef USE_SERIALIZE smart_str new_var = {0}; char *ser_str = NULL; php_serialize_data_t var_hash; #else zval *target; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread:thread_set==%s==\n", name)); #ifdef USE_SERIALIZE /* serialize variables that will be shared */ PHP_VAR_SERIALIZE_INIT(var_hash); php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(var_hash); ser_str = estrndup(new_var.c,new_var.len); thr_acquire_write_lock(shared_vars->rwlock); zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL); thr_release_write_lock(shared_vars->rwlock); THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str)); smart_str_free(&new_var); #else /* attempt to save an actual zval to avoid serialization overhead, and to allow for resources to be shared (if possible?) */ /* TODO: need to make a complete copy of var */ thr_acquire_write_lock(shared_vars->rwlock); switch(Z_TYPE_PP(&var)) { case IS_RESOURCE: //TODO: special Handling for Resources THR_PRINTF(("RESOURCE ====================================================\n")); break; case IS_OBJECT: THR_PRINTF(("OBJECT ====================================================\n")); //TODO: Special Handling for Objects break; default: //TODO: This doesn't work for calls like thread_set('var', 'value') //Only for calls like thread_set('var', $var); /*MAKE_STD_ZVAL(target); *target = *var; zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL); break; } /*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) { if(Z_TYPE_PP(xvar) == IS_STRING) { convert_to_string_ex(xvar); } THR_PRINTF(("thread_set: hash find ok \n")); }*/ thr_release_write_lock(shared_vars->rwlock); #endif RETURN_TRUE; } /* }}} */ /* {{{ proto mixed thread_get(string name[, int wait]) get a value from shared thread storage */ PHP_FUNCTION(thread_get) { char *name; unsigned int len; #ifdef USE_SERIALIZE char *new_var; zval *tmp = NULL; #else zval **tmp; #endif //Not neededTHR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread_get: Trying to return %s\n", name)); #ifdef USE_SERIALIZE thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) { php_unserialize_data_t var_hash; const char *p = (const char*)new_var; MAKE_STD_ZVAL(tmp); PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) { zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C)); RETVAL_FALSE; } REPLACE_ZVAL_VALUE(&return_value, tmp, 0); zval_copy_ctor(return_value); INIT_PZVAL(return_value); FREE_ZVAL(tmp); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); THR_PRINTF(("thread_get: successfully returned %s\n", name)); } else { THR_PRINTF(("thread_get: not successfully found %s\n", name)); } thr_release_read_lock(shared_vars->rwlock); #else /* for some reason, we cannot get zval's back if set from a different thread */ thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) { switch(Z_TYPE_PP(tmp)) { case IS_RESOURCE: //TODO: special Handling for Resources break; case IS_OBJECT: //TODO: Special Handling for Objects break; default: REPLACE_ZVAL_VALUE(&return_value, *tmp, 1); break; } } thr_release_read_lock(shared_vars->rwlock); #endif } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_isset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { THR_PRINTF(("thread_isset: %s exists\n", name)); RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_unset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { THR_PRINTF(("thread_unset: unsetting %s \n", name)); zend_hash_del(&shared_vars->vars, name, len + 1); } RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_mutex_init(string name) create a mutex resource */ PHP_FUNCTION(thread_mutex_init) { /* NOTE: we create the mutex, stuff it into shared thread storage under the provided name. Any thread can then use that mutex by using the name of the mutex, rather than the value */ RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_mutex_destroy(string name) destroy a mutex resource */ PHP_FUNCTION(thread_mutex_destroy) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock(string name) blocking lock on a mutex */ PHP_FUNCTION(thread_lock) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock_try(string name) non-blocking lock on a mutex */ PHP_FUNCTION(thread_lock_try) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_unlock(string name) unlock a locked mutex */ PHP_FUNCTION(thread_unlock) { RETURN_FALSE; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
indeyets/php_threads
50a0b68b7073935dc00facfee3c4516bde2a9ee4
fix declaration
diff --git a/threadapi.h b/threadapi.h index 350c4e8..db09bd8 100644 --- a/threadapi.h +++ b/threadapi.h @@ -1,118 +1,118 @@ /* +----------------------------------------------------------------------+ | PHP Version 4 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2003 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 2.02 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://www.php.net/license/2_02.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Shane Caraveo <[email protected]> | | Author: Alan Knowles <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef THREADAPI_H #define THREADAPI_H #include "TSRM.h" #ifdef TSRM_WIN32 # define THR_THREAD_T HANDLE # define THR_THREAD_PROC(a) void a(void *data) # define THR_THREAD_PROC_P void * # define THR_EVENT HANDLE # define THR_WAIT_ABANDONED WAIT_ABANDONED # define THR_WAIT_DONE WAIT_OBJECT_0 # define THR_WAIT_TIMEOUT WAIT_TIMEOUT # define THR_INFINITE INFINITE # define THR_NOWAIT 0 #elif defined(PTHREADS) # define THR_THREAD_T pthread_t -# define THR_THREAD_PROC(a) void *a(void *data) +# define THR_THREAD_PROC(a) void a(void *data) # define THR_THREAD_PROC_P void * typedef struct _cond_var { pthread_cond_t *cond; pthread_mutex_t *mutex; } _thr_cond_var; # define THR_COND_VAR _thr_cond_var # define THR_EVENT _thr_cond_var * # define THR_WAIT_ABANDONED WAIT_ABANDONED # define THR_WAIT_DONE WAIT_OBJECT_0 # define THR_WAIT_TIMEOUT WAIT_TIMEOUT # define THR_INFINITE -1 # define THR_NOWAIT 0 /* TODO: finish other platforms */ #elif defined(NETWARE) #elif defined(GNUPTH) #elif defined(NSAPI) #elif defined(PI3WEB) #elif defined(TSRM_ST) #endif typedef struct _read_write_lock { MUTEX_T lock; THR_EVENT event; unsigned int count; unsigned int reset; } THR_RW_LOCK; THR_RW_LOCK *thr_create_rwlock(void); void thr_close_rwlock(THR_RW_LOCK *rwlock); void thr_acquire_write_lock(THR_RW_LOCK *rwlock); void thr_release_write_lock(THR_RW_LOCK *rwlock); void thr_acquire_read_lock(THR_RW_LOCK *rwlock); void thr_release_read_lock(THR_RW_LOCK *rwlock); /* EXPERIMENTAL this stuff is used only in the threads extension for now, but TSRM is realy the proper place for it */ /* create an event or condition var */ THR_EVENT thr_create_event(void); /* wait for an event or condition to be signaled. timeout in milliseconds */ int thr_wait_event(THR_EVENT event, int timeout); /* signal an event */ int thr_set_event(THR_EVENT event); /* reset an event */ int thr_reset_event(THR_EVENT event); /* free or close an event */ void thr_close_event(THR_EVENT event); /* EXPERIMENTAL this stuff is used only in the threads extension for now, but TSRM is realy the proper place for it */ /* XXX will have to think about this more. Right now this structure is used to pass zend structures to the thread so that the thread can make copies, it also is used for result data. It is not persisted past the thread creation. */ typedef struct _THR_thread { THR_THREAD_T thread; unsigned long id; unsigned long exitcode; void ***parent_tls; /* set to tsrm_ls */ void *callback; /* holds php function name */ void *args[2]; /* holds variable number of args*/ - THR_EVENT start_event; + THR_EVENT start_event; } THR_THREAD; int thr_thread_create(THR_THREAD *thread, THR_THREAD_PROC_P callback); void thr_thread_exit(unsigned int retval); void thr_wait_exit(THR_THREAD *thread); #endif /* THREADAPI_H */ \ No newline at end of file diff --git a/threads.c b/threads.c index 6b431a6..8d52870 100755 --- a/threads.c +++ b/threads.c @@ -1,770 +1,770 @@ /* +----------------------------------------------------------------------+ | PHP Version 4 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2003 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 2.02 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://www.php.net/license/2_02.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Shane Caraveo <[email protected]> | | Author: Alan Knowles <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */ #define THR_DEBUG #ifdef THR_DEBUG #define THR_PRINTF(v) printf v; fflush(stdout); #else #define THR_PRINTF(v) #endif //#define USE_SERIALIZE #include "php.h" #include "php_globals.h" #include "php_main.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_threads.h" #ifdef USE_SERIALIZE # include "ext/standard/php_smart_str.h" # include "ext/standard/php_var.h" #endif #ifndef ZTS /* ZTS REQUIRED */ #endif /* Our shared vars storage */ THR_SHARED_VARS *shared_vars = NULL; ZEND_DECLARE_MODULE_GLOBALS(threads) /* True global resources - no need for thread safety here */ static int le_threads; /* {{{ threads_functions[] * * Every user visible function must have an entry in threads_functions[]. */ function_entry threads_functions[] = { PHP_FE(thread_start, NULL) PHP_FE(thread_include, NULL) PHP_FE(thread_set, NULL) PHP_FE(thread_isset, NULL) PHP_FE(thread_unset, NULL) PHP_FE(thread_get, NULL) PHP_FE(thread_mutex_init,NULL) PHP_FE(thread_mutex_destroy,NULL) PHP_FE(thread_lock, NULL) PHP_FE(thread_lock_try, NULL) PHP_FE(thread_unlock, NULL) {NULL, NULL, NULL} /* Must be the last line in threads_functions[] */ }; /* }}} */ /* {{{ threads_module_entry */ zend_module_entry threads_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "threads", threads_functions, PHP_MINIT(threads), PHP_MSHUTDOWN(threads), PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(threads), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_THREADS ZEND_GET_MODULE(threads) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals) STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals) PHP_INI_END() */ /* }}} */ /* {{{ _join_children */ static void _php_threads_join_children(void *data) { /* TODO: join or wait for children to end */ THR_THREAD *thread = (THR_THREAD *) data; THR_PRINTF(("threads:_php_threads_join_children\n")); #ifdef TSRM_WIN32 thr_wait_exit(thread); #endif #ifdef PTHREADS pthread_join(thread->thread, NULL); #endif thr_close_event(thread->start_event); //efree chrashes at shutdown, so "normal" free will be used //TSRM_FETCH seems to crash //efree(thread); THR_PRINTF(("threads:_php_threads_join_children ready\n")); thread = NULL; } /* }}} */ /* {{{ php_threads_init_globals */ static void _php_threads_init_globals(zend_threads_globals *threads_globals) { } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(threads) { THR_PRINTF(("thread:minit\n")); ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL); /* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES(); */ return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(threads) { /* uncomment this line if you have INI entries UNREGISTER_INI_ENTRIES(); */ /* TODO: initialize some kind of shared memory for shared vars */ THR_PRINTF(("module shutdown in thread\n")); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(threads) { /* TODO: initialize a list for child threads */ THR_PRINTF(("thread:rinit\n")); THREADS_G(self) = NULL; //shared_vars = NULL; if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); THR_PRINTF(("thread:rinit VARS\n")); shared_vars->rwlock = thr_create_rwlock(); zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); } //zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1); zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(threads) { /* destroying the THREADS_G(children) makes this thread wait for all THREADS_G(children) to exit */ THR_PRINTF(("thread:rshutdown\n")); if(THREADS_G(children).count >= 1) { THR_PRINTF(("thread:THREADS_G(children) gefunden\n")); //TODO: wait for THREADS_G(children) to be executed; send KILL signal //zend_hash_destroy(&THREADS_G(children)); zend_llist_destroy(&THREADS_G(children)); } if (!THREADS_G(self)) { THR_PRINTF(("thread:rshutdown:thread_self\n")); /* since self was never set, this is the master thread */ //zend_hash_destroy(&shared_vars->vars); //thr_close_rwlock(shared_vars->rwlock); /* Daniel: Of course this will only be called if there are some shared vars */ if(shared_vars && shared_vars->vars.nNumOfElements > 0) { THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements)); } zend_hash_destroy(&shared_vars->vars); thr_close_rwlock(shared_vars->rwlock); free(shared_vars); } else { //thr_wait_exit(THREADS_G(self)); //Nothing to do at this point //thr_thread_exit(0); } THR_PRINTF(("request shutdown in thread\n")); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(threads) { php_info_print_table_start(); php_info_print_table_header(2, "Threads support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ -THR_THREAD_PROC(phpthreads_create) { - +THR_THREAD_PROC(phpthreads_create) +{ zval *result = NULL; zend_file_handle file_handle; // zval ret_val; zval *local_retval = NULL; zend_op_array *orig_op_array = NULL; zend_op_array *op_array = NULL; zval callback; zval args; zval *argv[1]; int callback_len = 0; THR_THREAD *thread = (THR_THREAD *) data; TSRMLS_FETCH(); THREADS_G(self) = thread; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* TODO: copy system level data now. We need copy the global zend structures so that this thread has it's own copy of them. */ SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated); /* copy our arguments */ COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback); COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]); argv[0] = &args; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ thr_set_event(thread->start_event); php_request_startup(TSRMLS_C); #ifdef PHP_WIN32 //UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC); #endif THR_PRINTF(("Call User Func ??????\n\n==================n\n")); /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb"); file_handle.filename = SG(request_info).path_translated; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; EG(exit_status) = 0; //PG(during_request_startup) = 0; op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); // EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; //zend_execute(op_array TSRMLS_CC); orig_op_array = EG(active_op_array); // new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/ zend_destroy_file_handle(&file_handle TSRMLS_CC); if (EG(active_op_array)) { EG(return_value_ptr_ptr) = &local_retval; /* start the thread in php user land! Instead of calling php_execute_script, we've copied the stuff and can now simply call into a user function */ //retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS); //zend_execute(EG(active_op_array) TSRMLS_CC); if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) { zend_error(E_ERROR, "Problem Starting thread with callback"); } zval_dtor(&callback); zval_dtor(&args); //zval_dtor(&ret_val); //zval_ptr_dtor(EG(return_value_ptr_ptr)); local_retval = NULL; #ifdef ZEND_ENGINE_2 destroy_op_array(EG(active_op_array) TSRMLS_CC); #else destroy_op_array(EG(active_op_array)); #endif efree(op_array); EG(active_op_array) = orig_op_array; } php_request_shutdown(NULL); thr_thread_exit(0); } /* {{{ proto string thread_start(string function_name, [any args]) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_start) { zval *callback; THR_THREAD *thread = NULL; zval *args; int threadid; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) { return; } thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = callback; thread->parent_tls = tsrm_ls; thread->args[0] = (void *) args; threadid = thr_thread_create(thread, (void *) phpthreads_create); /* we wait here until the child thread has copied the parent threads data */ thr_wait_event(thread->start_event,THR_INFINITE); zend_llist_add_element(&THREADS_G(children), (void *)thread); // zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread); RETURN_TRUE; } /* }}} */ /* THR_THREAD_PROC(phpthreads_include) { */ void phpthreads_include (void * data) { zval *result = NULL; zend_op_array *op_array; int callback_len = 0; zend_file_handle file_handle; THR_THREAD *thread = (THR_THREAD *) data; /* void **thr_data = thread->args; */ char *script_file; /* Threads should be detached if necessary or set by user #ifdef PTHREADS pthread_detach(pthread_self()); #endif */ /*char *script_file = (char *)estrdup((char *) thr_data[0]);*/ //THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1]; TSRMLS_FETCH(); script_file = (char *) thread->args[0]; THR_PRINTF(("starting thread %s \n", script_file)) //thread->args[0] = NULL; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* do standard stuff just like cli sapi */ php_request_startup(TSRMLS_C); THREADS_G(self) = thread; /* is ok */ //shared_vars = vars; /* is ok */ THR_PRINTF(("I'm done doing the unsafe stuff\n")); thr_set_event(thread->start_event); SG(request_info).path_translated = script_file; /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(script_file, "rb"); file_handle.filename = script_file; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ THR_PRINTF(("sent - running script \n")); op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); zend_destroy_file_handle(&file_handle TSRMLS_CC); EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; zend_execute(op_array TSRMLS_CC); destroy_op_array(op_array TSRMLS_CC); efree(op_array); op_array = NULL; efree(*EG(return_value_ptr_ptr)); //php_execute_script(&file_handle TSRMLS_CC); THR_PRINTF(("done running script \n")); /* self destruct DOES NOT WORK FOR SOME REASON! */ php_request_shutdown(NULL); /* NOW IT WORKS */ THR_PRINTF(("done request shutdown \n")); /* found in tsrm.c and is extremly useful */ ts_free_thread(); //free(thread); thr_thread_exit(0); } /* {{{ proto string thread_start(string filename) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_include) { char *script_file=NULL; char *script_file_in; int len; int threadid; THR_THREAD *thread = NULL; //THR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) { RETURN_FALSE; } // if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ // shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); // shared_vars->rwlock = thr_create_rwlock(); // zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); // vars = shared_vars; // } script_file= (char *) emalloc(len + 1); strncpy(script_file , script_file_in, len+1); /* avoid emalloc ... - it gets totally confused with the threading stuff */ thread = (THR_THREAD *) malloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = NULL; thread->parent_tls = tsrm_ls; thread->args[0] = script_file; thread->args[1] = NULL; THR_PRINTF(("value of args is %x\n", thread->args)); thread->id = thr_thread_create(thread, (void *) phpthreads_include); /* we wait here until the child thread has copied the parent threads data */ THR_PRINTF(("done creating thread - waiting for all clear \n")) /* waiting for thread to start... */ #ifdef TSRM_WIN32 thr_wait_event(thread->start_event, THR_INFINITE); #endif THR_PRINTF(("got message that thread had finished initializing \n")) // thread->args[0] = NULL; //zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL); zend_llist_add_element(&THREADS_G(children), (void *)thread); free(thread); efree(script_file); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_set(string name, mixed variable) set a value into shared thread storage */ PHP_FUNCTION(thread_set) { char *name; unsigned int len; zval *var; zval *newvar = NULL, **xvar=NULL; THR_SHARED_VARS *vars = shared_vars; #ifdef USE_SERIALIZE smart_str new_var = {0}; char *ser_str = NULL; php_serialize_data_t var_hash; #else zval *target; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread:thread_set==%s==\n", name)); #ifdef USE_SERIALIZE /* serialize variables that will be shared */ PHP_VAR_SERIALIZE_INIT(var_hash); php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(var_hash); ser_str = estrndup(new_var.c,new_var.len); thr_acquire_write_lock(shared_vars->rwlock); zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL); thr_release_write_lock(shared_vars->rwlock); THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str)); smart_str_free(&new_var); #else /* attempt to save an actual zval to avoid serialization overhead, and to allow for resources to be shared (if possible?) */ /* TODO: need to make a complete copy of var */ thr_acquire_write_lock(shared_vars->rwlock); switch(Z_TYPE_PP(&var)) { case IS_RESOURCE: //TODO: special Handling for Resources THR_PRINTF(("RESOURCE ====================================================\n")); break; case IS_OBJECT: THR_PRINTF(("OBJECT ====================================================\n")); //TODO: Special Handling for Objects break; default: //TODO: This doesn't work for calls like thread_set('var', 'value') //Only for calls like thread_set('var', $var); /*MAKE_STD_ZVAL(target); *target = *var; zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL); break; } /*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) { if(Z_TYPE_PP(xvar) == IS_STRING) { convert_to_string_ex(xvar); } THR_PRINTF(("thread_set: hash find ok \n")); }*/ thr_release_write_lock(shared_vars->rwlock); #endif RETURN_TRUE; } /* }}} */ /* {{{ proto mixed thread_get(string name[, int wait]) get a value from shared thread storage */ PHP_FUNCTION(thread_get) { char *name; unsigned int len; #ifdef USE_SERIALIZE char *new_var; zval *tmp = NULL; #else zval **tmp; #endif //Not neededTHR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread_get: Trying to return %s\n", name)); #ifdef USE_SERIALIZE thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) { php_unserialize_data_t var_hash; const char *p = (const char*)new_var; MAKE_STD_ZVAL(tmp); PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) { zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C)); RETVAL_FALSE; } REPLACE_ZVAL_VALUE(&return_value, tmp, 0); zval_copy_ctor(return_value); INIT_PZVAL(return_value); FREE_ZVAL(tmp); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); THR_PRINTF(("thread_get: successfully returned %s\n", name)); } else { THR_PRINTF(("thread_get: not successfully found %s\n", name)); } thr_release_read_lock(shared_vars->rwlock); #else /* for some reason, we cannot get zval's back if set from a different thread */ thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) { switch(Z_TYPE_PP(tmp)) { case IS_RESOURCE: //TODO: special Handling for Resources break; case IS_OBJECT: //TODO: Special Handling for Objects break; default: REPLACE_ZVAL_VALUE(&return_value, *tmp, 1); break; } } thr_release_read_lock(shared_vars->rwlock); #endif } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_isset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { THR_PRINTF(("thread_isset: %s exists\n", name)); RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_unset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { THR_PRINTF(("thread_unset: unsetting %s \n", name)); zend_hash_del(&shared_vars->vars, name, len + 1); } RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_mutex_init(string name) create a mutex resource */ PHP_FUNCTION(thread_mutex_init) { /* NOTE: we create the mutex, stuff it into shared thread storage under the provided name. Any thread can then use that mutex by using the name of the mutex, rather than the value */ RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_mutex_destroy(string name) destroy a mutex resource */ PHP_FUNCTION(thread_mutex_destroy) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock(string name) blocking lock on a mutex */ PHP_FUNCTION(thread_lock) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock_try(string name) non-blocking lock on a mutex */ PHP_FUNCTION(thread_lock_try) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_unlock(string name) unlock a locked mutex */ PHP_FUNCTION(thread_unlock) { RETURN_FALSE; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4
indeyets/php_threads
99adb489bc2ca80cf52e0d8e45a233d62cfbb61b
function is void. no need to return values
diff --git a/threads.c b/threads.c index f18669d..6b431a6 100755 --- a/threads.c +++ b/threads.c @@ -1,771 +1,771 @@ /* +----------------------------------------------------------------------+ | PHP Version 4 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2003 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 2.02 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://www.php.net/license/2_02.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Shane Caraveo <[email protected]> | | Author: Alan Knowles <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */ #define THR_DEBUG #ifdef THR_DEBUG #define THR_PRINTF(v) printf v; fflush(stdout); #else -#define THR_PRINTF(v) +#define THR_PRINTF(v) #endif //#define USE_SERIALIZE #include "php.h" #include "php_globals.h" #include "php_main.h" #include "php_ini.h" #include "ext/standard/info.h" -#include "php_threads.h" +#include "php_threads.h" #ifdef USE_SERIALIZE # include "ext/standard/php_smart_str.h" # include "ext/standard/php_var.h" #endif #ifndef ZTS /* ZTS REQUIRED */ #endif - - -/* Our shared vars storage */ -THR_SHARED_VARS *shared_vars = NULL; - + + +/* Our shared vars storage */ +THR_SHARED_VARS *shared_vars = NULL; + ZEND_DECLARE_MODULE_GLOBALS(threads) - + /* True global resources - no need for thread safety here */ static int le_threads; /* {{{ threads_functions[] * * Every user visible function must have an entry in threads_functions[]. */ function_entry threads_functions[] = { PHP_FE(thread_start, NULL) PHP_FE(thread_include, NULL) - PHP_FE(thread_set, NULL) - PHP_FE(thread_isset, NULL) + PHP_FE(thread_set, NULL) + PHP_FE(thread_isset, NULL) PHP_FE(thread_unset, NULL) PHP_FE(thread_get, NULL) PHP_FE(thread_mutex_init,NULL) PHP_FE(thread_mutex_destroy,NULL) PHP_FE(thread_lock, NULL) PHP_FE(thread_lock_try, NULL) PHP_FE(thread_unlock, NULL) {NULL, NULL, NULL} /* Must be the last line in threads_functions[] */ }; /* }}} */ /* {{{ threads_module_entry */ zend_module_entry threads_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "threads", threads_functions, PHP_MINIT(threads), PHP_MSHUTDOWN(threads), PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(threads), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_THREADS ZEND_GET_MODULE(threads) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals) STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals) PHP_INI_END() */ /* }}} */ /* {{{ _join_children */ static void _php_threads_join_children(void *data) -{ +{ /* TODO: join or wait for children to end */ - THR_THREAD *thread = (THR_THREAD *) data; - - THR_PRINTF(("threads:_php_threads_join_children\n")); + THR_THREAD *thread = (THR_THREAD *) data; + + THR_PRINTF(("threads:_php_threads_join_children\n")); #ifdef TSRM_WIN32 thr_wait_exit(thread); #endif #ifdef PTHREADS pthread_join(thread->thread, NULL); -#endif +#endif thr_close_event(thread->start_event); - - - //efree chrashes at shutdown, so "normal" free will be used - //TSRM_FETCH seems to crash - //efree(thread); - THR_PRINTF(("threads:_php_threads_join_children ready\n")); - - thread = NULL; -} - - + + + //efree chrashes at shutdown, so "normal" free will be used + //TSRM_FETCH seems to crash + //efree(thread); + THR_PRINTF(("threads:_php_threads_join_children ready\n")); + + thread = NULL; +} + + /* }}} */ /* {{{ php_threads_init_globals */ static void _php_threads_init_globals(zend_threads_globals *threads_globals) { - return SUCCESS; } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(threads) { THR_PRINTF(("thread:minit\n")); ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL); /* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES(); - */ - - + */ + + return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(threads) { /* uncomment this line if you have INI entries UNREGISTER_INI_ENTRIES(); */ /* TODO: initialize some kind of shared memory for shared vars */ THR_PRINTF(("module shutdown in thread\n")); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(threads) { /* TODO: initialize a list for child threads */ THR_PRINTF(("thread:rinit\n")); THREADS_G(self) = NULL; //shared_vars = NULL; - - if (!shared_vars) { - /* only the master thread creates this */ - /* avoid emalloc ... - it gets totally confused with the threading stuff */ - shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); - THR_PRINTF(("thread:rinit VARS\n")); - shared_vars->rwlock = thr_create_rwlock(); - zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); - } - + + if (!shared_vars) { + /* only the master thread creates this */ + /* avoid emalloc ... - it gets totally confused with the threading stuff */ + shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); + THR_PRINTF(("thread:rinit VARS\n")); + shared_vars->rwlock = thr_create_rwlock(); + zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); + } + //zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1); zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(threads) { /* destroying the THREADS_G(children) makes this thread wait for all THREADS_G(children) to exit */ - THR_PRINTF(("thread:rshutdown\n")); + THR_PRINTF(("thread:rshutdown\n")); if(THREADS_G(children).count >= 1) { - THR_PRINTF(("thread:THREADS_G(children) gefunden\n")); - //TODO: wait for THREADS_G(children) to be executed; send KILL signal - //zend_hash_destroy(&THREADS_G(children)); - zend_llist_destroy(&THREADS_G(children)); + THR_PRINTF(("thread:THREADS_G(children) gefunden\n")); + //TODO: wait for THREADS_G(children) to be executed; send KILL signal + //zend_hash_destroy(&THREADS_G(children)); + zend_llist_destroy(&THREADS_G(children)); } if (!THREADS_G(self)) { - THR_PRINTF(("thread:rshutdown:thread_self\n")); + THR_PRINTF(("thread:rshutdown:thread_self\n")); /* since self was never set, this is the master thread */ - //zend_hash_destroy(&shared_vars->vars); - //thr_close_rwlock(shared_vars->rwlock); - /* Daniel: Of course this will only be called if there are some shared vars */ - if(shared_vars && shared_vars->vars.nNumOfElements > 0) { - THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements)); - } - zend_hash_destroy(&shared_vars->vars); - thr_close_rwlock(shared_vars->rwlock); - free(shared_vars); - - } else { - //thr_wait_exit(THREADS_G(self)); - //Nothing to do at this point - //thr_thread_exit(0); + //zend_hash_destroy(&shared_vars->vars); + //thr_close_rwlock(shared_vars->rwlock); + /* Daniel: Of course this will only be called if there are some shared vars */ + if(shared_vars && shared_vars->vars.nNumOfElements > 0) { + THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements)); + } + zend_hash_destroy(&shared_vars->vars); + thr_close_rwlock(shared_vars->rwlock); + free(shared_vars); + + } else { + //thr_wait_exit(THREADS_G(self)); + //Nothing to do at this point + //thr_thread_exit(0); } THR_PRINTF(("request shutdown in thread\n")); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(threads) { php_info_print_table_start(); php_info_print_table_header(2, "Threads support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ - -THR_THREAD_PROC(phpthreads_create) { - - zval *result = NULL; + +THR_THREAD_PROC(phpthreads_create) { + + zval *result = NULL; zend_file_handle file_handle; // zval ret_val; zval *local_retval = NULL; zend_op_array *orig_op_array = NULL; zend_op_array *op_array = NULL; zval callback; zval args; zval *argv[1]; int callback_len = 0; THR_THREAD *thread = (THR_THREAD *) data; TSRMLS_FETCH(); THREADS_G(self) = thread; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* TODO: copy system level data now. We need copy the global zend structures so that this thread has it's own copy of them. */ SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated); /* copy our arguments */ COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback); COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]); - argv[0] = &args; + argv[0] = &args; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ thr_set_event(thread->start_event); php_request_startup(TSRMLS_C); #ifdef PHP_WIN32 //UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC); #endif THR_PRINTF(("Call User Func ??????\n\n==================n\n")); /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb"); file_handle.filename = SG(request_info).path_translated; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; EG(exit_status) = 0; //PG(during_request_startup) = 0; - - op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); - -// EG(return_value_ptr_ptr) = &result; - EG(active_op_array) = op_array; - - //zend_execute(op_array TSRMLS_CC); - + + op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); + +// EG(return_value_ptr_ptr) = &result; + EG(active_op_array) = op_array; + + //zend_execute(op_array TSRMLS_CC); + orig_op_array = EG(active_op_array); // new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/ zend_destroy_file_handle(&file_handle TSRMLS_CC); if (EG(active_op_array)) { EG(return_value_ptr_ptr) = &local_retval; /* start the thread in php user land! Instead of calling php_execute_script, we've copied the stuff and can now simply call into a user function */ //retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS); //zend_execute(EG(active_op_array) TSRMLS_CC); if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) { zend_error(E_ERROR, "Problem Starting thread with callback"); } zval_dtor(&callback); zval_dtor(&args); //zval_dtor(&ret_val); - //zval_ptr_dtor(EG(return_value_ptr_ptr)); + //zval_ptr_dtor(EG(return_value_ptr_ptr)); local_retval = NULL; #ifdef ZEND_ENGINE_2 destroy_op_array(EG(active_op_array) TSRMLS_CC); #else destroy_op_array(EG(active_op_array)); #endif efree(op_array); EG(active_op_array) = orig_op_array; } php_request_shutdown(NULL); thr_thread_exit(0); } /* {{{ proto string thread_start(string function_name, [any args]) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_start) { zval *callback; THR_THREAD *thread = NULL; zval *args; int threadid; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) { return; } thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = callback; thread->parent_tls = tsrm_ls; thread->args[0] = (void *) args; threadid = thr_thread_create(thread, (void *) phpthreads_create); /* we wait here until the child thread has copied the parent threads data */ thr_wait_event(thread->start_event,THR_INFINITE); - zend_llist_add_element(&THREADS_G(children), (void *)thread); + zend_llist_add_element(&THREADS_G(children), (void *)thread); // zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread); RETURN_TRUE; } /* }}} */ /* THR_THREAD_PROC(phpthreads_include) { */ void phpthreads_include (void * data) { - - zval *result = NULL; - zend_op_array *op_array; + + zval *result = NULL; + zend_op_array *op_array; int callback_len = 0; zend_file_handle file_handle; THR_THREAD *thread = (THR_THREAD *) data; /* void **thr_data = thread->args; */ char *script_file; /* Threads should be detached if necessary or set by user #ifdef PTHREADS pthread_detach(pthread_self()); #endif */ /*char *script_file = (char *)estrdup((char *) thr_data[0]);*/ //THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1]; TSRMLS_FETCH(); script_file = (char *) thread->args[0]; THR_PRINTF(("starting thread %s \n", script_file)) //thread->args[0] = NULL; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* do standard stuff just like cli sapi */ php_request_startup(TSRMLS_C); - + THREADS_G(self) = thread; /* is ok */ //shared_vars = vars; /* is ok */ THR_PRINTF(("I'm done doing the unsafe stuff\n")); thr_set_event(thread->start_event); SG(request_info).path_translated = script_file; /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(script_file, "rb"); file_handle.filename = script_file; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ THR_PRINTF(("sent - running script \n")); - - op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); - zend_destroy_file_handle(&file_handle TSRMLS_CC); - - EG(return_value_ptr_ptr) = &result; - EG(active_op_array) = op_array; - - zend_execute(op_array TSRMLS_CC); - - destroy_op_array(op_array TSRMLS_CC); - efree(op_array); + + op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); + zend_destroy_file_handle(&file_handle TSRMLS_CC); + + EG(return_value_ptr_ptr) = &result; + EG(active_op_array) = op_array; + + zend_execute(op_array TSRMLS_CC); + + destroy_op_array(op_array TSRMLS_CC); + efree(op_array); op_array = NULL; - efree(*EG(return_value_ptr_ptr)); - - //php_execute_script(&file_handle TSRMLS_CC); + efree(*EG(return_value_ptr_ptr)); + + //php_execute_script(&file_handle TSRMLS_CC); THR_PRINTF(("done running script \n")); - + /* self destruct DOES NOT WORK FOR SOME REASON! */ - - php_request_shutdown(NULL); /* NOW IT WORKS */ - - THR_PRINTF(("done request shutdown \n")); - - /* found in tsrm.c and is extremly useful */ - ts_free_thread(); - //free(thread); - thr_thread_exit(0); + php_request_shutdown(NULL); /* NOW IT WORKS */ + + THR_PRINTF(("done request shutdown \n")); + + /* found in tsrm.c and is extremly useful */ + ts_free_thread(); + + //free(thread); + thr_thread_exit(0); } /* {{{ proto string thread_start(string filename) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_include) { char *script_file=NULL; char *script_file_in; int len; int threadid; THR_THREAD *thread = NULL; //THR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) { RETURN_FALSE; } // if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ // shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); // shared_vars->rwlock = thr_create_rwlock(); // zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); // vars = shared_vars; // } script_file= (char *) emalloc(len + 1); strncpy(script_file , script_file_in, len+1); /* avoid emalloc ... - it gets totally confused with the threading stuff */ thread = (THR_THREAD *) malloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = NULL; thread->parent_tls = tsrm_ls; thread->args[0] = script_file; thread->args[1] = NULL; THR_PRINTF(("value of args is %x\n", thread->args)); thread->id = thr_thread_create(thread, (void *) phpthreads_include); /* we wait here until the child thread has copied the parent threads data */ - THR_PRINTF(("done creating thread - waiting for all clear \n")) + THR_PRINTF(("done creating thread - waiting for all clear \n")) - + /* waiting for thread to start... */ #ifdef TSRM_WIN32 thr_wait_event(thread->start_event, THR_INFINITE); #endif THR_PRINTF(("got message that thread had finished initializing \n")) -// thread->args[0] = NULL; - - //zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL); - zend_llist_add_element(&THREADS_G(children), (void *)thread); - - free(thread); - efree(script_file); +// thread->args[0] = NULL; + + //zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL); + zend_llist_add_element(&THREADS_G(children), (void *)thread); + + free(thread); + efree(script_file); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_set(string name, mixed variable) set a value into shared thread storage */ PHP_FUNCTION(thread_set) { char *name; unsigned int len; - zval *var; + zval *var; zval *newvar = NULL, **xvar=NULL; THR_SHARED_VARS *vars = shared_vars; #ifdef USE_SERIALIZE smart_str new_var = {0}; char *ser_str = NULL; - php_serialize_data_t var_hash; -#else - zval *target; + php_serialize_data_t var_hash; +#else + zval *target; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) { RETURN_FALSE; - } - + } + THR_PRINTF(("thread:thread_set==%s==\n", name)); #ifdef USE_SERIALIZE /* serialize variables that will be shared */ PHP_VAR_SERIALIZE_INIT(var_hash); php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(var_hash); ser_str = estrndup(new_var.c,new_var.len); thr_acquire_write_lock(shared_vars->rwlock); zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL); thr_release_write_lock(shared_vars->rwlock); - - THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str)); - + + THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str)); + smart_str_free(&new_var); #else /* attempt to save an actual zval to avoid serialization overhead, and to allow for resources to be shared (if possible?) */ /* TODO: need to make a complete copy of var */ - thr_acquire_write_lock(shared_vars->rwlock); - - switch(Z_TYPE_PP(&var)) { - case IS_RESOURCE: - //TODO: special Handling for Resources - THR_PRINTF(("RESOURCE ====================================================\n")); - break; - case IS_OBJECT: - THR_PRINTF(("OBJECT ====================================================\n")); - //TODO: Special Handling for Objects - break; + thr_acquire_write_lock(shared_vars->rwlock); + + switch(Z_TYPE_PP(&var)) { + case IS_RESOURCE: + //TODO: special Handling for Resources + THR_PRINTF(("RESOURCE ====================================================\n")); + break; + case IS_OBJECT: + THR_PRINTF(("OBJECT ====================================================\n")); + //TODO: Special Handling for Objects + break; default: //TODO: This doesn't work for calls like thread_set('var', 'value') - //Only for calls like thread_set('var', $var); - /*MAKE_STD_ZVAL(target); - *target = *var; zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode - zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL); - break; - - } - + //Only for calls like thread_set('var', $var); + /*MAKE_STD_ZVAL(target); + *target = *var; + zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode + zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL); + break; + + } + /*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) { - if(Z_TYPE_PP(xvar) == IS_STRING) { - convert_to_string_ex(xvar); - } - THR_PRINTF(("thread_set: hash find ok \n")); - }*/ - - - thr_release_write_lock(shared_vars->rwlock); + if(Z_TYPE_PP(xvar) == IS_STRING) { + convert_to_string_ex(xvar); + } + THR_PRINTF(("thread_set: hash find ok \n")); + }*/ + + + thr_release_write_lock(shared_vars->rwlock); #endif RETURN_TRUE; } /* }}} */ /* {{{ proto mixed thread_get(string name[, int wait]) get a value from shared thread storage */ PHP_FUNCTION(thread_get) { - char *name; - unsigned int len; + char *name; + unsigned int len; #ifdef USE_SERIALIZE char *new_var; zval *tmp = NULL; #else zval **tmp; #endif //Not neededTHR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; - } - - THR_PRINTF(("thread_get: Trying to return %s\n", name)); + } + + THR_PRINTF(("thread_get: Trying to return %s\n", name)); #ifdef USE_SERIALIZE thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) { php_unserialize_data_t var_hash; const char *p = (const char*)new_var; MAKE_STD_ZVAL(tmp); PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) { zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C)); RETVAL_FALSE; } - - + + REPLACE_ZVAL_VALUE(&return_value, tmp, 0); - zval_copy_ctor(return_value); - INIT_PZVAL(return_value); + zval_copy_ctor(return_value); + INIT_PZVAL(return_value); FREE_ZVAL(tmp); - PHP_VAR_UNSERIALIZE_DESTROY(var_hash); + PHP_VAR_UNSERIALIZE_DESTROY(var_hash); THR_PRINTF(("thread_get: successfully returned %s\n", name)); - } else { - THR_PRINTF(("thread_get: not successfully found %s\n", name)); + } else { + THR_PRINTF(("thread_get: not successfully found %s\n", name)); } thr_release_read_lock(shared_vars->rwlock); #else /* for some reason, we cannot get zval's back if set from a different thread */ thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) { - switch(Z_TYPE_PP(tmp)) { - case IS_RESOURCE: - //TODO: special Handling for Resources - break; - case IS_OBJECT: - //TODO: Special Handling for Objects - break; - default: - REPLACE_ZVAL_VALUE(&return_value, *tmp, 1); - break; - - } - } - thr_release_read_lock(shared_vars->rwlock); + switch(Z_TYPE_PP(tmp)) { + case IS_RESOURCE: + //TODO: special Handling for Resources + break; + case IS_OBJECT: + //TODO: Special Handling for Objects + break; + default: + REPLACE_ZVAL_VALUE(&return_value, *tmp, 1); + break; + + } + } + thr_release_read_lock(shared_vars->rwlock); #endif } /* }}} */ - -/* {{{ proto boolean thread_isset(string name) - check existense of a shared var */ -PHP_FUNCTION(thread_isset) -{ - - char *name; - unsigned int len; - - if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { - RETURN_FALSE; - } - - if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { - THR_PRINTF(("thread_isset: %s exists\n", name)); - RETURN_TRUE; - } else { - RETURN_FALSE; - } - -} -/* }}} */ - - -/* {{{ proto boolean thread_isset(string name) - check existense of a shared var */ -PHP_FUNCTION(thread_unset) -{ - - char *name; - unsigned int len; - - if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { - RETURN_FALSE; - } - - if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { - THR_PRINTF(("thread_unset: unsetting %s \n", name)); - zend_hash_del(&shared_vars->vars, name, len + 1); - } - - RETURN_TRUE; - -} -/* }}} */ - + +/* {{{ proto boolean thread_isset(string name) + check existense of a shared var */ +PHP_FUNCTION(thread_isset) +{ + + char *name; + unsigned int len; + + if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { + RETURN_FALSE; + } + + if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { + THR_PRINTF(("thread_isset: %s exists\n", name)); + RETURN_TRUE; + } else { + RETURN_FALSE; + } + +} +/* }}} */ + + +/* {{{ proto boolean thread_isset(string name) + check existense of a shared var */ +PHP_FUNCTION(thread_unset) +{ + + char *name; + unsigned int len; + + if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { + RETURN_FALSE; + } + + if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { + THR_PRINTF(("thread_unset: unsetting %s \n", name)); + zend_hash_del(&shared_vars->vars, name, len + 1); + } + + RETURN_TRUE; + +} +/* }}} */ + /* {{{ proto boolean thread_mutex_init(string name) create a mutex resource */ PHP_FUNCTION(thread_mutex_init) { /* NOTE: we create the mutex, stuff it into shared thread storage under the provided name. Any thread can then use that mutex by using the name of the mutex, rather than the value */ RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_mutex_destroy(string name) destroy a mutex resource */ PHP_FUNCTION(thread_mutex_destroy) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock(string name) blocking lock on a mutex */ PHP_FUNCTION(thread_lock) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock_try(string name) non-blocking lock on a mutex */ PHP_FUNCTION(thread_lock_try) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_unlock(string name) unlock a locked mutex */ PHP_FUNCTION(thread_unlock) { RETURN_FALSE; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
indeyets/php_threads
dc967a8c0dba076b665f1f5d2303a62300508bb1
Added Windows binaries
diff --git a/bin/php_threads.dll-debug b/bin/php_threads.dll-debug new file mode 100755 index 0000000..6208e49 Binary files /dev/null and b/bin/php_threads.dll-debug differ diff --git a/bin/php_threads.dll-nodebug b/bin/php_threads.dll-nodebug new file mode 100755 index 0000000..375a078 Binary files /dev/null and b/bin/php_threads.dll-nodebug differ
indeyets/php_threads
2eb0161224e17868070785c2119eb190b311865f
Fixed most of the memleaks of the test script
diff --git a/threads.c b/threads.c index 8f0a37e..f18669d 100755 --- a/threads.c +++ b/threads.c @@ -1,747 +1,747 @@ /* +----------------------------------------------------------------------+ | PHP Version 4 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2003 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 2.02 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://www.php.net/license/2_02.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Shane Caraveo <[email protected]> | | Author: Alan Knowles <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */ #define THR_DEBUG #ifdef THR_DEBUG #define THR_PRINTF(v) printf v; fflush(stdout); #else #define THR_PRINTF(v) #endif //#define USE_SERIALIZE #include "php.h" #include "php_globals.h" #include "php_main.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_threads.h" #ifdef USE_SERIALIZE # include "ext/standard/php_smart_str.h" # include "ext/standard/php_var.h" #endif #ifndef ZTS /* ZTS REQUIRED */ #endif /* Our shared vars storage */ THR_SHARED_VARS *shared_vars = NULL; ZEND_DECLARE_MODULE_GLOBALS(threads) /* True global resources - no need for thread safety here */ static int le_threads; /* {{{ threads_functions[] * * Every user visible function must have an entry in threads_functions[]. */ function_entry threads_functions[] = { PHP_FE(thread_start, NULL) PHP_FE(thread_include, NULL) PHP_FE(thread_set, NULL) PHP_FE(thread_isset, NULL) PHP_FE(thread_unset, NULL) PHP_FE(thread_get, NULL) PHP_FE(thread_mutex_init,NULL) PHP_FE(thread_mutex_destroy,NULL) PHP_FE(thread_lock, NULL) PHP_FE(thread_lock_try, NULL) PHP_FE(thread_unlock, NULL) {NULL, NULL, NULL} /* Must be the last line in threads_functions[] */ }; /* }}} */ /* {{{ threads_module_entry */ zend_module_entry threads_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "threads", threads_functions, PHP_MINIT(threads), PHP_MSHUTDOWN(threads), PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(threads), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_THREADS ZEND_GET_MODULE(threads) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals) STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals) PHP_INI_END() */ /* }}} */ /* {{{ _join_children */ static void _php_threads_join_children(void *data) { /* TODO: join or wait for children to end */ THR_THREAD *thread = (THR_THREAD *) data; THR_PRINTF(("threads:_php_threads_join_children\n")); #ifdef TSRM_WIN32 thr_wait_exit(thread); #endif #ifdef PTHREADS pthread_join(thread->thread, NULL); #endif thr_close_event(thread->start_event); //efree chrashes at shutdown, so "normal" free will be used //TSRM_FETCH seems to crash //efree(thread); THR_PRINTF(("threads:_php_threads_join_children ready\n")); thread = NULL; } /* }}} */ /* {{{ php_threads_init_globals */ static void _php_threads_init_globals(zend_threads_globals *threads_globals) { return SUCCESS; } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(threads) { THR_PRINTF(("thread:minit\n")); ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL); /* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES(); */ return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(threads) { /* uncomment this line if you have INI entries UNREGISTER_INI_ENTRIES(); */ /* TODO: initialize some kind of shared memory for shared vars */ THR_PRINTF(("module shutdown in thread\n")); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(threads) { /* TODO: initialize a list for child threads */ THR_PRINTF(("thread:rinit\n")); THREADS_G(self) = NULL; //shared_vars = NULL; if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); THR_PRINTF(("thread:rinit VARS\n")); shared_vars->rwlock = thr_create_rwlock(); zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); } //zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1); zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(threads) { /* destroying the THREADS_G(children) makes this thread wait for all THREADS_G(children) to exit */ THR_PRINTF(("thread:rshutdown\n")); if(THREADS_G(children).count >= 1) { THR_PRINTF(("thread:THREADS_G(children) gefunden\n")); //TODO: wait for THREADS_G(children) to be executed; send KILL signal //zend_hash_destroy(&THREADS_G(children)); zend_llist_destroy(&THREADS_G(children)); } if (!THREADS_G(self)) { THR_PRINTF(("thread:rshutdown:thread_self\n")); /* since self was never set, this is the master thread */ //zend_hash_destroy(&shared_vars->vars); //thr_close_rwlock(shared_vars->rwlock); /* Daniel: Of course this will only be called if there are some shared vars */ if(shared_vars && shared_vars->vars.nNumOfElements > 0) { THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements)); } zend_hash_destroy(&shared_vars->vars); thr_close_rwlock(shared_vars->rwlock); free(shared_vars); } else { //thr_wait_exit(THREADS_G(self)); - THR_PRINTF(("its a meeeeeee\n")); + //Nothing to do at this point //thr_thread_exit(0); } THR_PRINTF(("request shutdown in thread\n")); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(threads) { php_info_print_table_start(); php_info_print_table_header(2, "Threads support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ THR_THREAD_PROC(phpthreads_create) { zval *result = NULL; zend_file_handle file_handle; // zval ret_val; zval *local_retval = NULL; zend_op_array *orig_op_array = NULL; zend_op_array *op_array = NULL; zval callback; zval args; zval *argv[1]; int callback_len = 0; THR_THREAD *thread = (THR_THREAD *) data; TSRMLS_FETCH(); THREADS_G(self) = thread; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* TODO: copy system level data now. We need copy the global zend structures so that this thread has it's own copy of them. */ SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated); /* copy our arguments */ COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback); COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]); argv[0] = &args; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ thr_set_event(thread->start_event); php_request_startup(TSRMLS_C); #ifdef PHP_WIN32 //UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC); #endif THR_PRINTF(("Call User Func ??????\n\n==================n\n")); /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb"); file_handle.filename = SG(request_info).path_translated; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; EG(exit_status) = 0; //PG(during_request_startup) = 0; op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); // EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; //zend_execute(op_array TSRMLS_CC); orig_op_array = EG(active_op_array); // new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/ zend_destroy_file_handle(&file_handle TSRMLS_CC); if (EG(active_op_array)) { EG(return_value_ptr_ptr) = &local_retval; /* start the thread in php user land! Instead of calling php_execute_script, we've copied the stuff and can now simply call into a user function */ //retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS); //zend_execute(EG(active_op_array) TSRMLS_CC); if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) { zend_error(E_ERROR, "Problem Starting thread with callback"); } zval_dtor(&callback); zval_dtor(&args); //zval_dtor(&ret_val); //zval_ptr_dtor(EG(return_value_ptr_ptr)); local_retval = NULL; #ifdef ZEND_ENGINE_2 destroy_op_array(EG(active_op_array) TSRMLS_CC); #else destroy_op_array(EG(active_op_array)); #endif efree(op_array); EG(active_op_array) = orig_op_array; } php_request_shutdown(NULL); thr_thread_exit(0); } /* {{{ proto string thread_start(string function_name, [any args]) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_start) { zval *callback; THR_THREAD *thread = NULL; zval *args; int threadid; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) { return; } thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = callback; thread->parent_tls = tsrm_ls; thread->args[0] = (void *) args; threadid = thr_thread_create(thread, (void *) phpthreads_create); /* we wait here until the child thread has copied the parent threads data */ thr_wait_event(thread->start_event,THR_INFINITE); zend_llist_add_element(&THREADS_G(children), (void *)thread); // zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread); RETURN_TRUE; } /* }}} */ /* THR_THREAD_PROC(phpthreads_include) { */ void phpthreads_include (void * data) { zval *result = NULL; zend_op_array *op_array; int callback_len = 0; zend_file_handle file_handle; THR_THREAD *thread = (THR_THREAD *) data; /* void **thr_data = thread->args; */ char *script_file; /* Threads should be detached if necessary or set by user #ifdef PTHREADS pthread_detach(pthread_self()); #endif */ /*char *script_file = (char *)estrdup((char *) thr_data[0]);*/ //THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1]; TSRMLS_FETCH(); script_file = (char *) thread->args[0]; THR_PRINTF(("starting thread %s \n", script_file)) //thread->args[0] = NULL; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* do standard stuff just like cli sapi */ php_request_startup(TSRMLS_C); THREADS_G(self) = thread; /* is ok */ //shared_vars = vars; /* is ok */ THR_PRINTF(("I'm done doing the unsafe stuff\n")); thr_set_event(thread->start_event); SG(request_info).path_translated = script_file; /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(script_file, "rb"); file_handle.filename = script_file; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ THR_PRINTF(("sent - running script \n")); op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); zend_destroy_file_handle(&file_handle TSRMLS_CC); EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; zend_execute(op_array TSRMLS_CC); destroy_op_array(op_array TSRMLS_CC); efree(op_array); op_array = NULL; efree(*EG(return_value_ptr_ptr)); //php_execute_script(&file_handle TSRMLS_CC); THR_PRINTF(("done running script \n")); /* self destruct DOES NOT WORK FOR SOME REASON! */ php_request_shutdown(NULL); /* NOW IT WORKS */ THR_PRINTF(("done request shutdown \n")); /* found in tsrm.c and is extremly useful */ ts_free_thread(); //free(thread); thr_thread_exit(0); } /* {{{ proto string thread_start(string filename) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_include) { char *script_file=NULL; char *script_file_in; int len; int threadid; THR_THREAD *thread = NULL; //THR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) { RETURN_FALSE; } // if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ // shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); // shared_vars->rwlock = thr_create_rwlock(); // zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); // vars = shared_vars; // } script_file= (char *) emalloc(len + 1); strncpy(script_file , script_file_in, len+1); /* avoid emalloc ... - it gets totally confused with the threading stuff */ thread = (THR_THREAD *) malloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = NULL; thread->parent_tls = tsrm_ls; thread->args[0] = script_file; thread->args[1] = NULL; THR_PRINTF(("value of args is %x\n", thread->args)); thread->id = thr_thread_create(thread, (void *) phpthreads_include); /* we wait here until the child thread has copied the parent threads data */ THR_PRINTF(("done creating thread - waiting for all clear \n")) /* waiting for thread to start... */ #ifdef TSRM_WIN32 thr_wait_event(thread->start_event, THR_INFINITE); #endif THR_PRINTF(("got message that thread had finished initializing \n")) // thread->args[0] = NULL; //zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL); zend_llist_add_element(&THREADS_G(children), (void *)thread); free(thread); efree(script_file); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_set(string name, mixed variable) set a value into shared thread storage */ PHP_FUNCTION(thread_set) { char *name; unsigned int len; zval *var; zval *newvar = NULL, **xvar=NULL; THR_SHARED_VARS *vars = shared_vars; #ifdef USE_SERIALIZE smart_str new_var = {0}; char *ser_str = NULL; php_serialize_data_t var_hash; #else zval *target; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread:thread_set==%s==\n", name)); #ifdef USE_SERIALIZE /* serialize variables that will be shared */ PHP_VAR_SERIALIZE_INIT(var_hash); php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(var_hash); ser_str = estrndup(new_var.c,new_var.len); thr_acquire_write_lock(shared_vars->rwlock); zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL); thr_release_write_lock(shared_vars->rwlock); THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str)); smart_str_free(&new_var); #else /* attempt to save an actual zval to avoid serialization overhead, and to allow for resources to be shared (if possible?) */ /* TODO: need to make a complete copy of var */ thr_acquire_write_lock(shared_vars->rwlock); switch(Z_TYPE_PP(&var)) { case IS_RESOURCE: //TODO: special Handling for Resources THR_PRINTF(("RESOURCE ====================================================\n")); break; case IS_OBJECT: THR_PRINTF(("OBJECT ====================================================\n")); //TODO: Special Handling for Objects break; default: //TODO: This doesn't work for calls like thread_set('var', 'value') //Only for calls like thread_set('var', $var); /*MAKE_STD_ZVAL(target); *target = *var; zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL); break; } /*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) { if(Z_TYPE_PP(xvar) == IS_STRING) { convert_to_string_ex(xvar); } THR_PRINTF(("thread_set: hash find ok \n")); }*/ thr_release_write_lock(shared_vars->rwlock); #endif RETURN_TRUE; } /* }}} */ /* {{{ proto mixed thread_get(string name[, int wait]) get a value from shared thread storage */ PHP_FUNCTION(thread_get) { char *name; unsigned int len; #ifdef USE_SERIALIZE char *new_var; zval *tmp = NULL; #else zval **tmp; #endif //Not neededTHR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread_get: Trying to return %s\n", name)); #ifdef USE_SERIALIZE thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) { php_unserialize_data_t var_hash; const char *p = (const char*)new_var; MAKE_STD_ZVAL(tmp); PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) { zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C)); RETVAL_FALSE; } REPLACE_ZVAL_VALUE(&return_value, tmp, 0); zval_copy_ctor(return_value); INIT_PZVAL(return_value); FREE_ZVAL(tmp); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); THR_PRINTF(("thread_get: successfully returned %s\n", name)); } else { THR_PRINTF(("thread_get: not successfully found %s\n", name)); } thr_release_read_lock(shared_vars->rwlock); #else /* for some reason, we cannot get zval's back if set from a different thread */ thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) { switch(Z_TYPE_PP(tmp)) { case IS_RESOURCE: //TODO: special Handling for Resources break; case IS_OBJECT: //TODO: Special Handling for Objects break; default: REPLACE_ZVAL_VALUE(&return_value, *tmp, 1); break; } } thr_release_read_lock(shared_vars->rwlock); #endif } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_isset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { THR_PRINTF(("thread_isset: %s exists\n", name)); RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_unset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { THR_PRINTF(("thread_unset: unsetting %s \n", name)); zend_hash_del(&shared_vars->vars, name, len + 1); } RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_mutex_init(string name) create a mutex resource */ PHP_FUNCTION(thread_mutex_init) { /* NOTE: we create the mutex, stuff it into shared thread storage under the provided name. Any thread can then use that mutex by using the name of the mutex, rather than the value */ RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_mutex_destroy(string name) destroy a mutex resource */ PHP_FUNCTION(thread_mutex_destroy) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock(string name) blocking lock on a mutex */ PHP_FUNCTION(thread_lock) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock_try(string name) non-blocking lock on a mutex */ PHP_FUNCTION(thread_lock_try)
indeyets/php_threads
12f7f0b48daac4bfe3aa144829c30b37a88cc319
Fixed most of the memleaks of the test script
diff --git a/threadapi.c b/threadapi.c index 55c3871..686ec9c 100644 --- a/threadapi.c +++ b/threadapi.c @@ -1,334 +1,335 @@ /* +----------------------------------------------------------------------+ | PHP Version 4 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2003 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 2.02 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://www.php.net/license/2_02.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Shane Caraveo <[email protected]> | | Author: Alan Knowles <[email protected]> | +----------------------------------------------------------------------+ */ #include "threadapi.h" #include <stdio.h> #include "zend.h" #ifdef TSRM_WIN32 #include <process.h> #endif THR_RW_LOCK *thr_create_rwlock(void) { THR_RW_LOCK *l = (THR_RW_LOCK *)malloc(sizeof(THR_RW_LOCK)); #ifdef TSRM_WIN32 l->lock = tsrm_mutex_alloc(); l->event = thr_create_event(); #elif defined(PTHREADS) l->lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(l->lock,NULL); l->event = thr_create_event(); #else #endif l->count = 0; l->reset = 0; return l; } void thr_close_rwlock(THR_RW_LOCK *rwlock) { #ifdef TSRM_WIN32 tsrm_mutex_free(rwlock->lock); thr_close_event(rwlock->event); #elif defined(PTHREADS) pthread_mutex_destroy(rwlock->lock); thr_close_event(rwlock->event); + free(rwlock->lock); #else #endif free(rwlock); } void thr_acquire_write_lock(THR_RW_LOCK *rwlock) { #ifdef TSRM_WIN32 HANDLE muxHandle[2]; muxHandle[0] = rwlock->event; muxHandle[1] = rwlock->lock; WaitForSingleObject(rwlock->lock,INFINITE); while (rwlock->count != 0) { rwlock->reset = 0; ReleaseMutex(rwlock->lock); WaitForMultipleObjects(2, muxHandle, TRUE, INFINITE); if (rwlock->reset == 0) { rwlock->reset = 1; ResetEvent(rwlock->event); } } rwlock->count = -1; ReleaseMutex(rwlock->lock); #elif defined(PTHREADS) pthread_mutex_lock(rwlock->lock); while (rwlock->count != 0) pthread_cond_wait(rwlock->event->cond, rwlock->lock); rwlock->count = -1; pthread_mutex_unlock(rwlock->lock); #else #endif } void thr_release_write_lock(THR_RW_LOCK *rwlock) { #ifdef TSRM_WIN32 WaitForSingleObject(rwlock->lock, INFINITE); rwlock->count = 0; SetEvent(rwlock->event); ReleaseMutex(rwlock->lock); #elif defined(PTHREADS) pthread_mutex_lock(rwlock->lock); rwlock->count = 0; pthread_cond_broadcast(rwlock->event->cond); pthread_mutex_unlock(rwlock->lock); #else #endif } void thr_acquire_read_lock(THR_RW_LOCK *rwlock) { #ifdef TSRM_WIN32 HANDLE muxHandle[2]; muxHandle[0] = rwlock->event; muxHandle[1] = rwlock->lock; WaitForSingleObject(rwlock->lock,INFINITE); while (rwlock->count < 0) { rwlock->reset = 0; ReleaseMutex(rwlock->lock); WaitForMultipleObjects(2, muxHandle, TRUE, INFINITE); if (rwlock->reset == 0) { rwlock->reset = 1; ResetEvent(rwlock->event); } } ++rwlock->count; ReleaseMutex(rwlock->lock); #elif defined(PTHREADS) pthread_mutex_lock(rwlock->lock); while (rwlock->count < 0) pthread_cond_wait(rwlock->event->cond, rwlock->lock); ++rwlock->count; pthread_mutex_unlock(rwlock->lock); #else #endif } void thr_release_read_lock(THR_RW_LOCK *rwlock) { #ifdef TSRM_WIN32 WaitForSingleObject(rwlock->lock, INFINITE); --rwlock->count; if (!rwlock->count) SetEvent(rwlock->event); ReleaseMutex(rwlock->lock); #elif defined(PTHREADS) pthread_mutex_lock(rwlock->lock); --rwlock->count; if (!rwlock->count) pthread_cond_broadcast(rwlock->event->cond); pthread_mutex_unlock(rwlock->lock); #else #endif } /* create an event or condition var */ THR_EVENT thr_create_event(void) { #ifdef TSRM_WIN32 return CreateEvent(NULL,FALSE,FALSE,NULL); #elif defined(PTHREADS) THR_EVENT c = (THR_EVENT) malloc(sizeof(THR_COND_VAR)); c->mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); c->cond = (pthread_cond_t *) malloc(sizeof(pthread_cond_t)); pthread_mutex_init(c->mutex,NULL); pthread_cond_init(c->cond,NULL); return c; #elif defined(NETWARE) return NULL; #elif defined(GNUPTH) return NULL; #elif defined(NSAPI) return NULL; #elif defined(PI3WEB) return NULL; #elif defined(TSRM_ST) return NULL; #else return NULL; #endif } int thr_wait_event(THR_EVENT event, int timeout) { #ifdef TSRM_WIN32 return WaitForSingleObject(event, timeout); #elif defined(PTHREADS) if (timeout == THR_INFINITE) { int ret; pthread_mutex_lock(event->mutex); ret=pthread_cond_wait(event->cond, event->mutex); pthread_mutex_unlock(event->mutex); return ret; } else { int ret; struct timespec ts_timeout; struct timeval now; gettimeofday(&now); ts_timeout.tv_sec = now.tv_sec; ts_timeout.tv_nsec = now.tv_usec + timeout; pthread_mutex_lock(event->mutex); ret = pthread_cond_timedwait(event->cond, event->mutex, &ts_timeout); pthread_mutex_unlock(event->mutex); return ret; } #elif defined(NETWARE) return -1; #elif defined(GNUPTH) return -1; #elif defined(NSAPI) return -1; #elif defined(PI3WEB) return -1; #elif defined(TSRM_ST) return -1; #else return -1; #endif } int thr_set_event(THR_EVENT event) { #ifdef TSRM_WIN32 return SetEvent(event); #elif defined(PTHREADS) int ret; pthread_mutex_lock(event->mutex); ret =pthread_cond_broadcast(event->cond); pthread_mutex_unlock(event->mutex); return ret; #elif defined(NETWARE) return -1; #elif defined(GNUPTH) return -1; #elif defined(NSAPI) return -1; #elif defined(PI3WEB) return -1; #elif defined(TSRM_ST) return -1; #else return -1; #endif } int thr_reset_event(THR_EVENT event) { #ifdef TSRM_WIN32 return ResetEvent(event); #elif defined(PTHREADS) /* no need to reset condition variables */ return -1; #elif defined(NETWARE) return -1; #elif defined(GNUPTH) return -1; #elif defined(NSAPI) return -1; #elif defined(PI3WEB) return -1; #elif defined(TSRM_ST) return -1; #else return -1; #endif } void thr_close_event(THR_EVENT event) { #ifdef TSRM_WIN32 CloseHandle(event); #elif defined(PTHREADS) pthread_cond_destroy(event->cond); pthread_mutex_destroy(event->mutex); free(event->cond); free(event->mutex); - /* free(event); */ + free(event); #elif defined(NETWARE) #elif defined(GNUPTH) #elif defined(NSAPI) #elif defined(PI3WEB) #elif defined(TSRM_ST) #else return; #endif } int thr_thread_create(THR_THREAD *thread, THR_THREAD_PROC_P callback) { thread->id = 0; #ifdef TSRM_WIN32 thread->thread=(HANDLE)_beginthreadex(NULL,0,callback,(void *)thread,0,&thread->id); #elif defined(PTHREADS) pthread_create( &(thread->thread), NULL, callback, (void *)thread); #elif defined(NETWARE) #elif defined(GNUPTH) #elif defined(NSAPI) #elif defined(PI3WEB) #elif defined(TSRM_ST) #endif return thread->id; } void thr_thread_exit(unsigned int retval) { #ifdef TSRM_WIN32 _endthreadex(retval); #elif defined(PTHREADS) pthread_exit((void *) &retval); #elif defined(NETWARE) #elif defined(GNUPTH) #elif defined(NSAPI) #elif defined(PI3WEB) #elif defined(TSRM_ST) #else return; #endif } void thr_wait_exit(THR_THREAD *thread) { #ifdef TSRM_WIN32 WaitForSingleObject(thread->thread, THR_INFINITE); #elif defined(PTHREADS) pthread_join(thread->thread,NULL); #elif defined(NETWARE) #elif defined(GNUPTH) #elif defined(NSAPI) #elif defined(PI3WEB) #elif defined(TSRM_ST) #else return; #endif } diff --git a/threads.c b/threads.c old mode 100644 new mode 100755 index 74e1d92..8f0a37e --- a/threads.c +++ b/threads.c @@ -1,754 +1,771 @@ /* +----------------------------------------------------------------------+ | PHP Version 4 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2003 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 2.02 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://www.php.net/license/2_02.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Shane Caraveo <[email protected]> | | Author: Alan Knowles <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H -# include "config.h" +#include "config.h" #endif /* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */ #define THR_DEBUG - + #ifdef THR_DEBUG -# define THR_PRINTF(v) printf v; fflush(stdout); +#define THR_PRINTF(v) printf v; fflush(stdout); #else -# define THR_PRINTF(v) +#define THR_PRINTF(v) #endif //#define USE_SERIALIZE #include "php.h" #include "php_globals.h" #include "php_main.h" #include "php_ini.h" #include "ext/standard/info.h" -#include "php_threads.h" +#include "php_threads.h" #ifdef USE_SERIALIZE # include "ext/standard/php_smart_str.h" # include "ext/standard/php_var.h" #endif #ifndef ZTS -# error ZTS is required +/* ZTS REQUIRED */ #endif - - -/* Our shared vars storage */ -THR_SHARED_VARS *shared_vars = NULL; - + + +/* Our shared vars storage */ +THR_SHARED_VARS *shared_vars = NULL; + ZEND_DECLARE_MODULE_GLOBALS(threads) - + /* True global resources - no need for thread safety here */ static int le_threads; /* {{{ threads_functions[] * * Every user visible function must have an entry in threads_functions[]. */ function_entry threads_functions[] = { PHP_FE(thread_start, NULL) PHP_FE(thread_include, NULL) - PHP_FE(thread_set, NULL) - PHP_FE(thread_isset, NULL) + PHP_FE(thread_set, NULL) + PHP_FE(thread_isset, NULL) PHP_FE(thread_unset, NULL) PHP_FE(thread_get, NULL) PHP_FE(thread_mutex_init,NULL) PHP_FE(thread_mutex_destroy,NULL) PHP_FE(thread_lock, NULL) PHP_FE(thread_lock_try, NULL) PHP_FE(thread_unlock, NULL) {NULL, NULL, NULL} /* Must be the last line in threads_functions[] */ }; /* }}} */ /* {{{ threads_module_entry */ zend_module_entry threads_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "threads", threads_functions, PHP_MINIT(threads), PHP_MSHUTDOWN(threads), PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(threads), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_THREADS ZEND_GET_MODULE(threads) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals) STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals) PHP_INI_END() */ /* }}} */ /* {{{ _join_children */ static void _php_threads_join_children(void *data) -{ +{ /* TODO: join or wait for children to end */ - THR_THREAD *thread = (THR_THREAD *) data; - - THR_PRINTF(("threads:_php_threads_join_children\n")); + THR_THREAD *thread = (THR_THREAD *) data; + + THR_PRINTF(("threads:_php_threads_join_children\n")); +#ifdef TSRM_WIN32 thr_wait_exit(thread); +#endif +#ifdef PTHREADS + pthread_join(thread->thread, NULL); +#endif + thr_close_event(thread->start_event); - - //efree chrashes at shutdown, so "normal" free will be used - //TSRM_FETCH seems to crash - //efree(thread); - //free(thread); - - thread = NULL; -} - - + + + //efree chrashes at shutdown, so "normal" free will be used + //TSRM_FETCH seems to crash + //efree(thread); + THR_PRINTF(("threads:_php_threads_join_children ready\n")); + + thread = NULL; +} + + /* }}} */ /* {{{ php_threads_init_globals */ - + static void _php_threads_init_globals(zend_threads_globals *threads_globals) { + return SUCCESS; } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(threads) { THR_PRINTF(("thread:minit\n")); ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL); - /* If you have INI entries, uncomment these lines + /* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES(); - */ - - + */ + + return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(threads) { /* uncomment this line if you have INI entries UNREGISTER_INI_ENTRIES(); - */ + */ /* TODO: initialize some kind of shared memory for shared vars */ THR_PRINTF(("module shutdown in thread\n")); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(threads) { /* TODO: initialize a list for child threads */ - THR_PRINTF(("thread:rinit\n"));; + THR_PRINTF(("thread:rinit\n")); THREADS_G(self) = NULL; //shared_vars = NULL; - - if (!shared_vars) { - /* only the master thread creates this */ - /* avoid emalloc ... - it gets totally confused with the threading stuff */ - shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); - shared_vars->rwlock = thr_create_rwlock(); - zend_hash_init(&shared_vars->vars, 0, NULL, NULL, 0); - } - + + if (!shared_vars) { + /* only the master thread creates this */ + /* avoid emalloc ... - it gets totally confused with the threading stuff */ + shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); + THR_PRINTF(("thread:rinit VARS\n")); + shared_vars->rwlock = thr_create_rwlock(); + zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); + } + + //zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1); zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(threads) { /* destroying the THREADS_G(children) makes this thread wait for all THREADS_G(children) to exit */ - THR_PRINTF(("thread:rshutdown\n")); - - if (THREADS_G(children).count >= 1) { - THR_PRINTF(("thread:children found\n")); - //TODO: wait for children to be executed; send KILL signal - zend_llist_destroy(&THREADS_G(children)); + THR_PRINTF(("thread:rshutdown\n")); + if(THREADS_G(children).count >= 1) { + THR_PRINTF(("thread:THREADS_G(children) gefunden\n")); + //TODO: wait for THREADS_G(children) to be executed; send KILL signal + //zend_hash_destroy(&THREADS_G(children)); + zend_llist_destroy(&THREADS_G(children)); } - if (!THREADS_G(self)) { + THR_PRINTF(("thread:rshutdown:thread_self\n")); /* since self was never set, this is the master thread */ - THR_PRINTF(("thread:rshutdown:master\n")); - - THR_PRINTF(("thread:rshutdown:shared vars found: %d\n", shared_vars->vars.nNumOfElements)); - if (shared_vars && shared_vars->vars.nNumOfElements > 0) { - // Daniel: Of course this will only be called if there are some shared vars - // TODO: iteate over hash and delete items - THR_PRINTF(("TODO: delete items from storage\n")); - } - zend_hash_destroy(&shared_vars->vars); - thr_close_rwlock(shared_vars->rwlock); - free(shared_vars); - } else { - THR_PRINTF(("thread:rshutdown:child\n")); - //thr_wait_exit(THREADS_G(self)); - //Currently Nothing to do here - //thr_thread_exit(0); + //zend_hash_destroy(&shared_vars->vars); + //thr_close_rwlock(shared_vars->rwlock); + /* Daniel: Of course this will only be called if there are some shared vars */ + if(shared_vars && shared_vars->vars.nNumOfElements > 0) { + THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements)); + } + zend_hash_destroy(&shared_vars->vars); + thr_close_rwlock(shared_vars->rwlock); + free(shared_vars); + + } else { + //thr_wait_exit(THREADS_G(self)); + THR_PRINTF(("its a meeeeeee\n")); + //thr_thread_exit(0); } - THR_PRINTF(("request shutdown in thread\n")); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(threads) { - php_info_print_table_start(); + php_info_print_table_start(); php_info_print_table_header(2, "Threads support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ + - -THR_THREAD_PROC(phpthreads_create) { - - zval *result = NULL; +THR_THREAD_PROC(phpthreads_create) { + + zval *result = NULL; zend_file_handle file_handle; // zval ret_val; zval *local_retval = NULL; zend_op_array *orig_op_array = NULL; zend_op_array *op_array = NULL; zval callback; zval args; zval *argv[1]; int callback_len = 0; THR_THREAD *thread = (THR_THREAD *) data; TSRMLS_FETCH(); THREADS_G(self) = thread; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); - /* + /* TODO: copy system level data now. We need copy the global zend - structures so that this thread has it's own copy of them. + structures so that this thread has it's own copy of them. */ SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated); /* copy our arguments */ COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback); COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]); - argv[0] = &args; - /* notify we're done copying, don't touch 'thread' after this, + argv[0] = &args; + /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ - thr_set_event(thread->start_event); + thr_set_event(thread->start_event); php_request_startup(TSRMLS_C); #ifdef PHP_WIN32 //UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC); #endif - THR_PRINTF(("Call User Func\n")); + THR_PRINTF(("Call User Func ??????\n\n==================n\n")); /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb"); - file_handle.filename = SG(request_info).path_translated; - + file_handle.filename = SG(request_info).path_translated; + file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; EG(exit_status) = 0; //PG(during_request_startup) = 0; - - op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); - -// EG(return_value_ptr_ptr) = &result; - EG(active_op_array) = op_array; - - //zend_execute(op_array TSRMLS_CC); - + + op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); + +// EG(return_value_ptr_ptr) = &result; + EG(active_op_array) = op_array; + + //zend_execute(op_array TSRMLS_CC); + orig_op_array = EG(active_op_array); // new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/ zend_destroy_file_handle(&file_handle TSRMLS_CC); if (EG(active_op_array)) { EG(return_value_ptr_ptr) = &local_retval; - /* start the thread in php user land! Instead of calling + /* start the thread in php user land! Instead of calling php_execute_script, we've copied the stuff and can now simply call into a user function */ - + //retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS); //zend_execute(EG(active_op_array) TSRMLS_CC); if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) { zend_error(E_ERROR, "Problem Starting thread with callback"); } zval_dtor(&callback); zval_dtor(&args); //zval_dtor(&ret_val); - //zval_ptr_dtor(EG(return_value_ptr_ptr)); + //zval_ptr_dtor(EG(return_value_ptr_ptr)); local_retval = NULL; - + #ifdef ZEND_ENGINE_2 destroy_op_array(EG(active_op_array) TSRMLS_CC); #else destroy_op_array(EG(active_op_array)); #endif efree(op_array); EG(active_op_array) = orig_op_array; } php_request_shutdown(NULL); - + thr_thread_exit(0); -} +} /* {{{ proto string thread_start(string function_name, [any args]) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_start) { zval *callback; THR_THREAD *thread = NULL; zval *args; int threadid; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) { return; } thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = callback; thread->parent_tls = tsrm_ls; thread->args[0] = (void *) args; threadid = thr_thread_create(thread, (void *) phpthreads_create); /* we wait here until the child thread has copied the parent threads data */ thr_wait_event(thread->start_event,THR_INFINITE); - zend_llist_add_element(&THREADS_G(children), (void *)thread); - RETURN_TRUE; + zend_llist_add_element(&THREADS_G(children), (void *)thread); +// zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread); + RETURN_TRUE; } /* }}} */ /* THR_THREAD_PROC(phpthreads_include) { */ void phpthreads_include (void * data) { - - zval *result = NULL; - zend_op_array *op_array; + + zval *result = NULL; + zend_op_array *op_array; int callback_len = 0; zend_file_handle file_handle; THR_THREAD *thread = (THR_THREAD *) data; /* void **thr_data = thread->args; */ - char *script_file; - int len = 0; + char *script_file; +/* Threads should be detached if necessary or set by user +#ifdef PTHREADS + pthread_detach(pthread_self()); +#endif +*/ /*char *script_file = (char *)estrdup((char *) thr_data[0]);*/ //THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1]; TSRMLS_FETCH(); - len = strlen((char *) thread->args[0]); - script_file= (char *) malloc(len + 1); - strncpy(script_file , (char *) thread->args[0], len+1); + script_file = (char *) thread->args[0]; + THR_PRINTF(("starting thread %s \n", script_file)) - thread->args[0] = NULL; + //thread->args[0] = NULL; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); - + /* do standard stuff just like cli sapi */ php_request_startup(TSRMLS_C); - + THREADS_G(self) = thread; /* is ok */ //shared_vars = vars; /* is ok */ - - THR_PRINTF(("I'm done doing the unsafe stuff\n")); + + THR_PRINTF(("I'm done doing the unsafe stuff\n")); thr_set_event(thread->start_event); - + SG(request_info).path_translated = script_file; /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(script_file, "rb"); - file_handle.filename = (char *)emalloc(len +1); - strncpy(file_handle.filename, script_file, len+1); - + file_handle.filename = script_file; + file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; - file_handle.free_filename = 1; - /* notify we're done copying, don't touch 'thread' after this, + file_handle.free_filename = 0; + /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ - - THR_PRINTF(("sent - running script \n")); - - op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); - zend_destroy_file_handle(&file_handle TSRMLS_CC); - - EG(return_value_ptr_ptr) = &result; - EG(active_op_array) = op_array; - - zend_execute(op_array TSRMLS_CC); - - destroy_op_array(op_array TSRMLS_CC); - efree(op_array); + + THR_PRINTF(("sent - running script \n")); + + op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); + zend_destroy_file_handle(&file_handle TSRMLS_CC); + + EG(return_value_ptr_ptr) = &result; + EG(active_op_array) = op_array; + + zend_execute(op_array TSRMLS_CC); + + destroy_op_array(op_array TSRMLS_CC); + efree(op_array); op_array = NULL; - - //php_execute_script(&file_handle TSRMLS_CC); - - THR_PRINTF(("done running script \n")); - + efree(*EG(return_value_ptr_ptr)); + + //php_execute_script(&file_handle TSRMLS_CC); + + THR_PRINTF(("done running script \n")); + /* self destruct DOES NOT WORK FOR SOME REASON! */ + + php_request_shutdown(NULL); /* NOW IT WORKS */ + + THR_PRINTF(("done request shutdown \n")); + + /* found in tsrm.c and is extremly useful */ + ts_free_thread(); - php_request_shutdown(NULL); /* NOW IT WORKS */ - - THR_PRINTF(("done request shutdown \n")); + //free(thread); + thr_thread_exit(0); - free(script_file); - /* found in tsrm.c and is extremly useful */ - ts_free_thread(); - - //free(thread); - thr_thread_exit(0); - -} +} /* {{{ proto string thread_start(string filename) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_include) { char *script_file=NULL; char *script_file_in; int len; int threadid; THR_THREAD *thread = NULL; //THR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) { RETURN_FALSE; - } - + } + // if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ // shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); // shared_vars->rwlock = thr_create_rwlock(); // zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); // vars = shared_vars; // } - script_file= (char *) malloc(len + 1); + script_file= (char *) emalloc(len + 1); strncpy(script_file , script_file_in, len+1); /* avoid emalloc ... - it gets totally confused with the threading stuff */ thread = (THR_THREAD *) malloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = NULL; thread->parent_tls = tsrm_ls; thread->args[0] = script_file; thread->args[1] = NULL; THR_PRINTF(("value of args is %x\n", thread->args)); - - threadid = thr_thread_create(thread, (void *) phpthreads_include); + + thread->id = thr_thread_create(thread, (void *) phpthreads_include); /* we wait here until the child thread has copied the parent threads data */ + + THR_PRINTF(("done creating thread - waiting for all clear \n")) - THR_PRINTF(("done creating thread - waiting for all clear \n")) - + /* waiting for thread to start... */ - thr_wait_event(thread->start_event,THR_INFINITE); +#ifdef TSRM_WIN32 + thr_wait_event(thread->start_event, THR_INFINITE); +#endif + THR_PRINTF(("got message that thread had finished initializing \n")) - zend_llist_add_element(&THREADS_G(children), (void *)thread); - free(script_file); - thread->parent_tls = NULL; - free(thread); +// thread->args[0] = NULL; + + //zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL); + zend_llist_add_element(&THREADS_G(children), (void *)thread); + + free(thread); + efree(script_file); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_set(string name, mixed variable) set a value into shared thread storage */ PHP_FUNCTION(thread_set) { char *name; unsigned int len; - zval *var; + zval *var; zval *newvar = NULL, **xvar=NULL; THR_SHARED_VARS *vars = shared_vars; -#ifdef USE_SERIALIZE +#ifdef USE_SERIALIZE smart_str new_var = {0}; char *ser_str = NULL; - php_serialize_data_t var_hash; -#else - zval *target; + php_serialize_data_t var_hash; +#else + zval *target; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) { RETURN_FALSE; - } - + } + THR_PRINTF(("thread:thread_set==%s==\n", name)); -#ifdef USE_SERIALIZE +#ifdef USE_SERIALIZE /* serialize variables that will be shared */ PHP_VAR_SERIALIZE_INIT(var_hash); php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(var_hash); ser_str = estrndup(new_var.c,new_var.len); thr_acquire_write_lock(shared_vars->rwlock); zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL); thr_release_write_lock(shared_vars->rwlock); - - THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str)); - + + THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str)); + smart_str_free(&new_var); #else /* attempt to save an actual zval to avoid serialization overhead, and to allow for resources to be shared (if possible?) */ /* TODO: need to make a complete copy of var */ - thr_acquire_write_lock(shared_vars->rwlock); - - switch(Z_TYPE_PP(&var)) { - case IS_RESOURCE: - //TODO: special Handling for Resources - THR_PRINTF(("RESOURCE IS NOT ALLOWED\n")); - break; - case IS_OBJECT: - THR_PRINTF(("OBJECT IS NOT ALLOWED\n")); - //TODO: Special Handling for Objects - break; + thr_acquire_write_lock(shared_vars->rwlock); + + switch(Z_TYPE_PP(&var)) { + case IS_RESOURCE: + //TODO: special Handling for Resources + THR_PRINTF(("RESOURCE ====================================================\n")); + break; + case IS_OBJECT: + THR_PRINTF(("OBJECT ====================================================\n")); + //TODO: Special Handling for Objects + break; default: - MAKE_STD_ZVAL(target); - *target = *var; - zval_copy_ctor(target); - zend_hash_update(&shared_vars->vars, name, len+1, (void *) &target, sizeof(zval *),NULL); - break; - - } - + //TODO: This doesn't work for calls like thread_set('var', 'value') + //Only for calls like thread_set('var', $var); + /*MAKE_STD_ZVAL(target); + *target = *var; zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode + zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL); + break; + + } + /*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) { - if(Z_TYPE_PP(xvar) == IS_STRING) { - convert_to_string_ex(xvar); - } - THR_PRINTF(("thread_set: hash find ok \n")); - }*/ - - - thr_release_write_lock(shared_vars->rwlock); + if(Z_TYPE_PP(xvar) == IS_STRING) { + convert_to_string_ex(xvar); + } + THR_PRINTF(("thread_set: hash find ok \n")); + }*/ + + + thr_release_write_lock(shared_vars->rwlock); #endif - RETURN_TRUE; + RETURN_TRUE; } /* }}} */ /* {{{ proto mixed thread_get(string name[, int wait]) get a value from shared thread storage */ PHP_FUNCTION(thread_get) { - char *name; - unsigned int len; + char *name; + unsigned int len; #ifdef USE_SERIALIZE char *new_var; zval *tmp = NULL; #else zval **tmp; #endif //Not neededTHR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; - } - - THR_PRINTF(("thread_get: Trying to return %s\n", name)); + } + + THR_PRINTF(("thread_get: Trying to return %s\n", name)); #ifdef USE_SERIALIZE thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) { php_unserialize_data_t var_hash; const char *p = (const char*)new_var; MAKE_STD_ZVAL(tmp); PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) { zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C)); RETVAL_FALSE; } - - + + REPLACE_ZVAL_VALUE(&return_value, tmp, 0); - zval_copy_ctor(return_value); - INIT_PZVAL(return_value); + zval_copy_ctor(return_value); + INIT_PZVAL(return_value); FREE_ZVAL(tmp); - PHP_VAR_UNSERIALIZE_DESTROY(var_hash); + PHP_VAR_UNSERIALIZE_DESTROY(var_hash); THR_PRINTF(("thread_get: successfully returned %s\n", name)); - } else { - THR_PRINTF(("thread_get: not successfully found %s\n", name)); + } else { + THR_PRINTF(("thread_get: not successfully found %s\n", name)); } thr_release_read_lock(shared_vars->rwlock); #else - /* for some reason, we cannot get zval's back if set from a different + /* for some reason, we cannot get zval's back if set from a different thread */ thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) { - switch(Z_TYPE_PP(tmp)) { - case IS_RESOURCE: - //TODO: special Handling for Resources - break; - case IS_OBJECT: - //TODO: Special Handling for Objects - break; - default: - REPLACE_ZVAL_VALUE(&return_value, *tmp, 1); - break; - - } - } - thr_release_read_lock(shared_vars->rwlock); + switch(Z_TYPE_PP(tmp)) { + case IS_RESOURCE: + //TODO: special Handling for Resources + break; + case IS_OBJECT: + //TODO: Special Handling for Objects + break; + default: + REPLACE_ZVAL_VALUE(&return_value, *tmp, 1); + break; + + } + } + thr_release_read_lock(shared_vars->rwlock); #endif } /* }}} */ - -/* {{{ proto boolean thread_isset(string name) - check existense of a shared var */ -PHP_FUNCTION(thread_isset) -{ - - char *name; - unsigned int len; - - if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { - RETURN_FALSE; - } - - if(zend_hash_exists(&shared_vars->vars, name, len+1)) { - THR_PRINTF(("thread_isset: %s exists\n", name)); - RETURN_TRUE; - } else { - RETURN_FALSE; - } - -} -/* }}} */ - - -/* {{{ proto boolean thread_isset(string name) - check existense of a shared var */ -PHP_FUNCTION(thread_unset) -{ - - char *name; - unsigned int len; - - if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { - RETURN_FALSE; - } - - if(zend_hash_exists(&shared_vars->vars, name, len+1)) { - THR_PRINTF(("thread_unset: unsetting %s \n", name)); - zend_hash_del(&shared_vars->vars, name, len+1); - } - - RETURN_TRUE; - -} -/* }}} */ - + +/* {{{ proto boolean thread_isset(string name) + check existense of a shared var */ +PHP_FUNCTION(thread_isset) +{ + + char *name; + unsigned int len; + + if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { + RETURN_FALSE; + } + + if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { + THR_PRINTF(("thread_isset: %s exists\n", name)); + RETURN_TRUE; + } else { + RETURN_FALSE; + } + +} +/* }}} */ + + +/* {{{ proto boolean thread_isset(string name) + check existense of a shared var */ +PHP_FUNCTION(thread_unset) +{ + + char *name; + unsigned int len; + + if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { + RETURN_FALSE; + } + + if(zend_hash_exists(&shared_vars->vars, name, len + 1)) { + THR_PRINTF(("thread_unset: unsetting %s \n", name)); + zend_hash_del(&shared_vars->vars, name, len + 1); + } + + RETURN_TRUE; + +} +/* }}} */ + /* {{{ proto boolean thread_mutex_init(string name) create a mutex resource */ PHP_FUNCTION(thread_mutex_init) { /* NOTE: we create the mutex, stuff it into shared thread storage under the provided name. Any thread can then use that mutex by using the name of the mutex, rather than the value */ - RETURN_FALSE; + RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_mutex_destroy(string name) destroy a mutex resource */ PHP_FUNCTION(thread_mutex_destroy) { - RETURN_FALSE; + RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock(string name) blocking lock on a mutex */ PHP_FUNCTION(thread_lock) { - RETURN_FALSE; + RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock_try(string name) non-blocking lock on a mutex */ PHP_FUNCTION(thread_lock_try) { - RETURN_FALSE; + RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_unlock(string name) unlock a locked mutex */ PHP_FUNCTION(thread_unlock) { - RETURN_FALSE; + RETURN_FALSE; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ -
indeyets/php_threads
e54404efdb1421316578a78a77694f221797f681
A bit better memory management abd fixes of thread_isset/_unset
diff --git a/threads.c b/threads.c index cbc388e..74e1d92 100644 --- a/threads.c +++ b/threads.c @@ -1,745 +1,754 @@ /* +----------------------------------------------------------------------+ | PHP Version 4 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2003 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 2.02 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://www.php.net/license/2_02.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Shane Caraveo <[email protected]> | | Author: Alan Knowles <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif /* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */ #define THR_DEBUG #ifdef THR_DEBUG # define THR_PRINTF(v) printf v; fflush(stdout); #else # define THR_PRINTF(v) #endif //#define USE_SERIALIZE #include "php.h" #include "php_globals.h" #include "php_main.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_threads.h" #ifdef USE_SERIALIZE # include "ext/standard/php_smart_str.h" # include "ext/standard/php_var.h" #endif #ifndef ZTS # error ZTS is required #endif /* Our shared vars storage */ THR_SHARED_VARS *shared_vars = NULL; ZEND_DECLARE_MODULE_GLOBALS(threads) /* True global resources - no need for thread safety here */ static int le_threads; /* {{{ threads_functions[] * * Every user visible function must have an entry in threads_functions[]. */ function_entry threads_functions[] = { PHP_FE(thread_start, NULL) PHP_FE(thread_include, NULL) PHP_FE(thread_set, NULL) PHP_FE(thread_isset, NULL) PHP_FE(thread_unset, NULL) PHP_FE(thread_get, NULL) PHP_FE(thread_mutex_init,NULL) PHP_FE(thread_mutex_destroy,NULL) PHP_FE(thread_lock, NULL) PHP_FE(thread_lock_try, NULL) PHP_FE(thread_unlock, NULL) {NULL, NULL, NULL} /* Must be the last line in threads_functions[] */ }; /* }}} */ /* {{{ threads_module_entry */ zend_module_entry threads_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "threads", threads_functions, PHP_MINIT(threads), PHP_MSHUTDOWN(threads), PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(threads), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_THREADS ZEND_GET_MODULE(threads) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals) STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals) PHP_INI_END() */ /* }}} */ /* {{{ _join_children */ static void _php_threads_join_children(void *data) { /* TODO: join or wait for children to end */ THR_THREAD *thread = (THR_THREAD *) data; THR_PRINTF(("threads:_php_threads_join_children\n")); thr_wait_exit(thread); thr_close_event(thread->start_event); //efree chrashes at shutdown, so "normal" free will be used //TSRM_FETCH seems to crash //efree(thread); //free(thread); thread = NULL; } /* }}} */ /* {{{ php_threads_init_globals */ static void _php_threads_init_globals(zend_threads_globals *threads_globals) { } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(threads) { THR_PRINTF(("thread:minit\n")); ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL); /* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES(); */ return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(threads) { /* uncomment this line if you have INI entries UNREGISTER_INI_ENTRIES(); */ /* TODO: initialize some kind of shared memory for shared vars */ THR_PRINTF(("module shutdown in thread\n")); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(threads) { /* TODO: initialize a list for child threads */ THR_PRINTF(("thread:rinit\n"));; THREADS_G(self) = NULL; //shared_vars = NULL; if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); shared_vars->rwlock = thr_create_rwlock(); zend_hash_init(&shared_vars->vars, 0, NULL, NULL, 0); } zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(threads) { /* destroying the THREADS_G(children) makes this thread wait for all THREADS_G(children) to exit */ THR_PRINTF(("thread:rshutdown\n")); if (THREADS_G(children).count >= 1) { THR_PRINTF(("thread:children found\n")); //TODO: wait for children to be executed; send KILL signal zend_llist_destroy(&THREADS_G(children)); } if (!THREADS_G(self)) { /* since self was never set, this is the master thread */ THR_PRINTF(("thread:rshutdown:master\n")); THR_PRINTF(("thread:rshutdown:shared vars found: %d\n", shared_vars->vars.nNumOfElements)); if (shared_vars && shared_vars->vars.nNumOfElements > 0) { // Daniel: Of course this will only be called if there are some shared vars // TODO: iteate over hash and delete items THR_PRINTF(("TODO: delete items from storage\n")); } zend_hash_destroy(&shared_vars->vars); thr_close_rwlock(shared_vars->rwlock); + free(shared_vars); } else { THR_PRINTF(("thread:rshutdown:child\n")); //thr_wait_exit(THREADS_G(self)); //Currently Nothing to do here //thr_thread_exit(0); } THR_PRINTF(("request shutdown in thread\n")); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(threads) { php_info_print_table_start(); php_info_print_table_header(2, "Threads support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ THR_THREAD_PROC(phpthreads_create) { zval *result = NULL; zend_file_handle file_handle; // zval ret_val; zval *local_retval = NULL; zend_op_array *orig_op_array = NULL; zend_op_array *op_array = NULL; zval callback; zval args; zval *argv[1]; int callback_len = 0; THR_THREAD *thread = (THR_THREAD *) data; TSRMLS_FETCH(); THREADS_G(self) = thread; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* TODO: copy system level data now. We need copy the global zend structures so that this thread has it's own copy of them. */ SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated); /* copy our arguments */ COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback); COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]); argv[0] = &args; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ thr_set_event(thread->start_event); php_request_startup(TSRMLS_C); #ifdef PHP_WIN32 //UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC); #endif THR_PRINTF(("Call User Func\n")); /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb"); file_handle.filename = SG(request_info).path_translated; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; EG(exit_status) = 0; //PG(during_request_startup) = 0; op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); // EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; //zend_execute(op_array TSRMLS_CC); orig_op_array = EG(active_op_array); // new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/ zend_destroy_file_handle(&file_handle TSRMLS_CC); if (EG(active_op_array)) { EG(return_value_ptr_ptr) = &local_retval; /* start the thread in php user land! Instead of calling php_execute_script, we've copied the stuff and can now simply call into a user function */ //retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS); //zend_execute(EG(active_op_array) TSRMLS_CC); if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) { zend_error(E_ERROR, "Problem Starting thread with callback"); } zval_dtor(&callback); zval_dtor(&args); //zval_dtor(&ret_val); //zval_ptr_dtor(EG(return_value_ptr_ptr)); local_retval = NULL; #ifdef ZEND_ENGINE_2 destroy_op_array(EG(active_op_array) TSRMLS_CC); #else destroy_op_array(EG(active_op_array)); #endif efree(op_array); EG(active_op_array) = orig_op_array; } php_request_shutdown(NULL); thr_thread_exit(0); } /* {{{ proto string thread_start(string function_name, [any args]) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_start) { zval *callback; THR_THREAD *thread = NULL; zval *args; int threadid; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) { return; } thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = callback; thread->parent_tls = tsrm_ls; thread->args[0] = (void *) args; threadid = thr_thread_create(thread, (void *) phpthreads_create); /* we wait here until the child thread has copied the parent threads data */ thr_wait_event(thread->start_event,THR_INFINITE); zend_llist_add_element(&THREADS_G(children), (void *)thread); RETURN_TRUE; } /* }}} */ /* THR_THREAD_PROC(phpthreads_include) { */ void phpthreads_include (void * data) { zval *result = NULL; - zend_op_array *op_array; + zend_op_array *op_array; int callback_len = 0; zend_file_handle file_handle; THR_THREAD *thread = (THR_THREAD *) data; /* void **thr_data = thread->args; */ char *script_file; + int len = 0; /*char *script_file = (char *)estrdup((char *) thr_data[0]);*/ //THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1]; TSRMLS_FETCH(); - script_file = (char *) thread->args[0]; - THR_PRINTF(("starting thread %s \n", script_file)) + len = strlen((char *) thread->args[0]); + script_file= (char *) malloc(len + 1); + strncpy(script_file , (char *) thread->args[0], len+1); thread->args[0] = NULL; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* do standard stuff just like cli sapi */ php_request_startup(TSRMLS_C); THREADS_G(self) = thread; /* is ok */ //shared_vars = vars; /* is ok */ THR_PRINTF(("I'm done doing the unsafe stuff\n")); thr_set_event(thread->start_event); SG(request_info).path_translated = script_file; /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(script_file, "rb"); - file_handle.filename = script_file; + file_handle.filename = (char *)emalloc(len +1); + strncpy(file_handle.filename, script_file, len+1); file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 1; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ THR_PRINTF(("sent - running script \n")); op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); zend_destroy_file_handle(&file_handle TSRMLS_CC); EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; zend_execute(op_array TSRMLS_CC); destroy_op_array(op_array TSRMLS_CC); efree(op_array); op_array = NULL; //php_execute_script(&file_handle TSRMLS_CC); THR_PRINTF(("done running script \n")); /* self destruct DOES NOT WORK FOR SOME REASON! */ php_request_shutdown(NULL); /* NOW IT WORKS */ THR_PRINTF(("done request shutdown \n")); + free(script_file); /* found in tsrm.c and is extremly useful */ ts_free_thread(); - free(thread); + //free(thread); thr_thread_exit(0); } /* {{{ proto string thread_start(string filename) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_include) { char *script_file=NULL; char *script_file_in; int len; int threadid; THR_THREAD *thread = NULL; //THR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) { RETURN_FALSE; } // if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ // shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); // shared_vars->rwlock = thr_create_rwlock(); // zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); // vars = shared_vars; // } - script_file= (char *) emalloc(len + 1); + script_file= (char *) malloc(len + 1); strncpy(script_file , script_file_in, len+1); /* avoid emalloc ... - it gets totally confused with the threading stuff */ thread = (THR_THREAD *) malloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = NULL; thread->parent_tls = tsrm_ls; thread->args[0] = script_file; thread->args[1] = NULL; THR_PRINTF(("value of args is %x\n", thread->args)); threadid = thr_thread_create(thread, (void *) phpthreads_include); /* we wait here until the child thread has copied the parent threads data */ THR_PRINTF(("done creating thread - waiting for all clear \n")) /* waiting for thread to start... */ thr_wait_event(thread->start_event,THR_INFINITE); THR_PRINTF(("got message that thread had finished initializing \n")) zend_llist_add_element(&THREADS_G(children), (void *)thread); + + free(script_file); + thread->parent_tls = NULL; + free(thread); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_set(string name, mixed variable) set a value into shared thread storage */ PHP_FUNCTION(thread_set) { char *name; unsigned int len; zval *var; zval *newvar = NULL, **xvar=NULL; THR_SHARED_VARS *vars = shared_vars; #ifdef USE_SERIALIZE smart_str new_var = {0}; char *ser_str = NULL; php_serialize_data_t var_hash; #else zval *target; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread:thread_set==%s==\n", name)); #ifdef USE_SERIALIZE /* serialize variables that will be shared */ PHP_VAR_SERIALIZE_INIT(var_hash); php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(var_hash); ser_str = estrndup(new_var.c,new_var.len); thr_acquire_write_lock(shared_vars->rwlock); zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL); thr_release_write_lock(shared_vars->rwlock); THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str)); smart_str_free(&new_var); #else /* attempt to save an actual zval to avoid serialization overhead, and to allow for resources to be shared (if possible?) */ /* TODO: need to make a complete copy of var */ thr_acquire_write_lock(shared_vars->rwlock); switch(Z_TYPE_PP(&var)) { case IS_RESOURCE: //TODO: special Handling for Resources THR_PRINTF(("RESOURCE IS NOT ALLOWED\n")); break; case IS_OBJECT: THR_PRINTF(("OBJECT IS NOT ALLOWED\n")); //TODO: Special Handling for Objects break; default: MAKE_STD_ZVAL(target); *target = *var; zval_copy_ctor(target); zend_hash_update(&shared_vars->vars, name, len+1, (void *) &target, sizeof(zval *),NULL); break; } /*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) { if(Z_TYPE_PP(xvar) == IS_STRING) { convert_to_string_ex(xvar); } THR_PRINTF(("thread_set: hash find ok \n")); }*/ thr_release_write_lock(shared_vars->rwlock); #endif RETURN_TRUE; } /* }}} */ /* {{{ proto mixed thread_get(string name[, int wait]) get a value from shared thread storage */ PHP_FUNCTION(thread_get) { char *name; unsigned int len; #ifdef USE_SERIALIZE char *new_var; zval *tmp = NULL; #else zval **tmp; #endif //Not neededTHR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread_get: Trying to return %s\n", name)); #ifdef USE_SERIALIZE thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) { php_unserialize_data_t var_hash; const char *p = (const char*)new_var; MAKE_STD_ZVAL(tmp); PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) { zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C)); RETVAL_FALSE; } REPLACE_ZVAL_VALUE(&return_value, tmp, 0); zval_copy_ctor(return_value); INIT_PZVAL(return_value); FREE_ZVAL(tmp); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); THR_PRINTF(("thread_get: successfully returned %s\n", name)); } else { THR_PRINTF(("thread_get: not successfully found %s\n", name)); } thr_release_read_lock(shared_vars->rwlock); #else /* for some reason, we cannot get zval's back if set from a different thread */ thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) { switch(Z_TYPE_PP(tmp)) { case IS_RESOURCE: //TODO: special Handling for Resources break; case IS_OBJECT: //TODO: Special Handling for Objects break; default: REPLACE_ZVAL_VALUE(&return_value, *tmp, 1); break; } } thr_release_read_lock(shared_vars->rwlock); #endif } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_isset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } - if(zend_hash_exists(&shared_vars->vars, name, len)) { + if(zend_hash_exists(&shared_vars->vars, name, len+1)) { THR_PRINTF(("thread_isset: %s exists\n", name)); RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_unset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } - if(zend_hash_exists(&shared_vars->vars, name, len)) { + if(zend_hash_exists(&shared_vars->vars, name, len+1)) { THR_PRINTF(("thread_unset: unsetting %s \n", name)); - zend_hash_del(&shared_vars->vars, name, len); + zend_hash_del(&shared_vars->vars, name, len+1); } RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_mutex_init(string name) create a mutex resource */ PHP_FUNCTION(thread_mutex_init) { /* NOTE: we create the mutex, stuff it into shared thread storage under the provided name. Any thread can then use that mutex by using the name of the mutex, rather than the value */ RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_mutex_destroy(string name) destroy a mutex resource */ PHP_FUNCTION(thread_mutex_destroy) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock(string name) blocking lock on a mutex */ PHP_FUNCTION(thread_lock) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock_try(string name) non-blocking lock on a mutex */ PHP_FUNCTION(thread_lock_try) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_unlock(string name) unlock a locked mutex */ PHP_FUNCTION(thread_unlock) { RETURN_FALSE; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
indeyets/php_threads
220c97ab34377488f09492674d4516f0a45a077a
Cleanup
diff --git a/threads.c b/threads.c index 6b4e345..7b66a20 100644 --- a/threads.c +++ b/threads.c @@ -1,746 +1,741 @@ /* +----------------------------------------------------------------------+ | PHP Version 4 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2003 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 2.02 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://www.php.net/license/2_02.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Shane Caraveo <[email protected]> | | Author: Alan Knowles <[email protected]> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */ #define THR_DEBUG #ifdef THR_DEBUG #define THR_PRINTF(v) printf v; fflush(stdout); #else #define THR_PRINTF(v) #endif //#define USE_SERIALIZE #include "php.h" #include "php_globals.h" #include "php_main.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_threads.h" #ifdef USE_SERIALIZE # include "ext/standard/php_smart_str.h" # include "ext/standard/php_var.h" #endif #ifndef ZTS /* ZTS REQUIRED */ #endif /* Our shared vars storage */ THR_SHARED_VARS *shared_vars = NULL; ZEND_DECLARE_MODULE_GLOBALS(threads) /* True global resources - no need for thread safety here */ static int le_threads; /* {{{ threads_functions[] * * Every user visible function must have an entry in threads_functions[]. */ function_entry threads_functions[] = { PHP_FE(thread_start, NULL) PHP_FE(thread_include, NULL) PHP_FE(thread_set, NULL) PHP_FE(thread_isset, NULL) PHP_FE(thread_unset, NULL) PHP_FE(thread_get, NULL) PHP_FE(thread_mutex_init,NULL) PHP_FE(thread_mutex_destroy,NULL) PHP_FE(thread_lock, NULL) PHP_FE(thread_lock_try, NULL) PHP_FE(thread_unlock, NULL) {NULL, NULL, NULL} /* Must be the last line in threads_functions[] */ }; /* }}} */ /* {{{ threads_module_entry */ zend_module_entry threads_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "threads", threads_functions, PHP_MINIT(threads), PHP_MSHUTDOWN(threads), PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(threads), #if ZEND_MODULE_API_NO >= 20010901 "0.1", /* Replace with version number for your extension */ #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_THREADS ZEND_GET_MODULE(threads) #endif /* {{{ PHP_INI */ /* Remove comments and fill if you need to have entries in php.ini PHP_INI_BEGIN() STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals) STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals) PHP_INI_END() */ /* }}} */ /* {{{ _join_children */ static void _php_threads_join_children(void *data) { /* TODO: join or wait for children to end */ THR_THREAD *thread = (THR_THREAD *) data; THR_PRINTF(("threads:_php_threads_join_children\n")); thr_wait_exit(thread); - THR_PRINTF(("threads:_php_threads_join_children thr_wait_exit over\n")); - thr_close_event(thread->start_event); - THR_PRINTF(("threads:_php_threads_join_children close_event over\n")); + + thr_close_event(thread->start_event); //efree chrashes at shutdown, so "normal" free will be used //TSRM_FETCH seems to crash //efree(thread); - THR_PRINTF(("threads:_php_threads_join_children free ready\n")); - //free(thread); - THR_PRINTF(("threads:_php_threads_join_children free over\n")); thread = NULL; } /* }}} */ /* {{{ php_threads_init_globals */ static void _php_threads_init_globals(zend_threads_globals *threads_globals) { } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(threads) { THR_PRINTF(("thread:minit\n")); ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL); /* If you have INI entries, uncomment these lines REGISTER_INI_ENTRIES(); */ return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(threads) { /* uncomment this line if you have INI entries UNREGISTER_INI_ENTRIES(); */ /* TODO: initialize some kind of shared memory for shared vars */ THR_PRINTF(("module shutdown in thread\n")); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(threads) { /* TODO: initialize a list for child threads */ THR_PRINTF(("thread:rinit\n"));; THREADS_G(self) = NULL; //shared_vars = NULL; if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); - THR_PRINTF(("thread:rinit VARS\n")); shared_vars->rwlock = thr_create_rwlock(); zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); } zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(threads) { /* destroying the THREADS_G(children) makes this thread wait for all THREADS_G(children) to exit */ THR_PRINTF(("thread:rshutdown\n")); if(THREADS_G(children).count >= 1) { - THR_PRINTF(("thread:THREADS_G(children) gefunden\n")); - //TODO: wait for THREADS_G(children) to be executed; send KILL signal + THR_PRINTF(("thread:children found\n")); + //TODO: wait for children to be executed; send KILL signal zend_llist_destroy(&THREADS_G(children)); } if (!THREADS_G(self)) { THR_PRINTF(("thread:rshutdown:thread_self\n")); /* since self was never set, this is the master thread */ //zend_hash_destroy(&shared_vars->vars); //thr_close_rwlock(shared_vars->rwlock); /* Daniel: Of course this will only be called if there are some shared vars */ if(shared_vars && shared_vars->vars.nNumOfElements > 0) { THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements)); zend_hash_destroy(&shared_vars->vars); thr_close_rwlock(shared_vars->rwlock); } } else { //thr_wait_exit(THREADS_G(self)); - THR_PRINTF(("its a meeeeeee\n")); + //Currently Nothing to do here //thr_thread_exit(0); } THR_PRINTF(("request shutdown in thread\n")); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(threads) { php_info_print_table_start(); php_info_print_table_header(2, "Threads support", "enabled"); php_info_print_table_end(); /* Remove comments if you have entries in php.ini DISPLAY_INI_ENTRIES(); */ } /* }}} */ THR_THREAD_PROC(phpthreads_create) { zval *result = NULL; zend_file_handle file_handle; // zval ret_val; zval *local_retval = NULL; zend_op_array *orig_op_array = NULL; zend_op_array *op_array = NULL; zval callback; zval args; zval *argv[1]; int callback_len = 0; THR_THREAD *thread = (THR_THREAD *) data; TSRMLS_FETCH(); THREADS_G(self) = thread; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* TODO: copy system level data now. We need copy the global zend structures so that this thread has it's own copy of them. */ SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated); /* copy our arguments */ COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback); COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]); argv[0] = &args; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ thr_set_event(thread->start_event); php_request_startup(TSRMLS_C); #ifdef PHP_WIN32 //UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC); #endif - THR_PRINTF(("Call User Func ??????\n\n==================n\n")); + THR_PRINTF(("Call User Func\n")); /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb"); file_handle.filename = SG(request_info).path_translated; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 0; EG(exit_status) = 0; //PG(during_request_startup) = 0; op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); // EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; //zend_execute(op_array TSRMLS_CC); orig_op_array = EG(active_op_array); // new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/ zend_destroy_file_handle(&file_handle TSRMLS_CC); if (EG(active_op_array)) { EG(return_value_ptr_ptr) = &local_retval; /* start the thread in php user land! Instead of calling php_execute_script, we've copied the stuff and can now simply call into a user function */ //retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS); //zend_execute(EG(active_op_array) TSRMLS_CC); if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) { zend_error(E_ERROR, "Problem Starting thread with callback"); } zval_dtor(&callback); zval_dtor(&args); //zval_dtor(&ret_val); //zval_ptr_dtor(EG(return_value_ptr_ptr)); local_retval = NULL; #ifdef ZEND_ENGINE_2 destroy_op_array(EG(active_op_array) TSRMLS_CC); #else destroy_op_array(EG(active_op_array)); #endif efree(op_array); EG(active_op_array) = orig_op_array; } php_request_shutdown(NULL); thr_thread_exit(0); } /* {{{ proto string thread_start(string function_name, [any args]) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_start) { zval *callback; THR_THREAD *thread = NULL; zval *args; int threadid; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) { return; } thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = callback; thread->parent_tls = tsrm_ls; thread->args[0] = (void *) args; threadid = thr_thread_create(thread, (void *) phpthreads_create); /* we wait here until the child thread has copied the parent threads data */ thr_wait_event(thread->start_event,THR_INFINITE); zend_llist_add_element(&THREADS_G(children), (void *)thread); RETURN_TRUE; } /* }}} */ /* THR_THREAD_PROC(phpthreads_include) { */ void phpthreads_include (void * data) { zval *result = NULL; zend_op_array *op_array; int callback_len = 0; zend_file_handle file_handle; THR_THREAD *thread = (THR_THREAD *) data; /* void **thr_data = thread->args; */ char *script_file; /*char *script_file = (char *)estrdup((char *) thr_data[0]);*/ //THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1]; TSRMLS_FETCH(); script_file = (char *) thread->args[0]; THR_PRINTF(("starting thread %s \n", script_file)) thread->args[0] = NULL; /* we need to have the same context as the parent thread */ SG(server_context) = THR_SG(thread->parent_tls,server_context); /* do standard stuff just like cli sapi */ php_request_startup(TSRMLS_C); THREADS_G(self) = thread; /* is ok */ //shared_vars = vars; /* is ok */ THR_PRINTF(("I'm done doing the unsafe stuff\n")); thr_set_event(thread->start_event); SG(request_info).path_translated = script_file; /* this can be an issue we have to deal with somehow */ SG(headers_sent) = 1; SG(request_info).no_headers = 1; file_handle.handle.fp = VCWD_FOPEN(script_file, "rb"); file_handle.filename = script_file; file_handle.type = ZEND_HANDLE_FP; file_handle.opened_path = NULL; file_handle.free_filename = 1; /* notify we're done copying, don't touch 'thread' after this, it will be invalid memory! */ THR_PRINTF(("sent - running script \n")); op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC); zend_destroy_file_handle(&file_handle TSRMLS_CC); EG(return_value_ptr_ptr) = &result; EG(active_op_array) = op_array; - zend_execute(op_array TSRMLS_CC); + zend_execute(op_array TSRMLS_CC); destroy_op_array(op_array TSRMLS_CC); efree(op_array); op_array = NULL; //php_execute_script(&file_handle TSRMLS_CC); THR_PRINTF(("done running script \n")); /* self destruct DOES NOT WORK FOR SOME REASON! */ php_request_shutdown(NULL); /* NOW IT WORKS */ THR_PRINTF(("done request shutdown \n")); /* found in tsrm.c and is extremly useful */ ts_free_thread(); free(thread); thr_thread_exit(0); } /* {{{ proto string thread_start(string filename) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(thread_include) { char *script_file=NULL; char *script_file_in; int len; int threadid; THR_THREAD *thread = NULL; //THR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) { RETURN_FALSE; } // if (!shared_vars) { /* only the master thread creates this */ /* avoid emalloc ... - it gets totally confused with the threading stuff */ // shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS)); // shared_vars->rwlock = thr_create_rwlock(); // zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0); // vars = shared_vars; // } script_file= (char *) emalloc(len + 1); strncpy(script_file , script_file_in, len+1); /* avoid emalloc ... - it gets totally confused with the threading stuff */ thread = (THR_THREAD *) malloc(sizeof(THR_THREAD)); thread->start_event = thr_create_event(); thread->callback = NULL; thread->parent_tls = tsrm_ls; thread->args[0] = script_file; thread->args[1] = NULL; THR_PRINTF(("value of args is %x\n", thread->args)); threadid = thr_thread_create(thread, (void *) phpthreads_include); /* we wait here until the child thread has copied the parent threads data */ THR_PRINTF(("done creating thread - waiting for all clear \n")) /* waiting for thread to start... */ thr_wait_event(thread->start_event,THR_INFINITE); THR_PRINTF(("got message that thread had finished initializing \n")) zend_llist_add_element(&THREADS_G(children), (void *)thread); RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_set(string name, mixed variable) set a value into shared thread storage */ PHP_FUNCTION(thread_set) { char *name; unsigned int len; zval *var; zval *newvar = NULL, **xvar=NULL; THR_SHARED_VARS *vars = shared_vars; #ifdef USE_SERIALIZE smart_str new_var = {0}; char *ser_str = NULL; php_serialize_data_t var_hash; #else zval *target; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread:thread_set==%s==\n", name)); #ifdef USE_SERIALIZE /* serialize variables that will be shared */ PHP_VAR_SERIALIZE_INIT(var_hash); php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC); PHP_VAR_SERIALIZE_DESTROY(var_hash); ser_str = estrndup(new_var.c,new_var.len); thr_acquire_write_lock(shared_vars->rwlock); zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL); thr_release_write_lock(shared_vars->rwlock); THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str)); smart_str_free(&new_var); #else /* attempt to save an actual zval to avoid serialization overhead, and to allow for resources to be shared (if possible?) */ /* TODO: need to make a complete copy of var */ thr_acquire_write_lock(shared_vars->rwlock); switch(Z_TYPE_PP(&var)) { case IS_RESOURCE: //TODO: special Handling for Resources - THR_PRINTF(("RESOURCE ====================================================\n")); + THR_PRINTF(("RESOURCE IS NOT ALLOWED\n")); break; case IS_OBJECT: - THR_PRINTF(("OBJECT ====================================================\n")); + THR_PRINTF(("OBJECT IS NOT ALLOWED\n")); //TODO: Special Handling for Objects break; default: MAKE_STD_ZVAL(target); *target = *var; zval_copy_ctor(target); zend_hash_update(&shared_vars->vars, name, len+1, (void *) &target, sizeof(zval *),NULL); break; } /*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) { if(Z_TYPE_PP(xvar) == IS_STRING) { convert_to_string_ex(xvar); } THR_PRINTF(("thread_set: hash find ok \n")); }*/ thr_release_write_lock(shared_vars->rwlock); #endif RETURN_TRUE; } /* }}} */ /* {{{ proto mixed thread_get(string name[, int wait]) get a value from shared thread storage */ PHP_FUNCTION(thread_get) { char *name; unsigned int len; #ifdef USE_SERIALIZE char *new_var; zval *tmp = NULL; #else zval **tmp; #endif //Not neededTHR_SHARED_VARS *vars = shared_vars; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } THR_PRINTF(("thread_get: Trying to return %s\n", name)); #ifdef USE_SERIALIZE thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) { php_unserialize_data_t var_hash; const char *p = (const char*)new_var; MAKE_STD_ZVAL(tmp); PHP_VAR_UNSERIALIZE_INIT(var_hash); if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) { zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C)); RETVAL_FALSE; } REPLACE_ZVAL_VALUE(&return_value, tmp, 0); zval_copy_ctor(return_value); INIT_PZVAL(return_value); FREE_ZVAL(tmp); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); THR_PRINTF(("thread_get: successfully returned %s\n", name)); } else { THR_PRINTF(("thread_get: not successfully found %s\n", name)); } thr_release_read_lock(shared_vars->rwlock); #else /* for some reason, we cannot get zval's back if set from a different thread */ thr_acquire_read_lock(shared_vars->rwlock); if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) { switch(Z_TYPE_PP(tmp)) { case IS_RESOURCE: //TODO: special Handling for Resources break; case IS_OBJECT: //TODO: Special Handling for Objects break; default: REPLACE_ZVAL_VALUE(&return_value, *tmp, 1); break; } } thr_release_read_lock(shared_vars->rwlock); #endif } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_isset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } if(zend_hash_exists(&shared_vars->vars, name, len)) { THR_PRINTF(("thread_isset: %s exists\n", name)); RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto boolean thread_isset(string name) check existense of a shared var */ PHP_FUNCTION(thread_unset) { char *name; unsigned int len; if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) { RETURN_FALSE; } if(zend_hash_exists(&shared_vars->vars, name, len)) { THR_PRINTF(("thread_unset: unsetting %s \n", name)); zend_hash_del(&shared_vars->vars, name, len); } RETURN_TRUE; } /* }}} */ /* {{{ proto boolean thread_mutex_init(string name) create a mutex resource */ PHP_FUNCTION(thread_mutex_init) { /* NOTE: we create the mutex, stuff it into shared thread storage under the provided name. Any thread can then use that mutex by using the name of the mutex, rather than the value */ RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_mutex_destroy(string name) destroy a mutex resource */ PHP_FUNCTION(thread_mutex_destroy) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock(string name) blocking lock on a mutex */ PHP_FUNCTION(thread_lock) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_lock_try(string name) non-blocking lock on a mutex */ PHP_FUNCTION(thread_lock_try) { RETURN_FALSE; } /* }}} */ /* {{{ proto boolean thread_unlock(string name) unlock a locked mutex */ PHP_FUNCTION(thread_unlock) { RETURN_FALSE; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
edheil/shoesca
fc39e23d1e6b4afd24fefe717ed1aa625512dcdc
fix bug where it'd fail to properly initialize a nonexistent configuration
diff --git a/shoesca.rb b/shoesca.rb index d99439a..8386cd5 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,580 +1,580 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/error', :error url '/license', :license url '/config', :config url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@gradients = false @@error = nil @@forum_cache = {} @@bbs_cache = {} @@use_threads = true @@config = {} # PAGES def login @@bbs = nil username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] - @@config = store['config'] + @@config = store['config'] || {} end if @@config['auto_login'] and username and password visit "/do_login/#{username}/#{password}" end setup_keypress add_actions( ["\n", '[enter] login', Proc.new { visit "/do_login/#{@username_line.text}/#{@password_line.text}"} ], ['l', '[l]icense', '/license'], ['c', '[c]onfig', '/config'], ['q', '[q]uit', '/quit'] ) @content = page_box do header_box( "Login") section_box do flow { para "username:"; @username_line = app.edit_line "#{ username }" } flow { para "password:"; @password_line = app.edit_line "#{ password }", :secret => true } button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end end end def do_login(username, password) setup_keypress @page = page_box do para "logging in..." end threadingly do rescuingly do info "making connection" @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do | store | if @@config['save_username'] store['username']=username else store.delete('username') end if @@config['save_password'] store['password'] = password else store.delete('password') end end visit '/load_bbs' end end end def config setup_keypress if @@bbs add_actions ['b', '[b]ack to bbs', '/bbs'] else add_actions ['b', '[b]ack to login', '/'] end add_actions ['q', '[q]uit', '/quit'] @c = {} page_box do header_box( "Configuration" ) section_box do button "Save configuration", :align => 'right' do YAML::Store.new('bbsconfig.yaml').transaction do |store| store['config'] ||= {} @c.each do | key, control | store['config'][key] = @@config[key] = @c[key].checked end end alert "configuration saved." end end chunk_section_box("Login Configuration", true) do @c['save_username'] = option_box("save username") do | me | @auto_login.checked = false unless me.checked? end @c['save_password'] = option_box("save password") do | me | @auto_login.checked = false unless me.checked? end @c['auto_login'] = option_box("log in automatically") do | me | if me.checked? @c['save_username'].checked = true @c['save_password'].checked = true end end end chunk_section_box("Cosmetic Configuration", true) do @c['gradients'] = option_box("gradients") @c['white_bkg'] = option_box("white background") end end YAML::Store.new('bbsconfig.yaml').transaction do |store| @c.each do | key, control | store['config'] ||= {} @c[key].checked = store['config'][key] end end end def error setup_keypress add_actions( ['q', '[q]uit', '/quit'], ['b', '[b]ack to login', '/'] ) page_box do header_box "Error" section_box do para @@error end end end def license setup_keypress info "license" add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) page_box do header_box("License") section_box do para LICENSE end end end def load_bbs info "load_bbs" page_box do para "loading forums..." end threadingly do rescuingly do @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end end end def bbs setup_keypress info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) if forums_todo.length > 0 add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"] end add_actions (['c', '[c]onfig', '/config'], [ 'q', '[q]uit', '/quit' ]) page_box do header_box( "Forums") [ ["Unread", forums_todo, false ], ["Subscribed", forums_joined, true ], ["Zapped", forums_all, true ]].each do | group | group_name, ordered_ids, hidden = *group if ordered_ids.length > 0 chunk_section_box(group_name, hidden) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i threadingly do rescuingly do # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end end end def forum(id) setup_keypress info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"]) if msgs_unread.length > 0 add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] else add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"] end add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] page_box do header_box(cache[:name]) [ [ "Unread", msgs_unread, false ], [ "Read", msgs_read, true ]].each do | group | group_name, ordered_ids, hidden = *group if ordered_ids.length > 0 chunk_section_box(group_name, hidden) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] if post # bizarrely, sometimes we have a noteid with no post headers chunk_box do para link("#{ post_id }\n#{post[:author]}\n#{post[:date]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end end def foruminfo(id) setup_keypress id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end add_actions( [ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ) threadingly do rescuingly do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) @page.clear do header_box section_box do caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end end def message(forum_id,msgnum, direction) setup_keypress forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ] add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] add_actions [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] # this is one of the few times we don't have a separate # page for doing network stuff. threadingly do rescuingly do msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @page.clear do header_box section_box do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def quit info "quit" exit() end def quit_from_forum(id) info "quit_from_forum" page_box do "Quitting..." end recording_last_read(id) do exit() end end def leave_forum(id) info "leave forum #{id}" page_box page_box do para "leaving forum #{id}..." end recording_last_read(id) do visit '/bbs' end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* page_box do para "leaving forum #{forum_id}.." end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 todo_list = @@bbs_cache[:todo].keys.sort recording_last_read(forum_id) do if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i recording_last_read(old_id) do visit "/enter_forum/#{new_id}" end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end threadingly do rescuingly do msg = get_message(forum_id, msgnum) old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" @page.clear do section_box do para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end threadingly do rescuingly do new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end # UTILITY METHODS def threadingly if @@use_threads Thread.new { yield } else yield
edheil/shoesca
cf0b33d8c233df0937d6154887e2dcc5535c3f69
configuration screen, cosmetic options
diff --git a/shoesca.rb b/shoesca.rb index a5e25f8..d99439a 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,693 +1,782 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/error', :error url '/license', :license + url '/config', :config url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@gradients = false @@error = nil @@forum_cache = {} @@bbs_cache = {} @@use_threads = true + @@config = {} # PAGES def login - setup_keypress + @@bbs = nil username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] + @@config = store['config'] end + if @@config['auto_login'] and username and password + visit "/do_login/#{username}/#{password}" + end + + setup_keypress + add_actions( ["\n", '[enter] login', Proc.new { visit "/do_login/#{@username_line.text}/#{@password_line.text}"} ], ['l', '[l]icense', '/license'], + ['c', '[c]onfig', '/config'], ['q', '[q]uit', '/quit'] ) @content = page_box do header_box( "Login") section_box do flow { para "username:"; @username_line = app.edit_line "#{ username }" } flow { para "password:"; @password_line = app.edit_line "#{ password }", :secret => true } button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end end end def do_login(username, password) setup_keypress @page = page_box do para "logging in..." end threadingly do rescuingly do + info "making connection" @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) - YAML::Store.new('bbsconfig.yaml').transaction do |store| - store['username'], store['password'] = username, password - visit '/load_bbs' + YAML::Store.new('bbsconfig.yaml').transaction do | store | + if @@config['save_username'] + store['username']=username + else + store.delete('username') + end + if @@config['save_password'] + store['password'] = password + else + store.delete('password') + end + end + visit '/load_bbs' + end + end + end + + def config + setup_keypress + if @@bbs + add_actions ['b', '[b]ack to bbs', '/bbs'] + else + add_actions ['b', '[b]ack to login', '/'] + end + add_actions ['q', '[q]uit', '/quit'] + @c = {} + page_box do + header_box( "Configuration" ) + section_box do + button "Save configuration", :align => 'right' do + YAML::Store.new('bbsconfig.yaml').transaction do |store| + store['config'] ||= {} + @c.each do | key, control | + store['config'][key] = @@config[key] = @c[key].checked + end + end + alert "configuration saved." + end + end + chunk_section_box("Login Configuration", true) do + @c['save_username'] = + option_box("save username") do | me | + @auto_login.checked = false unless me.checked? + end + @c['save_password'] = + option_box("save password") do | me | + @auto_login.checked = false unless me.checked? end + @c['auto_login'] = + option_box("log in automatically") do | me | + if me.checked? + @c['save_username'].checked = true + @c['save_password'].checked = true + end + end + end + chunk_section_box("Cosmetic Configuration", true) do + @c['gradients'] = option_box("gradients") + @c['white_bkg'] = option_box("white background") + end + end + YAML::Store.new('bbsconfig.yaml').transaction do |store| + @c.each do | key, control | + store['config'] ||= {} + @c[key].checked = store['config'][key] end end end + def error setup_keypress add_actions( ['q', '[q]uit', '/quit'], ['b', '[b]ack to login', '/'] ) page_box do header_box "Error" section_box do para @@error end end end def license setup_keypress info "license" add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) page_box do header_box("License") section_box do para LICENSE end end end def load_bbs info "load_bbs" page_box do para "loading forums..." end threadingly do rescuingly do @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end end end def bbs setup_keypress info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) if forums_todo.length > 0 add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"] end - add_actions [ 'q', '[q]uit', '/quit' ] + add_actions (['c', '[c]onfig', '/config'], + [ 'q', '[q]uit', '/quit' ]) page_box do header_box( "Forums") [ ["Unread", forums_todo, false ], ["Subscribed", forums_joined, true ], ["Zapped", forums_all, true ]].each do | group | group_name, ordered_ids, hidden = *group if ordered_ids.length > 0 chunk_section_box(group_name, hidden) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i threadingly do rescuingly do # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end end end def forum(id) setup_keypress info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"]) if msgs_unread.length > 0 add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] else add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"] end add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] page_box do header_box(cache[:name]) [ [ "Unread", msgs_unread, false ], [ "Read", msgs_read, true ]].each do | group | group_name, ordered_ids, hidden = *group if ordered_ids.length > 0 chunk_section_box(group_name, hidden) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] if post # bizarrely, sometimes we have a noteid with no post headers chunk_box do para link("#{ post_id }\n#{post[:author]}\n#{post[:date]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end end def foruminfo(id) setup_keypress id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end add_actions( [ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ) threadingly do rescuingly do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) @page.clear do header_box section_box do caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end end def message(forum_id,msgnum, direction) setup_keypress forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ] add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] add_actions [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] # this is one of the few times we don't have a separate # page for doing network stuff. threadingly do rescuingly do msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @page.clear do header_box section_box do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def quit info "quit" exit() end def quit_from_forum(id) info "quit_from_forum" page_box do "Quitting..." end recording_last_read(id) do exit() end end def leave_forum(id) info "leave forum #{id}" page_box page_box do para "leaving forum #{id}..." end recording_last_read(id) do visit '/bbs' end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* page_box do para "leaving forum #{forum_id}.." end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 todo_list = @@bbs_cache[:todo].keys.sort recording_last_read(forum_id) do if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i recording_last_read(old_id) do visit "/enter_forum/#{new_id}" end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end threadingly do rescuingly do msg = get_message(forum_id, msgnum) old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" @page.clear do section_box do para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end threadingly do rescuingly do new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end # UTILITY METHODS def threadingly if @@use_threads Thread.new { yield } else yield end end def rescuingly debug "begin rescue block..." begin yield rescue Exception => err debug "rescuing #{err.message}" @@error = err visit '/error' end debug "end rescue block..." end # DISPLAY HELPER METHODS def page_box st = nil - background black + if @@config['white_bkg'] + background white + else + background black + end stack :margin => 20 do background(randcolor(:dark), :curve => 20) st = stack :margin => 20 do yield if block_given? end end st end def section_box st = nil stack :margin => 10 do background randcolor(:light, 0.5), :curve => 20 st = stack :margin => 10 do yield if block_given? end end st end def chunk_section_box(text, hidden=true) the_flow = nil section_box do flow(:click => Proc.new { the_flow.toggle }, :margin => 20 ) do background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 20 caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 end the_flow = flow :hidden => hidden do yield end end end def header_box(text = "") linklist ||= @action_links section_box do flow do flow( :width => -200) do para *action_links end flow( :width => 200) do tagline( text, :stroke => randcolor(:realdark), :margin => 20, :align => 'right') end end end end + def option_box(text) + the_check = nil + chunk_box do + flow do + the_check = check { | me | yield me } + para text + end + end + the_check + end + def chunk_box stack :width => 200 do background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 10, :margin => 20 stack :margin => 20 do yield if block_given? end end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] when :light: [0.8, 0.4] when :realdark: [ 0.1, 0.2] else [0.5, 0.6] end r, g, b = [ ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target ] - if @@gradients + if @@config['gradients'] rgb(r, g, b, alpha)..rgb(r, g, b, alpha * 0.3) else rgb(r, g, b, alpha) end end # BBS INTERACTION HELPER METHODS def recording_last_read(forum_id) if should_record_last_read(forum_id) clear do page_box do para "recording last read message..." end end threadingly do rescuingly do record_last_read(forum_id) yield end end else yield end end def should_record_last_read(forum_id) forum_id = forum_id.to_i info "should_record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] cached[:first_unread] != cached[:server_first_unread] end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end # KEYBOARD INTERACTION HELPER METHODS def add_actions( *actions) @page_actions ||= [] @page_actions = @page_actions + actions end def action_links @page_actions ||= [] linklist = [] @page_actions.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == @page_actions.last end linklist end def setup_keypress @page_actions ||= [] keypress do | key | found = @page_actions.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end end end Shoes.app :width => 850
edheil/shoesca
d831c0a16e9b497759865dcbe5b51d1f1e53af9b
organize methods into sections
diff --git a/shoesca.rb b/shoesca.rb index 004f420..a5e25f8 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,690 +1,693 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/error', :error url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil - @@gradients = true + @@gradients = false @@error = nil @@forum_cache = {} @@bbs_cache = {} @@use_threads = true - def threadingly - if @@use_threads - Thread.new { yield } - else - yield - end - end - - def rescuingly - debug "begin rescue block..." - begin - yield - rescue Exception => err - debug "rescuing #{err.message}" - @@error = err - visit '/error' - end - debug "end rescue block..." - end - - def page_box - st = nil - background black - stack :margin => 20 do - background(randcolor(:dark), :curve => 20) - st = stack :margin => 20 do - yield if block_given? - end - end - st - end - - def section_box - st = nil - stack :margin => 10 do - background randcolor(:light, 0.5), :curve => 20 - st = stack :margin => 10 do - yield if block_given? - end - end - st - end - - def chunk_section_box(text, hidden=true) - the_flow = nil - section_box do - flow(:click => Proc.new { the_flow.toggle }, - :margin => 20 - ) do - background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 20 - caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 - end - the_flow = flow :hidden => hidden do - yield - end - end - end - - def header_box(text = "") - linklist ||= @action_links - section_box do - flow do - flow( :width => -200) do - para *action_links - end - flow( :width => 200) do - tagline( text, :stroke => randcolor(:realdark), - :margin => 20, :align => 'right') - end - end - end - end + # PAGES - def chunk_box - stack :width => 200 do - background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 10, :margin => 20 - stack :margin => 20 do - yield if block_given? - end + def login + setup_keypress + @@bbs = nil + username, password = nil, nil + YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| + username, password = store['username'], store['password'] end - end - def randcolor(bias=nil, alpha = 1.0) - target, range = case bias - when :dark: [ 0.3, 0.3 ] - when :light: [0.8, 0.4] - when :realdark: [ 0.1, 0.2] - else [0.5, 0.6] - end - r, g, b = [ ( (rand - 0.5) * range ) + target, - ( (rand - 0.5) * range ) + target, - ( (rand - 0.5) * range ) + target ] + add_actions( ["\n", '[enter] login', Proc.new { + visit "/do_login/#{@username_line.text}/#{@password_line.text}"} + ], + ['l', '[l]icense', '/license'], + ['q', '[q]uit', '/quit'] ) - if @@gradients - rgb(r, g, b, alpha)..rgb(r, g, b, alpha * 0.3) - else - rgb(r, g, b, alpha) - end - end - - - def license - setup_keypress - info "license" - add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) - page_box do - header_box("License") + @content = page_box do + header_box( "Login") section_box do - para LICENSE - end - end - end - - def recording_last_read(forum_id) - if should_record_last_read(forum_id) - clear do - page_box do - para "recording last read message..." - end - end - threadingly do - rescuingly do - record_last_read(forum_id) - yield + flow { para "username:"; @username_line = app.edit_line "#{ username }" } + flow { para "password:"; @password_line = app.edit_line "#{ password }", + :secret => true } + button "login" do + visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end - else - yield - end - end - - def should_record_last_read(forum_id) - forum_id = forum_id.to_i - info "should_record_last_read for #{forum_id}" - cached = @@forum_cache[forum_id] - cached[:first_unread] != cached[:server_first_unread] - end - - def record_last_read(forum_id) - forum_id = forum_id.to_i - info "record_last_read for #{forum_id}" - cached = @@forum_cache[forum_id] - forum = @@bbs.jump(forum_id) - forum.first_unread = cached[:first_unread] - cached[:server_first_unread] = cached[:first_unread] - - if cached[:first_unread] > cached[:noteids].last - @@bbs_cache[:todo].delete(forum_id) - end - - if cached[:first_unread] <= cached[:noteids].last - @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] - end - end - - def quit_from_forum(id) - info "quit_from_forum" - page_box do - "Quitting..." - end - recording_last_read(id) do - exit() end end - def quit - info "quit" - exit() - end - def do_login(username, password) setup_keypress @page = page_box do para "logging in..." end threadingly do rescuingly do @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password visit '/load_bbs' end end end end def error setup_keypress add_actions( ['q', '[q]uit', '/quit'], ['b', '[b]ack to login', '/'] ) page_box do header_box "Error" section_box do para @@error end end end - def login + def license setup_keypress - @@bbs = nil - username, password = nil, nil - YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| - username, password = store['username'], store['password'] - end - - add_actions( ["\n", '[enter] login', Proc.new { - visit "/do_login/#{@username_line.text}/#{@password_line.text}"} - ], - ['l', '[l]icense', '/license'], - ['q', '[q]uit', '/quit'] ) - - @content = page_box do - header_box( "Login") + info "license" + add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) + page_box do + header_box("License") section_box do - flow { para "username:"; @username_line = app.edit_line "#{ username }" } - flow { para "password:"; @password_line = app.edit_line "#{ password }", - :secret => true } - button "login" do - visit "/do_login/#{@username_line.text}/#{@password_line.text}" - end + para LICENSE end end end - - def quit - page_box do - exit() - end - end - - def leave_forum(id) - info "leave forum #{id}" - page_box - page_box do - para "leaving forum #{id}..." - end - recording_last_read(id) do - visit '/bbs' - end - end - def load_bbs info "load_bbs" page_box do para "loading forums..." end threadingly do rescuingly do @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end end end def bbs setup_keypress info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) if forums_todo.length > 0 add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"] end add_actions [ 'q', '[q]uit', '/quit' ] page_box do header_box( "Forums") [ ["Unread", forums_todo, false ], ["Subscribed", forums_joined, true ], ["Zapped", forums_all, true ]].each do | group | group_name, ordered_ids, hidden = *group if ordered_ids.length > 0 chunk_section_box(group_name, hidden) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end - def goto_next_from(forum_id) - forum_id = forum_id.to_i - # id is forum to jump *from* - page_box do - para "leaving forum #{forum_id}.." - end - cache = @@forum_cache[forum_id] - cache[:first_unread] = cache[:noteids].last + 1 - - todo_list = @@bbs_cache[:todo].keys.sort - recording_last_read(forum_id) do - if todo_list.length > 0 - visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" - else - visit "/bbs" - end - end - end - - def switch_forum(old_id, new_id) - old_id, new_id = old_id.to_i, new_id.to_i - recording_last_read(old_id) do - visit "/enter_forum/#{new_id}" - end - end - def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i threadingly do rescuingly do # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end end end def forum(id) setup_keypress info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"]) if msgs_unread.length > 0 add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] else add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"] end add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] page_box do header_box(cache[:name]) [ [ "Unread", msgs_unread, false ], [ "Read", msgs_read, true ]].each do | group | group_name, ordered_ids, hidden = *group if ordered_ids.length > 0 chunk_section_box(group_name, hidden) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] if post # bizarrely, sometimes we have a noteid with no post headers chunk_box do - para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") + para link("#{ post_id }\n#{post[:author]}\n#{post[:date]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end end def foruminfo(id) setup_keypress id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end add_actions( [ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ) threadingly do rescuingly do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) @page.clear do header_box section_box do caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end end - def mark_unread(forum_id,msgnum) - forum_id = forum_id.to_i; msgnum = msgnum.to_i - cache = @@forum_cache[forum_id] - if msgnum < cache[:first_unread] - cache[:first_unread] = msgnum - end - visit "/forum/#{forum_id}" - end - - def add_actions( *actions) - @page_actions ||= [] - @page_actions = @page_actions + actions - end - - def action_links - @page_actions ||= [] - linklist = [] - @page_actions.each do | item | - linklist << link(item[1], :click => item[2] ) - linklist << " " unless item == @page_actions.last - end - linklist - end - - def setup_keypress - @page_actions ||= [] - keypress do | key | - found = @page_actions.assoc(key) - if found - action = found[2] - if action.respond_to? :call - action.call - else - info "visiting <#{action}>" - visit action - end - end - end - end - - - def get_message(forum_id, msgnum) - msg = {} - post = @@bbs.jump(forum_id).read(msgnum) - [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } - msg[:message_id] = msgnum - msg[:forum_id] = forum_id - msg - end - def message(forum_id,msgnum, direction) setup_keypress forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ] add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] add_actions [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] # this is one of the few times we don't have a separate # page for doing network stuff. threadingly do rescuingly do msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @page.clear do header_box section_box do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end - + + def quit + info "quit" + exit() + end + + def quit_from_forum(id) + info "quit_from_forum" + page_box do + "Quitting..." + end + recording_last_read(id) do + exit() + end + end + + def leave_forum(id) + info "leave forum #{id}" + page_box + page_box do + para "leaving forum #{id}..." + end + recording_last_read(id) do + visit '/bbs' + end + end + + def goto_next_from(forum_id) + forum_id = forum_id.to_i + # id is forum to jump *from* + page_box do + para "leaving forum #{forum_id}.." + end + cache = @@forum_cache[forum_id] + cache[:first_unread] = cache[:noteids].last + 1 + + todo_list = @@bbs_cache[:todo].keys.sort + recording_last_read(forum_id) do + if todo_list.length > 0 + visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" + else + visit "/bbs" + end + end + end + + def switch_forum(old_id, new_id) + old_id, new_id = old_id.to_i, new_id.to_i + recording_last_read(old_id) do + visit "/enter_forum/#{new_id}" + end + end + + def mark_unread(forum_id,msgnum) + forum_id = forum_id.to_i; msgnum = msgnum.to_i + cache = @@forum_cache[forum_id] + if msgnum < cache[:first_unread] + cache[:first_unread] = msgnum + end + visit "/forum/#{forum_id}" + end + def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end threadingly do rescuingly do msg = get_message(forum_id, msgnum) old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" @page.clear do section_box do para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end threadingly do rescuingly do new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end + + + # UTILITY METHODS + + def threadingly + if @@use_threads + Thread.new { yield } + else + yield + end + end + + def rescuingly + debug "begin rescue block..." + begin + yield + rescue Exception => err + debug "rescuing #{err.message}" + @@error = err + visit '/error' + end + debug "end rescue block..." + end + + # DISPLAY HELPER METHODS + + def page_box + st = nil + background black + stack :margin => 20 do + background(randcolor(:dark), :curve => 20) + st = stack :margin => 20 do + yield if block_given? + end + end + st + end + + def section_box + st = nil + stack :margin => 10 do + background randcolor(:light, 0.5), :curve => 20 + st = stack :margin => 10 do + yield if block_given? + end + end + st + end + + def chunk_section_box(text, hidden=true) + the_flow = nil + section_box do + flow(:click => Proc.new { the_flow.toggle }, + :margin => 20 + ) do + background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 20 + caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 + end + the_flow = flow :hidden => hidden do + yield + end + end + end + + def header_box(text = "") + linklist ||= @action_links + section_box do + flow do + flow( :width => -200) do + para *action_links + end + flow( :width => 200) do + tagline( text, :stroke => randcolor(:realdark), + :margin => 20, :align => 'right') + end + end + end + end + + def chunk_box + stack :width => 200 do + background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 10, :margin => 20 + stack :margin => 20 do + yield if block_given? + end + end + end + + def randcolor(bias=nil, alpha = 1.0) + target, range = case bias + when :dark: [ 0.3, 0.3 ] + when :light: [0.8, 0.4] + when :realdark: [ 0.1, 0.2] + else [0.5, 0.6] + end + r, g, b = [ ( (rand - 0.5) * range ) + target, + ( (rand - 0.5) * range ) + target, + ( (rand - 0.5) * range ) + target ] + + if @@gradients + rgb(r, g, b, alpha)..rgb(r, g, b, alpha * 0.3) + else + rgb(r, g, b, alpha) + end + end + + # BBS INTERACTION HELPER METHODS + + def recording_last_read(forum_id) + if should_record_last_read(forum_id) + clear do + page_box do + para "recording last read message..." + end + end + threadingly do + rescuingly do + record_last_read(forum_id) + yield + end + end + else + yield + end + end + + def should_record_last_read(forum_id) + forum_id = forum_id.to_i + info "should_record_last_read for #{forum_id}" + cached = @@forum_cache[forum_id] + cached[:first_unread] != cached[:server_first_unread] + end + + def record_last_read(forum_id) + forum_id = forum_id.to_i + info "record_last_read for #{forum_id}" + cached = @@forum_cache[forum_id] + forum = @@bbs.jump(forum_id) + forum.first_unread = cached[:first_unread] + cached[:server_first_unread] = cached[:first_unread] + + if cached[:first_unread] > cached[:noteids].last + @@bbs_cache[:todo].delete(forum_id) + end + + if cached[:first_unread] <= cached[:noteids].last + @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] + end + end + + def get_message(forum_id, msgnum) + msg = {} + post = @@bbs.jump(forum_id).read(msgnum) + [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } + msg[:message_id] = msgnum + msg[:forum_id] = forum_id + msg + end + + # KEYBOARD INTERACTION HELPER METHODS + + def add_actions( *actions) + @page_actions ||= [] + @page_actions = @page_actions + actions + end + + def action_links + @page_actions ||= [] + linklist = [] + @page_actions.each do | item | + linklist << link(item[1], :click => item[2] ) + linklist << " " unless item == @page_actions.last + end + linklist + end + + def setup_keypress + @page_actions ||= [] + keypress do | key | + found = @page_actions.assoc(key) + if found + action = found[2] + if action.respond_to? :call + action.call + else + info "visiting <#{action}>" + visit action + end + end + end + end + end Shoes.app :width => 850
edheil/shoesca
82ea9a78f46407caa2a90ffac63b6c8e52be8fd1
pretty gradients auto-show only "unread", ever.
diff --git a/shoesca.rb b/shoesca.rb index a133a60..004f420 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,689 +1,690 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/error', :error url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil + @@gradients = true @@error = nil @@forum_cache = {} @@bbs_cache = {} @@use_threads = true def threadingly if @@use_threads Thread.new { yield } else yield end end def rescuingly debug "begin rescue block..." begin yield rescue Exception => err debug "rescuing #{err.message}" @@error = err visit '/error' end debug "end rescue block..." end def page_box st = nil background black stack :margin => 20 do - background randcolor(:dark), :curve => 20 + background(randcolor(:dark), :curve => 20) st = stack :margin => 20 do yield if block_given? end end st end - def section_box st = nil - stack :margin => 20 do + stack :margin => 10 do background randcolor(:light, 0.5), :curve => 20 - st = stack :margin => 20 do + st = stack :margin => 10 do yield if block_given? end end st end def chunk_section_box(text, hidden=true) the_flow = nil section_box do flow(:click => Proc.new { the_flow.toggle }, :margin => 20 ) do - background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20 + background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 20 caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 end the_flow = flow :hidden => hidden do yield end end end def header_box(text = "") linklist ||= @action_links section_box do flow do flow( :width => -200) do para *action_links end flow( :width => 200) do tagline( text, :stroke => randcolor(:realdark), :margin => 20, :align => 'right') end end end end def chunk_box stack :width => 200 do - background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20 + background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 10, :margin => 20 stack :margin => 20 do yield if block_given? end end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] when :light: [0.8, 0.4] when :realdark: [ 0.1, 0.2] else [0.5, 0.6] end - rgb( ( (rand - 0.5) * range ) + target, - ( (rand - 0.5) * range ) + target, - ( (rand - 0.5) * range ) + target, - alpha) + r, g, b = [ ( (rand - 0.5) * range ) + target, + ( (rand - 0.5) * range ) + target, + ( (rand - 0.5) * range ) + target ] + + if @@gradients + rgb(r, g, b, alpha)..rgb(r, g, b, alpha * 0.3) + else + rgb(r, g, b, alpha) + end end def license setup_keypress info "license" add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) page_box do header_box("License") section_box do para LICENSE end end end def recording_last_read(forum_id) if should_record_last_read(forum_id) clear do page_box do para "recording last read message..." end end threadingly do rescuingly do record_last_read(forum_id) yield end end else yield end end def should_record_last_read(forum_id) forum_id = forum_id.to_i info "should_record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] cached[:first_unread] != cached[:server_first_unread] end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end def quit_from_forum(id) info "quit_from_forum" page_box do "Quitting..." end recording_last_read(id) do exit() end end def quit info "quit" exit() end def do_login(username, password) setup_keypress @page = page_box do para "logging in..." end threadingly do rescuingly do @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password visit '/load_bbs' end end end end def error setup_keypress add_actions( ['q', '[q]uit', '/quit'], ['b', '[b]ack to login', '/'] ) page_box do header_box "Error" section_box do para @@error end end end def login setup_keypress @@bbs = nil username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end add_actions( ["\n", '[enter] login', Proc.new { visit "/do_login/#{@username_line.text}/#{@password_line.text}"} ], ['l', '[l]icense', '/license'], ['q', '[q]uit', '/quit'] ) @content = page_box do header_box( "Login") section_box do flow { para "username:"; @username_line = app.edit_line "#{ username }" } flow { para "password:"; @password_line = app.edit_line "#{ password }", :secret => true } button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end end end def quit page_box do exit() end end def leave_forum(id) info "leave forum #{id}" page_box page_box do para "leaving forum #{id}..." end recording_last_read(id) do visit '/bbs' end end def load_bbs info "load_bbs" page_box do para "loading forums..." end threadingly do rescuingly do @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end end end def bbs setup_keypress info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) if forums_todo.length > 0 add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"] end add_actions [ 'q', '[q]uit', '/quit' ] - open_shown = false page_box do header_box( "Forums") - [ ["Unread", forums_todo ], - ["Subscribed", forums_joined ], - ["Zapped", forums_all ]].each do | group | - group_name, ordered_ids = *group + [ ["Unread", forums_todo, false ], + ["Subscribed", forums_joined, true ], + ["Zapped", forums_all, true ]].each do | group | + group_name, ordered_ids, hidden = *group if ordered_ids.length > 0 - chunk_section_box(group_name, open_shown) do + chunk_section_box(group_name, hidden) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end - open_shown = true end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* page_box do para "leaving forum #{forum_id}.." end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 todo_list = @@bbs_cache[:todo].keys.sort recording_last_read(forum_id) do if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i recording_last_read(old_id) do visit "/enter_forum/#{new_id}" end end def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i threadingly do rescuingly do # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end end end def forum(id) setup_keypress info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"]) if msgs_unread.length > 0 add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] else add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"] end add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] - open_shown = false page_box do header_box(cache[:name]) - [ [ "Unread", msgs_unread, ], - [ "Read", msgs_read, ]].each do | pair | - group_name, ordered_ids = *pair + [ [ "Unread", msgs_unread, false ], + [ "Read", msgs_read, true ]].each do | group | + group_name, ordered_ids, hidden = *group if ordered_ids.length > 0 - chunk_section_box(group_name, open_shown) do + chunk_section_box(group_name, hidden) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] if post # bizarrely, sometimes we have a noteid with no post headers chunk_box do para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end - open_shown = true end end end end def foruminfo(id) setup_keypress id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end add_actions( [ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ) threadingly do rescuingly do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) @page.clear do header_box section_box do caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def add_actions( *actions) @page_actions ||= [] @page_actions = @page_actions + actions end def action_links @page_actions ||= [] linklist = [] @page_actions.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == @page_actions.last end linklist end def setup_keypress @page_actions ||= [] keypress do | key | found = @page_actions.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) setup_keypress forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ] add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] add_actions [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] # this is one of the few times we don't have a separate # page for doing network stuff. threadingly do rescuingly do msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @page.clear do header_box section_box do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end threadingly do rescuingly do msg = get_message(forum_id, msgnum) old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" @page.clear do section_box do para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end threadingly do rescuingly do new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end end Shoes.app :width => 850
edheil/shoesca
08fb07f3f2ba4fc6b4b879361e63eec8a7183138
generalized error rescue. still doesn't seem to deal with network failures well though.
diff --git a/shoesca.rb b/shoesca.rb index 9b18a19..a133a60 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,653 +1,689 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login - url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login + url '/error', :error url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil + @@error = nil @@forum_cache = {} @@bbs_cache = {} @@use_threads = true def threadingly if @@use_threads Thread.new { yield } else yield end end + def rescuingly + debug "begin rescue block..." + begin + yield + rescue Exception => err + debug "rescuing #{err.message}" + @@error = err + visit '/error' + end + debug "end rescue block..." + end + def page_box st = nil background black stack :margin => 20 do background randcolor(:dark), :curve => 20 st = stack :margin => 20 do yield if block_given? end end st end def section_box st = nil stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 st = stack :margin => 20 do yield if block_given? end end st end def chunk_section_box(text, hidden=true) the_flow = nil section_box do flow(:click => Proc.new { the_flow.toggle }, :margin => 20 ) do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20 caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 end the_flow = flow :hidden => hidden do yield end end end def header_box(text = "") linklist ||= @action_links section_box do flow do flow( :width => -200) do para *action_links end flow( :width => 200) do tagline( text, :stroke => randcolor(:realdark), :margin => 20, :align => 'right') end end end end def chunk_box stack :width => 200 do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20 stack :margin => 20 do yield if block_given? end end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] when :light: [0.8, 0.4] when :realdark: [ 0.1, 0.2] else [0.5, 0.6] end rgb( ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, alpha) end def license setup_keypress info "license" add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) page_box do header_box("License") section_box do para LICENSE end end end def recording_last_read(forum_id) if should_record_last_read(forum_id) clear do page_box do para "recording last read message..." end end threadingly do - record_last_read(forum_id) - yield + rescuingly do + record_last_read(forum_id) + yield + end end else yield end end def should_record_last_read(forum_id) forum_id = forum_id.to_i info "should_record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] cached[:first_unread] != cached[:server_first_unread] end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end def quit_from_forum(id) info "quit_from_forum" page_box do "Quitting..." end recording_last_read(id) do exit() end end def quit info "quit" exit() end def do_login(username, password) setup_keypress @page = page_box do para "logging in..." end threadingly do - begin + rescuingly do @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password + visit '/load_bbs' end - visit '/load_bbs' - rescue StandardError => err - @@bbs = nil - add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) - @page.clear do - header_box("Error") - section_box do - para "error logging in: #{err.message}" - end - end + end + end + end + + def error + setup_keypress + add_actions( ['q', '[q]uit', '/quit'], + ['b', '[b]ack to login', '/'] + ) + page_box do + header_box "Error" + section_box do + para @@error end end end def login setup_keypress + @@bbs = nil username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end add_actions( ["\n", '[enter] login', Proc.new { visit "/do_login/#{@username_line.text}/#{@password_line.text}"} ], ['l', '[l]icense', '/license'], ['q', '[q]uit', '/quit'] ) @content = page_box do header_box( "Login") section_box do flow { para "username:"; @username_line = app.edit_line "#{ username }" } flow { para "password:"; @password_line = app.edit_line "#{ password }", :secret => true } button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end end end def quit page_box do exit() end end def leave_forum(id) info "leave forum #{id}" page_box page_box do para "leaving forum #{id}..." end recording_last_read(id) do visit '/bbs' end end def load_bbs info "load_bbs" page_box do para "loading forums..." end threadingly do - @@bbs_cache[:all] = @@bbs.forums('all') - @@bbs_cache[:todo] = @@bbs.forums('todo') - @@bbs_cache[:joined] = @@bbs.forums('joined') - visit '/bbs' + rescuingly do + @@bbs_cache[:all] = @@bbs.forums('all') + @@bbs_cache[:todo] = @@bbs.forums('todo') + @@bbs_cache[:joined] = @@bbs.forums('joined') + visit '/bbs' + end end end def bbs setup_keypress info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) if forums_todo.length > 0 add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"] end add_actions [ 'q', '[q]uit', '/quit' ] open_shown = false page_box do header_box( "Forums") [ ["Unread", forums_todo ], ["Subscribed", forums_joined ], ["Zapped", forums_all ]].each do | group | group_name, ordered_ids = *group if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end open_shown = true end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* page_box do para "leaving forum #{forum_id}.." end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 todo_list = @@bbs_cache[:todo].keys.sort recording_last_read(forum_id) do if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i recording_last_read(old_id) do visit "/enter_forum/#{new_id}" end end def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i threadingly do - # we pull stuff into forum_cache only when we enter a new forum. - forum = @@bbs.jump(id) - cache = {} - first_unread = forum.first_unread.to_i - info "first_unread: #{ first_unread.inspect }" - cache[:server_first_unread] = first_unread - cache[:first_unread] = first_unread - info "first unread: #{first_unread.inspect}" - info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" - noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" - cache[:noteids] = forum.noteids(noterange).sort - if cache[:noteids].length == 0 # uh oh - noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" + rescuingly do + # we pull stuff into forum_cache only when we enter a new forum. + forum = @@bbs.jump(id) + cache = {} + first_unread = forum.first_unread.to_i + info "first_unread: #{ first_unread.inspect }" + cache[:server_first_unread] = first_unread + cache[:first_unread] = first_unread + info "first unread: #{first_unread.inspect}" + info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" + noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort + if cache[:noteids].length == 0 # uh oh + noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" + cache[:noteids] = forum.noteids(noterange).sort + end + info "noterange: #{noterange}" + cache[:post_headers] = forum.post_headers(noterange) + cache[:name] = forum.name + cache[:post_ok] = forum.post? + cache[:admin] = forum.admin + cache[:anonymous] = forum.anonymous + cache[:private] = forum.private + @@forum_cache[id] = cache + visit "/forum/#{id}" end - info "noterange: #{noterange}" - cache[:post_headers] = forum.post_headers(noterange) - cache[:name] = forum.name - cache[:post_ok] = forum.post? - cache[:admin] = forum.admin - cache[:anonymous] = forum.anonymous - cache[:private] = forum.private - @@forum_cache[id] = cache - visit "/forum/#{id}" end end def forum(id) setup_keypress info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"]) if msgs_unread.length > 0 add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] else add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"] end add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] open_shown = false page_box do header_box(cache[:name]) [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] if post # bizarrely, sometimes we have a noteid with no post headers chunk_box do para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end open_shown = true end end end end def foruminfo(id) setup_keypress id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end add_actions( [ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ) threadingly do - @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information - info = @@forum_cache[:forum_info] - the_body = info[:body] - body_urls = the_body.scan(URLRE) - @page.clear do - header_box - section_box do - caption "Forum moderator is #{@@forum_cache[id][:admin]}." - caption "Forum info last updated #{info[:date]} by #{info[:from]}" - para "#{info[:body]}" - body_urls.each do | a_url | - para link(a_url, :click => a_url) + rescuingly do + @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information + info = @@forum_cache[:forum_info] + the_body = info[:body] + body_urls = the_body.scan(URLRE) + @page.clear do + header_box + section_box do + caption "Forum moderator is #{@@forum_cache[id][:admin]}." + caption "Forum info last updated #{info[:date]} by #{info[:from]}" + para "#{info[:body]}" + body_urls.each do | a_url | + para link(a_url, :click => a_url) + end end end end end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def add_actions( *actions) @page_actions ||= [] @page_actions = @page_actions + actions end def action_links @page_actions ||= [] linklist = [] @page_actions.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == @page_actions.last end linklist end def setup_keypress @page_actions ||= [] keypress do | key | found = @page_actions.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) setup_keypress forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ] add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] add_actions [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] + + # this is one of the few times we don't have a separate + # page for doing network stuff. + threadingly do - msg = get_message(forum_id, msgnum) - body_urls = msg[:body].scan(URLRE) - authority = " (#{msg[:authority]})" if msg[:authority] - @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + - "#{msg[:body]}" + - "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") - - @page.clear do - header_box - section_box do - para @whole_message - body_urls.each do | a_url | - para link(a_url, :click => a_url) + rescuingly do + msg = get_message(forum_id, msgnum) + body_urls = msg[:body].scan(URLRE) + authority = " (#{msg[:authority]})" if msg[:authority] + @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + + "#{msg[:body]}" + + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") + + @page.clear do + header_box + section_box do + para @whole_message + body_urls.each do | a_url | + para link(a_url, :click => a_url) + end end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end threadingly do - msg = get_message(forum_id, msgnum) - old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") - quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" - @page.clear do - section_box do - para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") - tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' - @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 - button "post" do - text = @post_box.text - new_post = @@bbs.jump(forum_id).post(text) - recording_last_read(forum_id) do - visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + rescuingly do + msg = get_message(forum_id, msgnum) + old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") + quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" + @page.clear do + section_box do + para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") + tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' + @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 + button "post" do + text = @post_box.text + new_post = @@bbs.jump(forum_id).post(text) + recording_last_read(forum_id) do + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + end end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end threadingly do - new_post = @@bbs.jump(forum_id).post(text) - recording_last_read(forum_id) do - visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + rescuingly do + new_post = @@bbs.jump(forum_id).post(text) + recording_last_read(forum_id) do + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + end end end end end end end end Shoes.app :width => 850
edheil/shoesca
57da3bc93520396560800044e23ae9a5d4843a41
cosmetics on license page
diff --git a/shoesca.rb b/shoesca.rb index aab25bc..9b18a19 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,652 +1,653 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} @@use_threads = true def threadingly if @@use_threads Thread.new { yield } else yield end end def page_box st = nil background black stack :margin => 20 do background randcolor(:dark), :curve => 20 st = stack :margin => 20 do yield if block_given? end end st end def section_box st = nil stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 st = stack :margin => 20 do yield if block_given? end end st end def chunk_section_box(text, hidden=true) the_flow = nil section_box do flow(:click => Proc.new { the_flow.toggle }, :margin => 20 ) do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20 caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 end the_flow = flow :hidden => hidden do yield end end end def header_box(text = "") linklist ||= @action_links section_box do flow do flow( :width => -200) do para *action_links end flow( :width => 200) do tagline( text, :stroke => randcolor(:realdark), :margin => 20, :align => 'right') end end end end def chunk_box stack :width => 200 do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20 stack :margin => 20 do yield if block_given? end end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] when :light: [0.8, 0.4] when :realdark: [ 0.1, 0.2] else [0.5, 0.6] end rgb( ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, alpha) end def license + setup_keypress info "license" + add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) page_box do + header_box("License") section_box do - background aliceblue, :curve => 20 - para link('back', :click => '/login') para LICENSE end end end def recording_last_read(forum_id) if should_record_last_read(forum_id) clear do page_box do para "recording last read message..." end end threadingly do record_last_read(forum_id) yield end else yield end end def should_record_last_read(forum_id) forum_id = forum_id.to_i info "should_record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] cached[:first_unread] != cached[:server_first_unread] end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end def quit_from_forum(id) info "quit_from_forum" page_box do "Quitting..." end recording_last_read(id) do exit() end end def quit info "quit" exit() end def do_login(username, password) setup_keypress @page = page_box do para "logging in..." end threadingly do begin @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password end visit '/load_bbs' rescue StandardError => err @@bbs = nil add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) @page.clear do header_box("Error") section_box do para "error logging in: #{err.message}" end end end end end def login setup_keypress username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end add_actions( ["\n", '[enter] login', Proc.new { visit "/do_login/#{@username_line.text}/#{@password_line.text}"} ], ['l', '[l]icense', '/license'], ['q', '[q]uit', '/quit'] ) @content = page_box do header_box( "Login") section_box do flow { para "username:"; @username_line = app.edit_line "#{ username }" } flow { para "password:"; @password_line = app.edit_line "#{ password }", :secret => true } button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end end end def quit page_box do exit() end end def leave_forum(id) info "leave forum #{id}" page_box page_box do para "leaving forum #{id}..." end recording_last_read(id) do visit '/bbs' end end def load_bbs info "load_bbs" page_box do para "loading forums..." end threadingly do @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end end def bbs setup_keypress info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) if forums_todo.length > 0 add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"] end add_actions [ 'q', '[q]uit', '/quit' ] open_shown = false page_box do header_box( "Forums") [ ["Unread", forums_todo ], ["Subscribed", forums_joined ], ["Zapped", forums_all ]].each do | group | group_name, ordered_ids = *group if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end open_shown = true end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* page_box do para "leaving forum #{forum_id}.." end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 todo_list = @@bbs_cache[:todo].keys.sort recording_last_read(forum_id) do if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i recording_last_read(old_id) do visit "/enter_forum/#{new_id}" end end def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i threadingly do # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end end def forum(id) setup_keypress info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"]) if msgs_unread.length > 0 add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] else add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"] end add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] open_shown = false page_box do header_box(cache[:name]) [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] if post # bizarrely, sometimes we have a noteid with no post headers chunk_box do para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end open_shown = true end end end end def foruminfo(id) setup_keypress id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end add_actions( [ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ) threadingly do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) @page.clear do header_box section_box do caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def add_actions( *actions) @page_actions ||= [] @page_actions = @page_actions + actions end def action_links @page_actions ||= [] linklist = [] @page_actions.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == @page_actions.last end linklist end def setup_keypress @page_actions ||= [] keypress do | key | found = @page_actions.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) setup_keypress forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ] add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] add_actions [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] threadingly do msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @page.clear do header_box section_box do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end threadingly do msg = get_message(forum_id, msgnum) old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" @page.clear do section_box do para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end threadingly do new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end Shoes.app :width => 850
edheil/shoesca
51bb904277c9cb64c4f74730b5fb411364dac0cd
simplify and unify the keystroke action / link code
diff --git a/shoesca.rb b/shoesca.rb index 954e1ec..aab25bc 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,658 +1,652 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} @@use_threads = true def threadingly if @@use_threads Thread.new { yield } else yield end end def page_box st = nil background black stack :margin => 20 do background randcolor(:dark), :curve => 20 st = stack :margin => 20 do yield if block_given? end end st end def section_box st = nil stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 st = stack :margin => 20 do - info "yielding..." yield if block_given? end end st end def chunk_section_box(text, hidden=true) the_flow = nil section_box do flow(:click => Proc.new { the_flow.toggle }, :margin => 20 ) do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20 caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 end the_flow = flow :hidden => hidden do yield end end end - def header_box(linklist=[], text = "") + def header_box(text = "") + linklist ||= @action_links section_box do flow do flow( :width => -200) do - para *linklist + para *action_links end flow( :width => 200) do tagline( text, :stroke => randcolor(:realdark), :margin => 20, :align => 'right') end end end end def chunk_box stack :width => 200 do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20 stack :margin => 20 do yield if block_given? end end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] when :light: [0.8, 0.4] when :realdark: [ 0.1, 0.2] else [0.5, 0.6] end rgb( ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, alpha) end def license info "license" page_box do section_box do background aliceblue, :curve => 20 para link('back', :click => '/login') para LICENSE end end end def recording_last_read(forum_id) if should_record_last_read(forum_id) clear do page_box do para "recording last read message..." end end threadingly do record_last_read(forum_id) yield end else yield end end def should_record_last_read(forum_id) forum_id = forum_id.to_i info "should_record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] cached[:first_unread] != cached[:server_first_unread] end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end def quit_from_forum(id) info "quit_from_forum" page_box do "Quitting..." end recording_last_read(id) do exit() end end def quit info "quit" exit() end def do_login(username, password) - debug "do_login" + setup_keypress @page = page_box do para "logging in..." end threadingly do begin @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password end visit '/load_bbs' rescue StandardError => err - debug "error: #{err.message}" @@bbs = nil - linklist, keypressproc = actions([['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']]) - keypress { | key | keypressproc.call(key) } + add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']) @page.clear do - header_box(linklist, "Error") + header_box("Error") section_box do para "error logging in: #{err.message}" end end end end end def login + setup_keypress username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end - - actionlist = [["\n", '[enter] login', Proc.new { + + add_actions( ["\n", '[enter] login', Proc.new { visit "/do_login/#{@username_line.text}/#{@password_line.text}"} ], - ['l', '[l]icense', '/license'], - ['q', '[q]uit', '/quit']] - linklist, keypressproc = actions(actionlist) - keypress { | key | keypressproc.call(key) } + ['l', '[l]icense', '/license'], + ['q', '[q]uit', '/quit'] ) @content = page_box do - header_box(linklist, "Login") + header_box( "Login") section_box do flow { para "username:"; @username_line = app.edit_line "#{ username }" } flow { para "password:"; @password_line = app.edit_line "#{ password }", :secret => true } button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end end end def quit page_box do exit() end end def leave_forum(id) info "leave forum #{id}" page_box page_box do para "leaving forum #{id}..." end recording_last_read(id) do visit '/bbs' end end def load_bbs info "load_bbs" page_box do para "loading forums..." end threadingly do @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end end def bbs + setup_keypress info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) - action_list = [] if forums_todo.length > 0 - action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] + add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else - action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] + add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"] end - action_list << [ 'q', '[q]uit', '/quit' ] + add_actions [ 'q', '[q]uit', '/quit' ] - linklist, keypressproc = actions( action_keypress ) - list { | key | keypressproc.call(key) } open_shown = false page_box do - header_box( linklist, "Forums") + header_box( "Forums") [ ["Unread", forums_todo ], ["Subscribed", forums_joined ], ["Zapped", forums_all ]].each do | group | group_name, ordered_ids = *group if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end open_shown = true end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* page_box do para "leaving forum #{forum_id}.." end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 todo_list = @@bbs_cache[:todo].keys.sort recording_last_read(forum_id) do if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i recording_last_read(old_id) do visit "/enter_forum/#{new_id}" end end def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i threadingly do # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end end def forum(id) + setup_keypress info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } - actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"], - [ 'i', '[i]nfo', "/foruminfo/#{id}"], - [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], - [ 'f', 'read [f]orward', - "/message/#{id}/#{noteids.first}/forward"], - [ 'b', 'read [b]ackward', - "/message/#{id}/#{noteids.last}/backward"], - [ 'g', '[g]oto next forum with unread messages', - "/goto_next_from/#{id}"]] + add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"], + [ 'i', '[i]nfo', "/foruminfo/#{id}"], + [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], + [ 'f', 'read [f]orward', + "/message/#{id}/#{noteids.first}/forward"], + [ 'b', 'read [b]ackward', + "/message/#{id}/#{noteids.last}/backward"], + [ 'g', '[g]oto next forum with unread messages', + "/goto_next_from/#{id}"]) if msgs_unread.length > 0 - actionlist << [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] + add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] else - actionlist << [ ' ', '[ ]forum list', "/leave_forum/#{id}"] + add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"] end - actionlist << [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] - - linklist, keypressproc = actions(actionlist) + add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] - keypress { | key | keypressproc.call(key) } open_shown = false page_box do - header_box(linklist, cache[:name]) + header_box(cache[:name]) [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] if post # bizarrely, sometimes we have a noteid with no post headers chunk_box do para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end open_shown = true end end end end def foruminfo(id) + setup_keypress id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end - linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], - [ 'p', '[e]nter msg', "/new_post/#{id}"], - [ "q", "[q]uit", "/quit_from_forum/#{id}" ] - ] - keypress { | key | keypressproc.call(key) } + add_actions( [ 'b', '[b]ack', "/forum/#{id}"], + [ 'p', '[e]nter msg', "/new_post/#{id}"], + [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ) threadingly do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) @page.clear do - section_box do - para *linklist - end + header_box section_box do caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end - def actions(list) + def add_actions( *actions) + @page_actions ||= [] + @page_actions = @page_actions + actions + end + + def action_links + @page_actions ||= [] linklist = [] - list.each do | item | + @page_actions.each do | item | linklist << link(item[1], :click => item[2] ) - linklist << " " unless item == list.last + linklist << " " unless item == @page_actions.last end + linklist + end - keypressproc = Proc.new do | key | - found = list.assoc(key) + def setup_keypress + @page_actions ||= [] + keypress do | key | + found = @page_actions.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end - return linklist, keypressproc end + def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) + setup_keypress forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev - action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] + add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next - action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] + add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end - action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] - action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] - action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] - action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] - action_list << [ "c", "[c]opy to clipboard", + add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] + add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] + add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ] + add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] + add_actions [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next - action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] + add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else - action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] + add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev - action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] + add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else - action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] + add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev - action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] + add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else - action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] + add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next - action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] + add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else - action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] + add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end - action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] - - linklist, keypressproc = actions(action_list) - keypress { | key | - keypressproc.call(key) - } + add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] threadingly do msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @page.clear do - section_box do - para *linklist - end + header_box section_box do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end threadingly do msg = get_message(forum_id, msgnum) old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" @page.clear do section_box do para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end threadingly do new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end Shoes.app :width => 850
edheil/shoesca
20489ac36187f2bb3ec193adde1e7f1f00c1007a
single on/off switch for threading fix login error display cosmetics
diff --git a/shoesca.rb b/shoesca.rb index 0bad89f..954e1ec 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,647 +1,658 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} + @@use_threads = true + + def threadingly + if @@use_threads + Thread.new { yield } + else + yield + end + end def page_box st = nil background black stack :margin => 20 do background randcolor(:dark), :curve => 20 st = stack :margin => 20 do yield if block_given? end end st end def section_box st = nil stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 st = stack :margin => 20 do info "yielding..." yield if block_given? end end st end def chunk_section_box(text, hidden=true) the_flow = nil section_box do flow(:click => Proc.new { the_flow.toggle }, :margin => 20 ) do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20 caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 end the_flow = flow :hidden => hidden do yield end end end def header_box(linklist=[], text = "") section_box do flow do flow( :width => -200) do para *linklist end flow( :width => 200) do tagline( text, :stroke => randcolor(:realdark), :margin => 20, :align => 'right') end end end end def chunk_box stack :width => 200 do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20 stack :margin => 20 do yield if block_given? end end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] when :light: [0.8, 0.4] when :realdark: [ 0.1, 0.2] else [0.5, 0.6] end rgb( ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, alpha) end def license info "license" page_box do section_box do background aliceblue, :curve => 20 para link('back', :click => '/login') para LICENSE end end end def recording_last_read(forum_id) if should_record_last_read(forum_id) clear do page_box do para "recording last read message..." end end - Thread.new do + threadingly do record_last_read(forum_id) yield end else yield end end def should_record_last_read(forum_id) forum_id = forum_id.to_i info "should_record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] cached[:first_unread] != cached[:server_first_unread] end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end def quit_from_forum(id) info "quit_from_forum" page_box do "Quitting..." end recording_last_read(id) do exit() end end def quit info "quit" exit() end - def login_error(error) - stack do - para err.message - link("try again",:click => '/') - end - end - def do_login(username, password) - page_box do + debug "do_login" + @page = page_box do para "logging in..." end - Thread.new do + threadingly do begin @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password end visit '/load_bbs' - rescue RuntimeError => err + rescue StandardError => err debug "error: #{err.message}" @@bbs = nil - visit "/login_error/#{err.message}" + linklist, keypressproc = actions([['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']]) + keypress { | key | keypressproc.call(key) } + @page.clear do + header_box(linklist, "Error") + section_box do + para "error logging in: #{err.message}" + end + end end end end def login username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end - keypress do | key | - if key == "\n" - visit "/do_login/#{@username_line.text}/#{@password_line.text}" - end - end + actionlist = [["\n", '[enter] login', Proc.new { + visit "/do_login/#{@username_line.text}/#{@password_line.text}"} + ], + ['l', '[l]icense', '/license'], + ['q', '[q]uit', '/quit']] + linklist, keypressproc = actions(actionlist) + keypress { | key | keypressproc.call(key) } + @content = page_box do + header_box(linklist, "Login") section_box do - tagline "Login", :stroke => randcolor(:realdark), :align => right - para "username:" - @username_line = app.edit_line "#{ username }" - para "password:" - @password_line = app.edit_line "#{ password }", :secret => true + flow { para "username:"; @username_line = app.edit_line "#{ username }" } + flow { para "password:"; @password_line = app.edit_line "#{ password }", + :secret => true } button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end - para(link( 'license', :click => '/license' )) end end end def quit page_box do exit() end end def leave_forum(id) info "leave forum #{id}" page_box page_box do para "leaving forum #{id}..." end recording_last_read(id) do visit '/bbs' end end def load_bbs info "load_bbs" page_box do para "loading forums..." end - Thread.new do + threadingly do @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end end def bbs info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] - linklist, keypressproc = actions( action_list ) - keypress { | key | keypressproc.call(key) } + linklist, keypressproc = actions( action_keypress ) + list { | key | keypressproc.call(key) } open_shown = false page_box do header_box( linklist, "Forums") [ ["Unread", forums_todo ], ["Subscribed", forums_joined ], ["Zapped", forums_all ]].each do | group | group_name, ordered_ids = *group if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end open_shown = true end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* page_box do para "leaving forum #{forum_id}.." end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 todo_list = @@bbs_cache[:todo].keys.sort recording_last_read(forum_id) do if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i recording_last_read(old_id) do visit "/enter_forum/#{new_id}" end end def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i - Thread.new do + threadingly do # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end end def forum(id) info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"]] if msgs_unread.length > 0 actionlist << [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] else actionlist << [ ' ', '[ ]forum list', "/leave_forum/#{id}"] end actionlist << [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] linklist, keypressproc = actions(actionlist) keypress { | key | keypressproc.call(key) } open_shown = false page_box do header_box(linklist, cache[:name]) [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] if post # bizarrely, sometimes we have a noteid with no post headers chunk_box do para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end open_shown = true end end end end def foruminfo(id) id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } - Thread.new do + threadingly do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) @page.clear do section_box do para *linklist end section_box do caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } - Thread.new do + threadingly do msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @page.clear do section_box do para *linklist end section_box do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end - Thread.new do + threadingly do msg = get_message(forum_id, msgnum) old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" @page.clear do section_box do para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end - Thread.new do + threadingly do new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end Shoes.app :width => 850
edheil/shoesca
cf3a51e065acdeca2578e960a09228f474285ea8
guard against getting a noteno with no post header
diff --git a/shoesca.rb b/shoesca.rb index 9f4381f..0bad89f 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,646 +1,647 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} def page_box st = nil background black stack :margin => 20 do background randcolor(:dark), :curve => 20 st = stack :margin => 20 do yield if block_given? end end st end def section_box st = nil stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 st = stack :margin => 20 do info "yielding..." yield if block_given? end end st end def chunk_section_box(text, hidden=true) the_flow = nil section_box do flow(:click => Proc.new { the_flow.toggle }, :margin => 20 ) do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20 caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 end the_flow = flow :hidden => hidden do yield end end end def header_box(linklist=[], text = "") section_box do flow do flow( :width => -200) do para *linklist end flow( :width => 200) do tagline( text, :stroke => randcolor(:realdark), :margin => 20, :align => 'right') end end end end def chunk_box stack :width => 200 do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20 stack :margin => 20 do yield if block_given? end end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] when :light: [0.8, 0.4] when :realdark: [ 0.1, 0.2] else [0.5, 0.6] end rgb( ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, alpha) end def license info "license" page_box do section_box do background aliceblue, :curve => 20 para link('back', :click => '/login') para LICENSE end end end def recording_last_read(forum_id) if should_record_last_read(forum_id) clear do page_box do para "recording last read message..." end end Thread.new do record_last_read(forum_id) yield end else yield end end def should_record_last_read(forum_id) forum_id = forum_id.to_i info "should_record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] cached[:first_unread] != cached[:server_first_unread] end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end def quit_from_forum(id) info "quit_from_forum" page_box do "Quitting..." end recording_last_read(id) do exit() end end def quit info "quit" exit() end def login_error(error) stack do para err.message link("try again",:click => '/') end end def do_login(username, password) page_box do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password end visit '/load_bbs' rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil visit "/login_error/#{err.message}" end end end def login username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end keypress do | key | if key == "\n" visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end @content = page_box do section_box do tagline "Login", :stroke => randcolor(:realdark), :align => right para "username:" @username_line = app.edit_line "#{ username }" para "password:" @password_line = app.edit_line "#{ password }", :secret => true button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end para(link( 'license', :click => '/license' )) end end end def quit page_box do exit() end end def leave_forum(id) info "leave forum #{id}" page_box page_box do para "leaving forum #{id}..." end recording_last_read(id) do visit '/bbs' end end def load_bbs info "load_bbs" page_box do para "loading forums..." end Thread.new do @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end end def bbs info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] linklist, keypressproc = actions( action_list ) keypress { | key | keypressproc.call(key) } open_shown = false page_box do header_box( linklist, "Forums") [ ["Unread", forums_todo ], ["Subscribed", forums_joined ], ["Zapped", forums_all ]].each do | group | group_name, ordered_ids = *group if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end open_shown = true end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* page_box do para "leaving forum #{forum_id}.." end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 todo_list = @@bbs_cache[:todo].keys.sort recording_last_read(forum_id) do if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i recording_last_read(old_id) do visit "/enter_forum/#{new_id}" end end def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i Thread.new do # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end end def forum(id) info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end - first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"]] if msgs_unread.length > 0 actionlist << [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] else actionlist << [ ' ', '[ ]forum list', "/leave_forum/#{id}"] end actionlist << [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] linklist, keypressproc = actions(actionlist) keypress { | key | keypressproc.call(key) } open_shown = false page_box do header_box(linklist, cache[:name]) [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] - chunk_box do - para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") - para post[:subject] + if post # bizarrely, sometimes we have a noteid with no post headers + chunk_box do + para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") + para post[:subject] + end end end end open_shown = true end end end end def foruminfo(id) id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } Thread.new do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) @page.clear do section_box do para *linklist end section_box do caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } Thread.new do msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @page.clear do section_box do para *linklist end section_box do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end Thread.new do msg = get_message(forum_id, msgnum) old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" @page.clear do section_box do para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end Thread.new do new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end Shoes.app :width => 850
edheil/shoesca
13341983043360f9133b2319844de734f60a6f95
remove unneeded first_unread page
diff --git a/shoesca.rb b/shoesca.rb index 110ed9d..9f4381f 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,664 +1,646 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo - url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} def page_box st = nil background black stack :margin => 20 do background randcolor(:dark), :curve => 20 st = stack :margin => 20 do yield if block_given? end end st end def section_box st = nil stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 st = stack :margin => 20 do info "yielding..." yield if block_given? end end st end def chunk_section_box(text, hidden=true) the_flow = nil section_box do flow(:click => Proc.new { the_flow.toggle }, :margin => 20 ) do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20 caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 end the_flow = flow :hidden => hidden do yield end end end def header_box(linklist=[], text = "") section_box do flow do flow( :width => -200) do para *linklist end flow( :width => 200) do tagline( text, :stroke => randcolor(:realdark), :margin => 20, :align => 'right') end end end end def chunk_box stack :width => 200 do background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20 stack :margin => 20 do yield if block_given? end end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] when :light: [0.8, 0.4] when :realdark: [ 0.1, 0.2] else [0.5, 0.6] end rgb( ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, alpha) end def license info "license" page_box do section_box do background aliceblue, :curve => 20 para link('back', :click => '/login') para LICENSE end end end def recording_last_read(forum_id) if should_record_last_read(forum_id) clear do page_box do para "recording last read message..." end end Thread.new do record_last_read(forum_id) yield end else yield end end def should_record_last_read(forum_id) forum_id = forum_id.to_i info "should_record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] cached[:first_unread] != cached[:server_first_unread] end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end def quit_from_forum(id) info "quit_from_forum" page_box do "Quitting..." end recording_last_read(id) do exit() end end def quit info "quit" exit() end def login_error(error) stack do para err.message link("try again",:click => '/') end end def do_login(username, password) page_box do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password end visit '/load_bbs' rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil visit "/login_error/#{err.message}" end end end def login username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end keypress do | key | if key == "\n" visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end @content = page_box do section_box do tagline "Login", :stroke => randcolor(:realdark), :align => right para "username:" @username_line = app.edit_line "#{ username }" para "password:" @password_line = app.edit_line "#{ password }", :secret => true button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end para(link( 'license', :click => '/license' )) end end end def quit page_box do exit() end end def leave_forum(id) info "leave forum #{id}" page_box page_box do para "leaving forum #{id}..." end recording_last_read(id) do visit '/bbs' end end def load_bbs info "load_bbs" page_box do para "loading forums..." end Thread.new do @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end end def bbs info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] linklist, keypressproc = actions( action_list ) keypress { | key | keypressproc.call(key) } open_shown = false page_box do header_box( linklist, "Forums") [ ["Unread", forums_todo ], ["Subscribed", forums_joined ], ["Zapped", forums_all ]].each do | group | group_name, ordered_ids = *group if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.each do | id | data = forums[id] chunk_box do para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end open_shown = true end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* page_box do para "leaving forum #{forum_id}.." end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 todo_list = @@bbs_cache[:todo].keys.sort recording_last_read(forum_id) do if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i recording_last_read(old_id) do visit "/enter_forum/#{new_id}" end end def enter_forum(id) page_box do para "loading forum #{id}..." end info "enter_forum #{id}" id = id.to_i Thread.new do # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end end def forum(id) info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', - "/goto_next_from/#{id}"], - [ ' ', '[ ]first unread', "/first_unread/#{id}"], - [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] - ] + "/goto_next_from/#{id}"]] + if msgs_unread.length > 0 + actionlist << [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"] + else + actionlist << [ ' ', '[ ]forum list', "/leave_forum/#{id}"] + end + actionlist << [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] linklist, keypressproc = actions(actionlist) keypress { | key | keypressproc.call(key) } open_shown = false page_box do header_box(linklist, cache[:name]) [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 chunk_section_box(group_name, open_shown) do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] chunk_box do para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end open_shown = true end end end end def foruminfo(id) id = id.to_i info "foruminfo #{id}" @page = page_box do para "loading info for forum #{id}..." end linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], - [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } Thread.new do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) @page.clear do section_box do para *linklist end section_box do caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end end - def first_unread(forum_id) - info "first_unread for forum_id #{forum_id}" - forum_id = forum_id.to_i - cache = @@forum_cache[forum_id] - - page_box do - para "finding first unread message in forum #{forum_id}..." - end - - noteids = cache[:noteids] - first_unread_msg = cache[:first_unread] - first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } - if first_unread_found - visit "/message/#{forum_id}/#{first_unread_found}/forward" - else - visit "/leave_forum/#{forum_id}" - end - end - def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i @page = page_box do para "loading messge #{msgnum} in forum #{forum_id}" end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } Thread.new do msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @page.clear do section_box do para *linklist end section_box do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @page = page_box do "loading message #{msgnum} in forum #{forum_id} to reply to..." end Thread.new do msg = get_message(forum_id, msgnum) old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" @page.clear do section_box do para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end def new_post(forum_id) @page = page_box do section_box do tagline "New Post", :stroke => randcolor(:realdark), :align => right para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text @page.clear do para "posting message..." end Thread.new do new_post = @@bbs.jump(forum_id).post(text) recording_last_read(forum_id) do visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end end end end Shoes.app :width => 850
edheil/shoesca
aeeb0f23619f24141cf655cbf44520244ce29aa5
bring threading back where appropriate
diff --git a/shoesca.rb b/shoesca.rb index 7ddc773..110ed9d 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,571 +1,664 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} - def show_page - info "show_page" + def page_box + st = nil background black stack :margin => 20 do background randcolor(:dark), :curve => 20 - stack :margin => 20 do + st = stack :margin => 20 do yield if block_given? end end + st end - def show_section - info "show_section: background" + + def section_box + st = nil stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 - stack :margin => 20 do + st = stack :margin => 20 do info "yielding..." yield if block_given? end end + st end - - def show_chunk(coloring=nil) - coloring ||= rgb(1.0, 1.0, 1.0, 0.5) + + def chunk_section_box(text, hidden=true) + the_flow = nil + section_box do + flow(:click => Proc.new { the_flow.toggle }, + :margin => 20 + ) do + background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20 + caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 + end + the_flow = flow :hidden => hidden do + yield + end + end + end + + def header_box(linklist=[], text = "") + section_box do + flow do + flow( :width => -200) do + para *linklist + end + flow( :width => 200) do + tagline( text, :stroke => randcolor(:realdark), + :margin => 20, :align => 'right') + end + end + end + end + + def chunk_box stack :width => 200 do - background coloring, :curve => 10, :margin => 10 + background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20 stack :margin => 20 do yield if block_given? end end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] - when :light: [0.8, 0.4] - when :realdark: [ 0.1, 0.2] - else [0.5, 0.6] - end + when :light: [0.8, 0.4] + when :realdark: [ 0.1, 0.2] + else [0.5, 0.6] + end rgb( ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, alpha) end def license info "license" - show_page do - show_section do + page_box do + section_box do background aliceblue, :curve => 20 para link('back', :click => '/login') para LICENSE end end end + def recording_last_read(forum_id) + if should_record_last_read(forum_id) + clear do + page_box do + para "recording last read message..." + end + end + Thread.new do + record_last_read(forum_id) + yield + end + else + yield + end + end + + def should_record_last_read(forum_id) + forum_id = forum_id.to_i + info "should_record_last_read for #{forum_id}" + cached = @@forum_cache[forum_id] + cached[:first_unread] != cached[:server_first_unread] + end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] - if cached - if cached[:first_unread] != cached[:server_first_unread] - forum = @@bbs.jump(forum_id) - forum.first_unread = cached[:first_unread] - cached[:server_first_unread] = cached[:first_unread] - - if cached[:first_unread] > cached[:noteids].last - @@bbs_cache[:todo].delete(forum_id) - end - - if cached[:first_unread] <= cached[:noteids].last - @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] - end - end + forum = @@bbs.jump(forum_id) + forum.first_unread = cached[:first_unread] + cached[:server_first_unread] = cached[:first_unread] + + if cached[:first_unread] > cached[:noteids].last + @@bbs_cache[:todo].delete(forum_id) + end + + if cached[:first_unread] <= cached[:noteids].last + @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end def quit_from_forum(id) info "quit_from_forum" - record_last_read(id) - exit() + page_box do + "Quitting..." + end + recording_last_read(id) do + exit() + end end def quit info "quit" exit() end def login_error(error) stack do para err.message link("try again",:click => '/') end end def do_login(username, password) - begin - @@bbs = Raccdoc::Connection.new(:user => username, :password => password, - :host => HOST, - :port => PORT - ) - YAML::Store.new('bbsconfig.yaml').transaction do |store| - store['username'], store['password'] = username, password + page_box do + para "logging in..." + end + Thread.new do + begin + @@bbs = Raccdoc::Connection.new(:user => username, :password => password, + :host => HOST, + :port => PORT + ) + YAML::Store.new('bbsconfig.yaml').transaction do |store| + store['username'], store['password'] = username, password + end + visit '/load_bbs' + rescue RuntimeError => err + debug "error: #{err.message}" + @@bbs = nil + visit "/login_error/#{err.message}" end - visit '/load_bbs' - rescue RuntimeError => err - debug "error: #{err.message}" - @@bbs = nil - visit "/login_error/#{err.message}" end end def login username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end keypress do | key | if key == "\n" visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end - - show_page do - show_section do + @content = page_box do + section_box do tagline "Login", :stroke => randcolor(:realdark), :align => right para "username:" @username_line = app.edit_line "#{ username }" para "password:" @password_line = app.edit_line "#{ password }", :secret => true - button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end - para(link( 'license', :click => '/license' )) end end end def quit - show_page do + page_box do exit() end end def leave_forum(id) info "leave forum #{id}" - show_page - record_last_read(id) - visit '/bbs' + page_box + page_box do + para "leaving forum #{id}..." + end + recording_last_read(id) do + visit '/bbs' + end end + def load_bbs - show_page - @@bbs_cache[:all] = @@bbs.forums('all') - @@bbs_cache[:todo] = @@bbs.forums('todo') - @@bbs_cache[:joined] = @@bbs.forums('joined') - visit '/bbs' + info "load_bbs" + page_box do + para "loading forums..." + end + Thread.new do + @@bbs_cache[:all] = @@bbs.forums('all') + @@bbs_cache[:todo] = @@bbs.forums('todo') + @@bbs_cache[:joined] = @@bbs.forums('joined') + visit '/bbs' + end end def bbs + info "bbs" forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] linklist, keypressproc = actions( action_list ) keypress { | key | keypressproc.call(key) } - show_page do - show_section do - para *linklist - end - #flow(:margin_left => 20, :margin_top => 20) { para *linklist } - # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', - # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } - [ ["Unread", forums_todo, ivory], - ["Subscribed", forums_joined, lightgrey], - ["Zapped", forums_all, darkslateblue]].each do | group | - group_name, ordered_ids, coloring = *group + open_shown = false + page_box do + header_box( linklist, "Forums") + [ ["Unread", forums_todo ], + ["Subscribed", forums_joined ], + ["Zapped", forums_all ]].each do | group | + group_name, ordered_ids = *group if ordered_ids.length > 0 - show_section do - info "doing #{group_name}" - caption( group_name, - :align => 'right', - :margin => 20 ) - flow do - ordered_ids.each do | id | - data = forums[id] - show_chunk do - para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") - end + chunk_section_box(group_name, open_shown) do + ordered_ids.each do | id | + data = forums[id] + chunk_box do + para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end + open_shown = true end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* + page_box do + para "leaving forum #{forum_id}.." + end cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 - record_last_read(forum_id) + todo_list = @@bbs_cache[:todo].keys.sort - if todo_list.length > 0 - visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" - else - visit "/bbs" + recording_last_read(forum_id) do + if todo_list.length > 0 + visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" + else + visit "/bbs" + end end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i - record_last_read(old_id) - visit "/enter_forum/#{new_id}" + recording_last_read(old_id) do + visit "/enter_forum/#{new_id}" + end end def enter_forum(id) + page_box do + para "loading forum #{id}..." + end info "enter_forum #{id}" id = id.to_i - # we pull stuff into forum_cache only when we enter a new forum. - forum = @@bbs.jump(id) - cache = {} - first_unread = forum.first_unread.to_i - info "first_unread: #{ first_unread.inspect }" - cache[:server_first_unread] = first_unread - cache[:first_unread] = first_unread - info "first unread: #{first_unread.inspect}" - info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" - noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" - cache[:noteids] = forum.noteids(noterange).sort - if cache[:noteids].length == 0 # uh oh - noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" + Thread.new do + # we pull stuff into forum_cache only when we enter a new forum. + forum = @@bbs.jump(id) + cache = {} + first_unread = forum.first_unread.to_i + info "first_unread: #{ first_unread.inspect }" + cache[:server_first_unread] = first_unread + cache[:first_unread] = first_unread + info "first unread: #{first_unread.inspect}" + info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" + noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort + if cache[:noteids].length == 0 # uh oh + noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" + cache[:noteids] = forum.noteids(noterange).sort + end + info "noterange: #{noterange}" + cache[:post_headers] = forum.post_headers(noterange) + cache[:name] = forum.name + cache[:post_ok] = forum.post? + cache[:admin] = forum.admin + cache[:anonymous] = forum.anonymous + cache[:private] = forum.private + @@forum_cache[id] = cache + visit "/forum/#{id}" end - info "noterange: #{noterange}" - cache[:post_headers] = forum.post_headers(noterange) - cache[:name] = forum.name - cache[:post_ok] = forum.post? - cache[:admin] = forum.admin - cache[:anonymous] = forum.anonymous - cache[:private] = forum.private - @@forum_cache[id] = cache - visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } + actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"], + [ 'i', '[i]nfo', "/foruminfo/#{id}"], + [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], + [ 'f', 'read [f]orward', + "/message/#{id}/#{noteids.first}/forward"], + [ 'b', 'read [b]ackward', + "/message/#{id}/#{noteids.last}/backward"], + [ 'g', '[g]oto next forum with unread messages', + "/goto_next_from/#{id}"], + [ ' ', '[ ]first unread', "/first_unread/#{id}"], + [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] + ] - linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], - [ 'i', '[i]nfo', "/foruminfo/#{id}"], - [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], - [ 'f', 'read [f]orward', - "/message/#{id}/#{noteids.first}/forward"], - [ 'b', 'read [b]ackward', - "/message/#{id}/#{noteids.last}/backward"], - [ 'g', '[g]oto next forum with unread messages', - "/goto_next_from/#{id}"], - [ ' ', '[ ]first unread', "/first_unread/#{id}"], - [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] - ] ) + linklist, keypressproc = actions(actionlist) keypress { | key | keypressproc.call(key) } - show_page do - show_section do - para *linklist - tagline( cache[:name], :stroke => randcolor(:realdark), - :margin => 20, :align => 'right') - end + open_shown = false + page_box do + header_box(linklist, cache[:name]) [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 - show_section do - caption group_name, :align => 'right', :stroke => randcolor(:realdark) - flow do - ordered_ids.reverse.each do | post_id | - post = posts[post_id.to_s] - show_chunk do - para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") - para post[:subject] - end + chunk_section_box(group_name, open_shown) do + ordered_ids.reverse.each do | post_id | + post = posts[post_id.to_s] + chunk_box do + para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") + para post[:subject] end end end + open_shown = true end end end end def foruminfo(id) id = id.to_i info "foruminfo #{id}" + @page = page_box do + para "loading info for forum #{id}..." + end + linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } - - show_page do - para *linklist + + Thread.new do @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) - show_section do - caption "Forum moderator is #{@@forum_cache[id][:admin]}." - caption "Forum info last updated #{info[:date]} by #{info[:from]}" - para "#{info[:body]}" - body_urls.each do | a_url | - para link(a_url, :click => a_url) + @page.clear do + section_box do + para *linklist + end + section_box do + caption "Forum moderator is #{@@forum_cache[id][:admin]}." + caption "Forum info last updated #{info[:date]} by #{info[:from]}" + para "#{info[:body]}" + body_urls.each do | a_url | + para link(a_url, :click => a_url) + end end end end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" forum_id = forum_id.to_i cache = @@forum_cache[forum_id] - show_page do + page_box do para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) - show_page forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i + @page = page_box do + para "loading messge #{msgnum} in forum #{forum_id}" + end + post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } - show_page do - show_section do - para *linklist - end - msg = get_message(forum_id, msgnum) - body_urls = msg[:body].scan(URLRE) - authority = " (#{msg[:authority]})" if msg[:authority] - @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + - "#{msg[:body]}" + - "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") - - show_section do + Thread.new do + msg = get_message(forum_id, msgnum) + body_urls = msg[:body].scan(URLRE) + authority = " (#{msg[:authority]})" if msg[:authority] + @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + + "#{msg[:body]}" + + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") + + @page.clear do + section_box do + para *linklist + end + section_box do para @whole_message - body_urls.each do | a_url | - para link(a_url, :click => a_url) + body_urls.each do | a_url | + para link(a_url, :click => a_url) + end end end end - if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end + end def new_reply(forum_id, msgnum) - @post = @@bbs.jump(forum_id).read(msgnum) - old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") - quote = "#{@post.author} wrote:\n#{old_body}\n\n" - show_page do - tagline "New Post", :stroke => randcolor(:realdark), :align => 'right' - para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") - @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 - button "post" do - text = @post_box.text - new_post = @@bbs.jump(forum_id).post(text) - record_last_read(forum_id) - visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + @page = page_box do + "loading message #{msgnum} in forum #{forum_id} to reply to..." + end + + Thread.new do + msg = get_message(forum_id, msgnum) + old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n") + quote = "#{msg[:author]} wrote:\n#{old_body}\n\n" + @page.clear do + section_box do + para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") + tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right' + @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 + button "post" do + text = @post_box.text + new_post = @@bbs.jump(forum_id).post(text) + recording_last_read(forum_id) do + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + end + end + end end end end def new_post(forum_id) - show_page do - tagline "New Post", :stroke => randcolor(:realdark), :align => right - para link("back", :click => "/forum/#{forum_id}") - @post_box = edit_box :width => 500, :height => 300, :margin => 20 - button "post" do - text = @post_box.text - new_post = @@bbs.jump(forum_id).post(text) - record_last_read(forum_id) - visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + @page = page_box do + section_box do + tagline "New Post", :stroke => randcolor(:realdark), :align => right + para link("back", :click => "/forum/#{forum_id}") + @post_box = edit_box :width => 500, :height => 300, :margin => 20 + button "post" do + text = @post_box.text + @page.clear do + para "posting message..." + end + Thread.new do + new_post = @@bbs.jump(forum_id).post(text) + recording_last_read(forum_id) do + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + end + end + end end end end end - -Shoes.app :width => 800 +Shoes.app :width => 850
edheil/shoesca
04a4822278035c3753185f9d4fd489dc902396fc
abstract out page painting
diff --git a/shoesca.rb b/shoesca.rb index 8cd8895..7ddc773 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,549 +1,571 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} - def tweakcolor(r, g, b, v) + def show_page + info "show_page" + background black + stack :margin => 20 do + background randcolor(:dark), :curve => 20 + stack :margin => 20 do + yield if block_given? + end + end + end + def show_section + info "show_section: background" + stack :margin => 20 do + background randcolor(:light, 0.5), :curve => 20 + stack :margin => 20 do + info "yielding..." + yield if block_given? + end + end + end + + def show_chunk(coloring=nil) + coloring ||= rgb(1.0, 1.0, 1.0, 0.5) + stack :width => 200 do + background coloring, :curve => 10, :margin => 10 + stack :margin => 20 do + yield if block_given? + end + end end def randcolor(bias=nil, alpha = 1.0) target, range = case bias when :dark: [ 0.3, 0.3 ] when :light: [0.8, 0.4] when :realdark: [ 0.1, 0.2] else [0.5, 0.6] end rgb( ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, ( (rand - 0.5) * range ) + target, alpha) end def license info "license" - background black - stack :margin => 20 do - background aliceblue, :curve => 20 - para link('back', :click => '/login') - para LICENSE + show_page do + show_section do + background aliceblue, :curve => 20 + para link('back', :click => '/login') + para LICENSE + end end end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] if cached if cached[:first_unread] != cached[:server_first_unread] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end end end def quit_from_forum(id) info "quit_from_forum" record_last_read(id) exit() end def quit info "quit" exit() end def login_error(error) stack do para err.message link("try again",:click => '/') end end def do_login(username, password) begin @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password end visit '/load_bbs' rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil visit "/login_error/#{err.message}" end end def login - background black username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end - - stack :margin => 20 do - background randcolor(:light), :curve => 20 - stack :margin => 20 do + + keypress do | key | + if key == "\n" + visit "/do_login/#{@username_line.text}/#{@password_line.text}" + end + end + + show_page do + show_section do tagline "Login", :stroke => randcolor(:realdark), :align => right para "username:" - @username_line = edit_line "#{ username }" + @username_line = app.edit_line "#{ username }" para "password:" - @password_line = edit_line "#{ password }", :secret => true + @password_line = app.edit_line "#{ password }", :secret => true button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end para(link( 'license', :click => '/license' )) end - - keypress do | key | - if key == "\n" - visit "/do_login/#{@username_line.text}/#{@password_line.text}" - end - end end end def quit - exit() + show_page do + exit() + end end def leave_forum(id) info "leave forum #{id}" + show_page record_last_read(id) visit '/bbs' end def load_bbs - background black + show_page @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end def bbs - background black forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] linklist, keypressproc = actions( action_list ) keypress { | key | keypressproc.call(key) } - stack :margin => 20 do - background randcolor(:light, 0.5), :curve => 20 - flow(:margin_left => 20, :margin_top => 20) { para *linklist } + show_page do + show_section do + para *linklist + end + #flow(:margin_left => 20, :margin_top => 20) { para *linklist } # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo, ivory], ["Subscribed", forums_joined, lightgrey], ["Zapped", forums_all, darkslateblue]].each do | group | group_name, ordered_ids, coloring = *group - stack :margin => 20 do - background randcolor(:light, 0.5), :curve => 20 - caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 - flow do - coloring = rgb(1.0,1.0,1.0, 0.5) - ordered_ids.each do | id | - data = forums[id] - stack :width => 200, :margin => 20 do - background coloring, :curve => 10 - para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") + if ordered_ids.length > 0 + show_section do + info "doing #{group_name}" + caption( group_name, + :align => 'right', + :margin => 20 ) + flow do + ordered_ids.each do | id | + data = forums[id] + show_chunk do + para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") + end end end end end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 record_last_read(forum_id) todo_list = @@bbs_cache[:todo].keys.sort if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i record_last_read(old_id) visit "/enter_forum/#{new_id}" end def enter_forum(id) info "enter_forum #{id}" id = id.to_i - background black # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i - background black cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } - stack :margin => 20 do - background randcolor(:dark), :curve => 20 - flow(:margin => 20) { para *linklist } - tagline( cache[:name], :stroke => randcolor(:realdark), - :margin => 20, :align => 'right') + show_page do + show_section do + para *linklist + tagline( cache[:name], :stroke => randcolor(:realdark), + :margin => 20, :align => 'right') + end [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair - stack :margin => 20 do - background randcolor(nil, 0.5), :curve => 20 - caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 - flow do - ordered_ids.reverse.each do | post_id | - post = posts[post_id.to_s] - stack :margin => 20, :width => 200 do - background rgb(1.0,1.0,1.0, 0.5), :curve => 10 - para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") - para post[:subject] + if ordered_ids.length > 0 + show_section do + caption group_name, :align => 'right', :stroke => randcolor(:realdark) + flow do + ordered_ids.reverse.each do | post_id | + post = posts[post_id.to_s] + show_chunk do + para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") + para post[:subject] + end end end end end end end end def foruminfo(id) + id = id.to_i info "foruminfo #{id}" - background black - linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } - stack :margin => 20 do - background blanchedalmond, :curve => 20 - flow(:margin_left => 20, :margin_top => 20) { para *linklist } + show_page do + para *linklist @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) - stack :margin => 20 do - background lightgrey, :curve => 10 - caption "Forum moderator is #{@@forum_cache[:admin]}." + show_section do + caption "Forum moderator is #{@@forum_cache[id][:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" forum_id = forum_id.to_i - background black cache = @@forum_cache[forum_id] - stack :margin => 20 do - background blanchedalmond, :curve => 20 + show_page do para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) + show_page forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i - background black post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] - + linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } + show_page do + show_section do + para *linklist + end msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") - stack :margin => 20 do - background randcolor(:dark), :curve => 20 - flow(:margin_left => 20, :margin_top => 20) { para *linklist } - stack :margin => 20 do - background rgb(1.0,1.0,1.0,0.8), :curve => 20 + show_section do para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end + if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" - background black - stack :margin => 20 do - background randcolor(:light, 0.5), :curve => 20 - stack :margin => 20 do - tagline "New Post", :stroke => randcolor(:realdark), :align => 'right' - para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") - @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 - button "post" do - text = @post_box.text - new_post = @@bbs.jump(forum_id).post(text) - visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! - end + show_page do + tagline "New Post", :stroke => randcolor(:realdark), :align => 'right' + para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") + @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 + button "post" do + text = @post_box.text + new_post = @@bbs.jump(forum_id).post(text) + record_last_read(forum_id) + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end def new_post(forum_id) - background black - stack :margin => 20 do - background randcolor(:light, 0.5), :curve => 20 - stack :margin => 20 do - tagline "New Post", :stroke => randcolor(:realdark), :align => right - para link("back", :click => "/forum/#{forum_id}") - @post_box = edit_box :width => 500, :height => 300, :margin => 20 - button "post" do - text = @post_box.text - new_post = @@bbs.jump(forum_id).post(text) - visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! - end + show_page do + tagline "New Post", :stroke => randcolor(:realdark), :align => right + para link("back", :click => "/forum/#{forum_id}") + @post_box = edit_box :width => 500, :height => 300, :margin => 20 + button "post" do + text = @post_box.text + new_post = @@bbs.jump(forum_id).post(text) + record_last_read(forum_id) + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end Shoes.app :width => 800
edheil/shoesca
5d23c9172a739ab1f7337b2336755ce50f38dc9f
more cosmetics
diff --git a/shoesca.rb b/shoesca.rb index 5bbf1e2..8cd8895 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,547 +1,549 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} + def tweakcolor(r, g, b, v) + + end + def randcolor(bias=nil, alpha = 1.0) - if bias == :dark - rgb( (rand/2 + 0.2), (rand/2 + 0.2), (rand/2 + 0.2), alpha ) - elsif bias == :light - rgb( (rand/2 + 0.5), (rand/2 + 0.5), (rand/2 + 0.5), alpha ) - elsif bias == :realdark - rgb( rand/4, rand/4, rand/4, alpha) - else - rgb( rand * 0.8 + 0.2, rand * 0.8 + 0.2, rand * 0.8 + 0.2, alpha ) - end + target, range = case bias + when :dark: [ 0.3, 0.3 ] + when :light: [0.8, 0.4] + when :realdark: [ 0.1, 0.2] + else [0.5, 0.6] + end + rgb( ( (rand - 0.5) * range ) + target, + ( (rand - 0.5) * range ) + target, + ( (rand - 0.5) * range ) + target, + alpha) end + def license info "license" background black stack :margin => 20 do background aliceblue, :curve => 20 para link('back', :click => '/login') para LICENSE end end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] if cached if cached[:first_unread] != cached[:server_first_unread] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end end end def quit_from_forum(id) info "quit_from_forum" record_last_read(id) exit() end def quit info "quit" exit() end def login_error(error) stack do para err.message link("try again",:click => '/') end end def do_login(username, password) begin @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password end visit '/load_bbs' rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil visit "/login_error/#{err.message}" end end def login background black username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end stack :margin => 20 do background randcolor(:light), :curve => 20 stack :margin => 20 do - tagline "Login", :stroke => randcolor(:realdark) + tagline "Login", :stroke => randcolor(:realdark), :align => right para "username:" @username_line = edit_line "#{ username }" para "password:" @password_line = edit_line "#{ password }", :secret => true button "login" do visit "/do_login/#{@username_line.text}/#{@password_line.text}" end para(link( 'license', :click => '/license' )) end keypress do | key | if key == "\n" visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end end end def quit exit() end def leave_forum(id) info "leave forum #{id}" record_last_read(id) visit '/bbs' end def load_bbs background black @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end def bbs background black - - @mainstack = stack :margin => 20 do - background aliceblue, :curve => 20 - para "loading bbs..." - end - forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] linklist, keypressproc = actions( action_list ) keypress { | key | keypressproc.call(key) } - @mainstack.clear do + stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 flow(:margin_left => 20, :margin_top => 20) { para *linklist } # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo, ivory], ["Subscribed", forums_joined, lightgrey], ["Zapped", forums_all, darkslateblue]].each do | group | group_name, ordered_ids, coloring = *group stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 flow do coloring = rgb(1.0,1.0,1.0, 0.5) ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do background coloring, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 record_last_read(forum_id) todo_list = @@bbs_cache[:todo].keys.sort if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i record_last_read(old_id) visit "/enter_forum/#{new_id}" end def enter_forum(id) info "enter_forum #{id}" id = id.to_i background black # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i background black cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } - @mainstack = stack :margin => 20 do - background blanchedalmond, :curve => 20 - para "loading forum #{id}..." - end - - @mainstack.clear do - background blanchedalmond, :curve => 20 - tagline cache[:name], :stroke => randcolor(:realdark), :margin => 20 - flow(:margin_left => 20, :margin_top => 20) { para *linklist } + stack :margin => 20 do + background randcolor(:dark), :curve => 20 + flow(:margin => 20) { para *linklist } + tagline( cache[:name], :stroke => randcolor(:realdark), + :margin => 20, :align => 'right') [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair stack :margin => 20 do - background randcolor(:light, 0.5), :curve => 20 + background randcolor(nil, 0.5), :curve => 20 caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 flow do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] stack :margin => 20, :width => 200 do background rgb(1.0,1.0,1.0, 0.5), :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end def foruminfo(id) info "foruminfo #{id}" background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } stack :margin => 20 do background blanchedalmond, :curve => 20 flow(:margin_left => 20, :margin_top => 20) { para *linklist } @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) stack :margin => 20 do background lightgrey, :curve => 10 caption "Forum moderator is #{@@forum_cache[:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" forum_id = forum_id.to_i background black cache = @@forum_cache[forum_id] stack :margin => 20 do background blanchedalmond, :curve => 20 para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack :margin => 20 do - background randcolor, :curve => 20 + background randcolor(:dark), :curve => 20 flow(:margin_left => 20, :margin_top => 20) { para *linklist } stack :margin => 20 do background rgb(1.0,1.0,1.0,0.8), :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 - tagline "New Post", :stroke => randcolor(:realdark) - para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") - @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 - button "post" do - text = @post_box.text - new_post = @@bbs.jump(forum_id).post(text) - visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + stack :margin => 20 do + tagline "New Post", :stroke => randcolor(:realdark), :align => 'right' + para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") + @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 + button "post" do + text = @post_box.text + new_post = @@bbs.jump(forum_id).post(text) + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + end end end end def new_post(forum_id) background black stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 - tagline "New Post", :stroke => randcolor(:realdark) - para link("back", :click => "/forum/#{forum_id}") - @post_box = edit_box :width => 500, :height => 300, :margin => 20 - button "post" do - text = @post_box.text - new_post = @@bbs.jump(forum_id).post(text) - visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + stack :margin => 20 do + tagline "New Post", :stroke => randcolor(:realdark), :align => right + para link("back", :click => "/forum/#{forum_id}") + @post_box = edit_box :width => 500, :height => 300, :margin => 20 + button "post" do + text = @post_box.text + new_post = @@bbs.jump(forum_id).post(text) + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! + end end end end end + + Shoes.app :width => 800
edheil/shoesca
b749bd4ff767cd0c4436367432bc664f674bc443
cosmetics
diff --git a/shoesca.rb b/shoesca.rb index 6931c19..5bbf1e2 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,546 +1,547 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/login_error/(.+)', :login_error url '/bbs', :bbs url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} def randcolor(bias=nil, alpha = 1.0) if bias == :dark rgb( (rand/2 + 0.2), (rand/2 + 0.2), (rand/2 + 0.2), alpha ) elsif bias == :light rgb( (rand/2 + 0.5), (rand/2 + 0.5), (rand/2 + 0.5), alpha ) elsif bias == :realdark rgb( rand/4, rand/4, rand/4, alpha) else rgb( rand * 0.8 + 0.2, rand * 0.8 + 0.2, rand * 0.8 + 0.2, alpha ) end end def license info "license" background black stack :margin => 20 do background aliceblue, :curve => 20 para link('back', :click => '/login') para LICENSE end end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] if cached if cached[:first_unread] != cached[:server_first_unread] forum = @@bbs.jump(forum_id) forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] if cached[:first_unread] > cached[:noteids].last @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end end end def quit_from_forum(id) info "quit_from_forum" record_last_read(id) exit() end def quit info "quit" exit() end def login_error(error) stack do para err.message link("try again",:click => '/') end end def do_login(username, password) begin @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => HOST, :port => PORT ) YAML::Store.new('bbsconfig.yaml').transaction do |store| store['username'], store['password'] = username, password end visit '/load_bbs' rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil visit "/login_error/#{err.message}" end end def login background black username, password = nil, nil YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| username, password = store['username'], store['password'] end stack :margin => 20 do background randcolor(:light), :curve => 20 - tagline "Login", :stroke => randcolor(:realdark) - para "username:" - @username_line = edit_line "#{ username }" - para "password:" - @password_line = edit_line "#{ password }", :secret => true - - button "login" do - visit "/do_login/#{@username_line.text}/#{@password_line.text}" + stack :margin => 20 do + tagline "Login", :stroke => randcolor(:realdark) + para "username:" + @username_line = edit_line "#{ username }" + para "password:" + @password_line = edit_line "#{ password }", :secret => true + + button "login" do + visit "/do_login/#{@username_line.text}/#{@password_line.text}" + end + + para(link( 'license', :click => '/license' )) end - para(link( 'license', :click => '/license' )) - keypress do | key | if key == "\n" visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end end end def quit exit() end def leave_forum(id) info "leave forum #{id}" record_last_read(id) visit '/bbs' end def load_bbs background black @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end def bbs background black @mainstack = stack :margin => 20 do background aliceblue, :curve => 20 para "loading bbs..." end forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] linklist, keypressproc = actions( action_list ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background randcolor(:light, 0.5), :curve => 20 - para *linklist + flow(:margin_left => 20, :margin_top => 20) { para *linklist } # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo, ivory], ["Subscribed", forums_joined, lightgrey], ["Zapped", forums_all, darkslateblue]].each do | group | group_name, ordered_ids, coloring = *group stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 - caption group_name + caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 flow do - coloring = randcolor(:light, 0.5) + coloring = rgb(1.0,1.0,1.0, 0.5) ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do background coloring, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 record_last_read(forum_id) todo_list = @@bbs_cache[:todo].keys.sort if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i record_last_read(old_id) visit "/enter_forum/#{new_id}" end def enter_forum(id) info "enter_forum #{id}" id = id.to_i background black # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread info "first unread: #{first_unread.inspect}" info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort if cache[:noteids].length == 0 # uh oh noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" cache[:noteids] = forum.noteids(noterange).sort end info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i background black cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack :margin => 20 do background blanchedalmond, :curve => 20 para "loading forum #{id}..." end @mainstack.clear do background blanchedalmond, :curve => 20 - tagline cache[:name], :stroke => randcolor(:realdark) - para *linklist + tagline cache[:name], :stroke => randcolor(:realdark), :margin => 20 + flow(:margin_left => 20, :margin_top => 20) { para *linklist } [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 - caption group_name - the_color = randcolor(:light) + caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20 flow do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] stack :margin => 20, :width => 200 do - background the_color, :curve => 10 + background rgb(1.0,1.0,1.0, 0.5), :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end def foruminfo(id) info "foruminfo #{id}" background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } stack :margin => 20 do background blanchedalmond, :curve => 20 - para *linklist + flow(:margin_left => 20, :margin_top => 20) { para *linklist } @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) stack :margin => 20 do background lightgrey, :curve => 10 caption "Forum moderator is #{@@forum_cache[:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" forum_id = forum_id.to_i background black cache = @@forum_cache[forum_id] stack :margin => 20 do background blanchedalmond, :curve => 20 para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack :margin => 20 do - background randcolor(:light, 0.5), :curve => 20 - para *linklist + background randcolor, :curve => 20 + flow(:margin_left => 20, :margin_top => 20) { para *linklist } stack :margin => 20 do - background randcolor(:light), :curve => 20 + background rgb(1.0,1.0,1.0,0.8), :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 tagline "New Post", :stroke => randcolor(:realdark) para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end def new_post(forum_id) background black stack :margin => 20 do background randcolor(:light, 0.5), :curve => 20 tagline "New Post", :stroke => randcolor(:realdark) para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end Shoes.app :width => 800
edheil/shoesca
ccbe1dbd8c78d0cc322baff134f9cfd5357abb4c
smarter noteids, random colors
diff --git a/shoesca.rb b/shoesca.rb index 814ea3e..6931c19 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,557 +1,546 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login + url '/login_error/(.+)', :login_error url '/bbs', :bbs + url '/do_login/([^\/]+)/(.+)', :do_login url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} + def randcolor(bias=nil, alpha = 1.0) + if bias == :dark + rgb( (rand/2 + 0.2), (rand/2 + 0.2), (rand/2 + 0.2), alpha ) + elsif bias == :light + rgb( (rand/2 + 0.5), (rand/2 + 0.5), (rand/2 + 0.5), alpha ) + elsif bias == :realdark + rgb( rand/4, rand/4, rand/4, alpha) + else + rgb( rand * 0.8 + 0.2, rand * 0.8 + 0.2, rand * 0.8 + 0.2, alpha ) + end + end + def license info "license" background black stack :margin => 20 do background aliceblue, :curve => 20 - border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] if cached - info "got cache" - info "seeing if #{ cached[:first_unread] } != #{ cached[:server_first_unread] }" if cached[:first_unread] != cached[:server_first_unread] - info "yep. must modify server's first_unread" forum = @@bbs.jump(forum_id) - info "setting first_unread to #{cached[:first_unread]}" forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] - info "after the change..." if cached[:first_unread] > cached[:noteids].last - info "first_unread is greater than last_note. deleting #{forum_id} from todo" @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last - info "first_unread is less than or equal to last_note. adding #{forum_id} to todo" @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end end end def quit_from_forum(id) info "quit_from_forum" record_last_read(id) exit() end def quit info "quit" exit() end - - - def login - background black - @store = YAML::Store.new('bbsconfig.yaml') - @username, @password = nil, nil - @store.transaction(true) do - @username, @password = @store['username'], @store['password'] + def login_error(error) + stack do + para err.message + link("try again",:click => '/') end + end - def do_login - @@username = @username_line.text - @@password = @password_line.text - @mainstack.append do - para "logging in..." + def do_login(username, password) + begin + @@bbs = Raccdoc::Connection.new(:user => username, :password => password, + :host => HOST, + :port => PORT + ) + YAML::Store.new('bbsconfig.yaml').transaction do |store| + store['username'], store['password'] = username, password end - Thread.new do - begin - @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, - :host => HOST, - :port => PORT - ) - rescue RuntimeError => err - debug "error: #{err.message}" - @@bbs = nil - @mainstack.append do - para err.message - end - end - if @@bbs - @store.transaction do - @store['username'], @store['password'] = @username, @password - end - visit '/load_bbs' - end - end + visit '/load_bbs' + rescue RuntimeError => err + debug "error: #{err.message}" + @@bbs = nil + visit "/login_error/#{err.message}" end + end + def login + background black + username, password = nil, nil + YAML::Store.new('bbsconfig.yaml').transaction(true) do |store| + username, password = store['username'], store['password'] + end - @mainstack = stack :margin => 20 do - background salmon, :curve => 20 - border black, :curve => 20 - tagline "Login" + stack :margin => 20 do + background randcolor(:light), :curve => 20 + tagline "Login", :stroke => randcolor(:realdark) para "username:" - @username_line = edit_line "#{ @username }" + @username_line = edit_line "#{ username }" para "password:" - @password_line = edit_line "#{ @password }", :secret => true + @password_line = edit_line "#{ password }", :secret => true button "login" do - do_login + visit "/do_login/#{@username_line.text}/#{@password_line.text}" end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" - do_login + visit "/do_login/#{@username_line.text}/#{@password_line.text}" end end end end def quit exit() end def leave_forum(id) info "leave forum #{id}" record_last_read(id) visit '/bbs' end def load_bbs background black @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end def bbs background black @mainstack = stack :margin => 20 do background aliceblue, :curve => 20 - border black, :curve => 20 para "loading bbs..." end forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 - action_list << [ ' ', '[ ]first forum with unread', "/forum/#{forums_todo.first}"] + action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] linklist, keypressproc = actions( action_list ) keypress { | key | keypressproc.call(key) } @mainstack.clear do - background aliceblue, :curve => 20 - border black, :curve => 20 + background randcolor(:light, 0.5), :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo, ivory], ["Subscribed", forums_joined, lightgrey], ["Zapped", forums_all, darkslateblue]].each do | group | group_name, ordered_ids, coloring = *group stack :margin => 20 do - background white, :curve => 20 - border black, :curve => 20 + background randcolor(:light, 0.5), :curve => 20 caption group_name flow do + coloring = randcolor(:light, 0.5) ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do background coloring, :curve => 10 - border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 record_last_read(forum_id) todo_list = @@bbs_cache[:todo].keys.sort if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i record_last_read(old_id) visit "/enter_forum/#{new_id}" end def enter_forum(id) info "enter_forum #{id}" id = id.to_i background black # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i + info "first_unread: #{ first_unread.inspect }" cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread + info "first unread: #{first_unread.inspect}" + info "forum_id info: #{ @@bbs_cache[:all][id].inspect }" noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" cache[:noteids] = forum.noteids(noterange).sort + if cache[:noteids].length == 0 # uh oh + noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }" + cache[:noteids] = forum.noteids(noterange).sort + end + info "noterange: #{noterange}" cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name cache[:post_ok] = forum.post? cache[:admin] = forum.admin cache[:anonymous] = forum.anonymous cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i background black cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack :margin => 20 do background blanchedalmond, :curve => 20 - border black, :curve => 20 para "loading forum #{id}..." end @mainstack.clear do background blanchedalmond, :curve => 20 - border black, :curve => 20 - tagline cache[:name] + tagline cache[:name], :stroke => randcolor(:realdark) para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair stack :margin => 20 do - background white, :curve => 20 - border black, :curve => 20 + background randcolor(:light, 0.5), :curve => 20 caption group_name + the_color = randcolor(:light) flow do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] stack :margin => 20, :width => 200 do - background ivory, :curve => 10 - border black, :curve => 10 + background the_color, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end def foruminfo(id) info "foruminfo #{id}" background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } stack :margin => 20 do background blanchedalmond, :curve => 20 - border black, :curve => 20 para *linklist @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information info = @@forum_cache[:forum_info] the_body = info[:body] body_urls = the_body.scan(URLRE) stack :margin => 20 do background lightgrey, :curve => 10 - border black, :curve => 10 caption "Forum moderator is #{@@forum_cache[:admin]}." caption "Forum info last updated #{info[:date]} by #{info[:from]}" para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" forum_id = forum_id.to_i background black cache = @@forum_cache[forum_id] stack :margin => 20 do background blanchedalmond, :curve => 20 - border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black - stack :margin => 20 do - background gold, :curve => 20 - border black, :curve => 20 - @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } - end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") - @messagestack.clear do + stack :margin => 20 do + background randcolor(:light, 0.5), :curve => 20 para *linklist stack :margin => 20 do - background aliceblue, :curve => 20 - border black, :curve => 20 + background randcolor(:light), :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack :margin => 20 do - background lime, :curve => 20 - border black, :curve => 20 - tagline "New Post" + background randcolor(:light, 0.5), :curve => 20 + tagline "New Post", :stroke => randcolor(:realdark) para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end def new_post(forum_id) background black stack :margin => 20 do - background lime, :curve => 20 - border black, :curve => 20 - tagline "New Post" + background randcolor(:light, 0.5), :curve => 20 + tagline "New Post", :stroke => randcolor(:realdark) para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end Shoes.app :width => 800
edheil/shoesca
2c852e482da303fdbadcd2ee8d89acaf59a5d281
add "horizon" of 200 posts, cleanup unused methods
diff --git a/shoesca.rb b/shoesca.rb index 555c73f..814ea3e 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,565 +1,557 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') + HORIZON = 200 # the range of noteids retrieved before or after the first_unread url '/', :login url '/bbs', :bbs url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} def license info "license" background black stack :margin => 20 do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] if cached info "got cache" info "seeing if #{ cached[:first_unread] } != #{ cached[:server_first_unread] }" if cached[:first_unread] != cached[:server_first_unread] info "yep. must modify server's first_unread" forum = @@bbs.jump(forum_id) info "setting first_unread to #{cached[:first_unread]}" forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] info "after the change..." if cached[:first_unread] > cached[:noteids].last info "first_unread is greater than last_note. deleting #{forum_id} from todo" @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last info "first_unread is less than or equal to last_note. adding #{forum_id} to todo" @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end end end def quit_from_forum(id) info "quit_from_forum" record_last_read(id) exit() end def quit info "quit" exit() end def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @@username = @username_line.text @@password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/load_bbs' end end end @mainstack = stack :margin => 20 do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def quit exit() end def leave_forum(id) info "leave forum #{id}" record_last_read(id) visit '/bbs' end def load_bbs background black @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end def bbs background black @mainstack = stack :margin => 20 do background aliceblue, :curve => 20 border black, :curve => 20 para "loading bbs..." end forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 action_list << [ ' ', '[ ]first forum with unread', "/forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] linklist, keypressproc = actions( action_list ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo, ivory], ["Subscribed", forums_joined, lightgrey], ["Zapped", forums_all, darkslateblue]].each do | group | group_name, ordered_ids, coloring = *group stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do background coloring, :curve => 10 border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 record_last_read(forum_id) todo_list = @@bbs_cache[:todo].keys.sort if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end - - def with_new_bbs_connection - begin - bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, - :host => HOST, - :port => PORT - ) - yield bbs - rescue RuntimeError => err - debug "error: #{err.message}" - visit '/' - end - end - def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i record_last_read(old_id) visit "/enter_forum/#{new_id}" end def enter_forum(id) info "enter_forum #{id}" id = id.to_i background black # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread - cache[:post_headers] = forum.post_headers - cache[:noteids] = forum.noteids.sort + noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }" + cache[:noteids] = forum.noteids(noterange).sort + cache[:post_headers] = forum.post_headers(noterange) cache[:name] = forum.name + cache[:post_ok] = forum.post? + cache[:admin] = forum.admin + cache[:anonymous] = forum.anonymous + cache[:private] = forum.private @@forum_cache[id] = cache visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i background black cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end @mainstack.clear do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline cache[:name] para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] stack :margin => 20, :width => 200 do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end - + def foruminfo(id) info "foruminfo #{id}" - @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist - @info = @forum.forum_information - the_body = @info[:body] + @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information + info = @@forum_cache[:forum_info] + the_body = info[:body] body_urls = the_body.scan(URLRE) stack :margin => 20 do background lightgrey, :curve => 10 border black, :curve => 10 - caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." - caption "Forum info last updated #{@info[:date]} by Mikemike" - para "#{@info[:body]}" + caption "Forum moderator is #{@@forum_cache[:admin]}." + caption "Forum info last updated #{info[:date]} by #{info[:from]}" + para "#{info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" forum_id = forum_id.to_i background black cache = @@forum_cache[forum_id] stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black stack :margin => 20 do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) authority = " (#{msg[:authority]})" if msg[:authority] @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") @messagestack.clear do para *linklist stack :margin => 20 do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack :margin => 20 do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) - visit("/forum/#{forum_id}"); + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end def new_post(forum_id) background black stack :margin => 20 do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) - visit("/forum/#{forum_id}"); + visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post! end end end end Shoes.app :width => 800
edheil/shoesca
33f014f883053fc52d21163e835295307468d7ca
remove first_todo which isn't needed anymore
diff --git a/shoesca.rb b/shoesca.rb index 7dcc526..555c73f 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,586 +1,565 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :login url '/bbs', :bbs url '/load_bbs', :load_bbs url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo - url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} def license info "license" background black stack :margin => 20 do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] if cached info "got cache" info "seeing if #{ cached[:first_unread] } != #{ cached[:server_first_unread] }" if cached[:first_unread] != cached[:server_first_unread] info "yep. must modify server's first_unread" forum = @@bbs.jump(forum_id) info "setting first_unread to #{cached[:first_unread]}" forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] info "after the change..." if cached[:first_unread] > cached[:noteids].last info "first_unread is greater than last_note. deleting #{forum_id} from todo" @@bbs_cache[:todo].delete(forum_id) end if cached[:first_unread] <= cached[:noteids].last info "first_unread is less than or equal to last_note. adding #{forum_id} to todo" @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] end end end end def quit_from_forum(id) info "quit_from_forum" record_last_read(id) exit() end def quit info "quit" exit() end def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @@username = @username_line.text @@password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/load_bbs' end end end @mainstack = stack :margin => 20 do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def quit exit() end def leave_forum(id) info "leave forum #{id}" record_last_read(id) visit '/bbs' end def load_bbs background black @@bbs_cache[:all] = @@bbs.forums('all') @@bbs_cache[:todo] = @@bbs.forums('todo') @@bbs_cache[:joined] = @@bbs.forums('joined') visit '/bbs' end def bbs background black @mainstack = stack :margin => 20 do background aliceblue, :curve => 20 border black, :curve => 20 para "loading bbs..." end forums = @@bbs_cache[:all] forums_todo = (@@bbs_cache[:todo].keys - [1]).sort forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort # delete mail forums.delete(1) action_list = [] if forums_todo.length > 0 - action_list << [ ' ', '[ ]first forum with unread', "/first_todo"] + action_list << [ ' ', '[ ]first forum with unread', "/forum/#{forums_todo.first}"] else action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] end action_list << [ 'q', '[q]uit', '/quit' ] linklist, keypressproc = actions( action_list ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo, ivory], ["Subscribed", forums_joined, lightgrey], ["Zapped", forums_all, darkslateblue]].each do | group | group_name, ordered_ids, coloring = *group stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do background coloring, :curve => 10 border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end def goto_next_from(forum_id) forum_id = forum_id.to_i # id is forum to jump *from* cache = @@forum_cache[forum_id] cache[:first_unread] = cache[:noteids].last + 1 record_last_read(forum_id) todo_list = @@bbs_cache[:todo].keys.sort if todo_list.length > 0 visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" else visit "/bbs" end end def with_new_bbs_connection begin bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) yield bbs rescue RuntimeError => err debug "error: #{err.message}" visit '/' end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i record_last_read(old_id) visit "/enter_forum/#{new_id}" end def enter_forum(id) info "enter_forum #{id}" id = id.to_i background black # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread cache[:post_headers] = forum.post_headers cache[:noteids] = forum.noteids.sort cache[:name] = forum.name @@forum_cache[id] = cache visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i background black cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto_next_from/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end @mainstack.clear do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline cache[:name] para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] stack :margin => 20, :width => 200 do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end def foruminfo(id) info "foruminfo #{id}" @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack :margin => 20 do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end - - def first_todo - info "first_todo" - background black - stack :margin => 20 do - background blanchedalmond, :curve => 20 - border black, :curve => 20 - para "finding first forum with unread messages..." - end - forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort - if forums_todo.length > 0 - forum_id = forums_todo[0] - visit "/enter_forum/#{forum_id}" - else - visit "/bbs" - end - end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" forum_id = forum_id.to_i background black cache = @@forum_cache[forum_id] stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) forum_id = forum_id.to_i; msgnum = msgnum.to_i cache = @@forum_cache[forum_id] if msgnum < cache[:first_unread] cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black stack :margin => 20 do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | - keypressproc.call(key) + keypressproc.call(key) } -# Thread.new { - msg = get_message(forum_id, msgnum) - - body_urls = msg[:body].scan(URLRE) - - @messagestack.clear do - para *linklist - @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + - "#{msg[:body]}" + - "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") - - stack :margin => 20 do - background aliceblue, :curve => 20 - border black, :curve => 20 - para @whole_message - body_urls.each do | a_url | - para link(a_url, :click => a_url) - end + msg = get_message(forum_id, msgnum) + body_urls = msg[:body].scan(URLRE) + authority = " (#{msg[:authority]})" if msg[:authority] + @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" + + "#{msg[:body]}" + + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") + + @messagestack.clear do + para *linklist + stack :margin => 20 do + background aliceblue, :curve => 20 + border black, :curve => 20 + para @whole_message + body_urls.each do | a_url | + para link(a_url, :click => a_url) end end - if @@forum_cache[forum_id][:first_unread] <= msgnum - @@forum_cache[forum_id][:first_unread] = msgnum + 1 - end - # } + end + if @@forum_cache[forum_id][:first_unread] <= msgnum + @@forum_cache[forum_id][:first_unread] = msgnum + 1 + end end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack :margin => 20 do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end def new_post(forum_id) background black stack :margin => 20 do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end end Shoes.app :width => 800
edheil/shoesca
f0ea047becbd699eafe7e75bc0984d376f664be0
caching forum_list, cleanup, fix quit_from_forum
diff --git a/shoesca.rb b/shoesca.rb index eeab7ef..3dd4b6a 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,584 +1,602 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 - STACKSTYLE = { :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :login url '/bbs', :bbs + url '/load_bbs', :load_bbs + url '/quit_from_forum/(\d+)', :quit_from_forum url '/quit', :quit - url '/quit_from_forum/(d+)', :quit_from_forum - url '/goto/(\d+)', :goto + url '/goto_next_from/(\d+)', :goto_next_from url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil @@forum_cache = {} @@bbs_cache = {} def license info "license" background black - stack STACKSTYLE do + stack :margin => 20 do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] if cached info "got cache" - info "seeing if #{ cached[:first_unread] } > #{ cached[:server_first_unread] }" - if cached[:first_unread] > cached[:server_first_unread] - info "yep" + info "seeing if #{ cached[:first_unread] } != #{ cached[:server_first_unread] }" + if cached[:first_unread] != cached[:server_first_unread] + info "yep. must modify server's first_unread" forum = @@bbs.jump(forum_id) info "setting first_unread to #{cached[:first_unread]}" forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] + + info "after the change..." + if cached[:first_unread] > cached[:noteids].last + info "first_unread is greater than last_note. deleting #{forum_id} from todo" + @@bbs_cache[:todo].delete(forum_id) + end + + if cached[:first_unread] <= cached[:noteids].last + info "first_unread is less than or equal to last_note. adding #{forum_id} to todo" + @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id] + end end end end def quit_from_forum(id) info "quit_from_forum" record_last_read(id) exit() end def quit info "quit" exit() end def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @@username = @username_line.text @@password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end - visit '/bbs' + visit '/load_bbs' end end end - @mainstack = stack STACKSTYLE do + @mainstack = stack :margin => 20 do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def quit exit() end def leave_forum(id) info "leave forum #{id}" record_last_read(id) visit '/bbs' end + def load_bbs + background black + @@bbs_cache[:all] = @@bbs.forums('all') + @@bbs_cache[:todo] = @@bbs.forums('todo') + @@bbs_cache[:joined] = @@bbs.forums('joined') + visit '/bbs' + end + def bbs background black - @mainstack = stack STACKSTYLE do + @mainstack = stack :margin => 20 do background aliceblue, :curve => 20 border black, :curve => 20 para "loading bbs..." end - Thread.new do - forums = @@bbs.forums('all') - forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort - forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort - forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort - forums_todo.each { |n| forums[n][:todo] = true } - forums_joined.each { |n| forums[n][:joined] = true } - # delete mail - forums.delete(1) - linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], - [ 'q', '[q]uit', '/quit' ] - ] ) - keypress { | key | keypressproc.call(key) } - @mainstack.clear do - background aliceblue, :curve => 20 - border black, :curve => 20 - para *linklist - # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', - # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } - [ ["Unread", forums_todo], - ["Subscribed", forums_joined], - ["Zapped", forums_all]].each do | pair | - group_name, ordered_ids = *pair - stack STACKSTYLE do - background white, :curve => 20 - border black, :curve => 20 - caption group_name - flow do - ordered_ids.each do | id | - data = forums[id] - stack :width => 200, :margin => 20 do - if data[:todo] - background ivory, :curve => 10 - elsif data[:joined] - background lightgrey, :curve => 10 - else - background darkslateblue, :curve => 10 - end - border black, :curve => 10 - para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") - end + forums = @@bbs_cache[:all] + forums_todo = (@@bbs_cache[:todo].keys - [1]).sort + forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort + forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort + # delete mail + forums.delete(1) + action_list = [] + if forums_todo.length > 0 + action_list << [ ' ', '[ ]first forum with unread', "/first_todo"] + else + action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"] + end + action_list << [ 'q', '[q]uit', '/quit' ] + + linklist, keypressproc = actions( action_list ) + keypress { | key | keypressproc.call(key) } + @mainstack.clear do + background aliceblue, :curve => 20 + border black, :curve => 20 + para *linklist + # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', + # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } + [ ["Unread", forums_todo, ivory], + ["Subscribed", forums_joined, lightgrey], + ["Zapped", forums_all, darkslateblue]].each do | group | + group_name, ordered_ids, coloring = *group + stack :margin => 20 do + background white, :curve => 20 + border black, :curve => 20 + caption group_name + flow do + ordered_ids.each do | id | + data = forums[id] + stack :width => 200, :margin => 20 do + background coloring, :curve => 10 + border black, :curve => 10 + para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end - - def goto(id) + def goto_next_from(forum_id) + forum_id = forum_id.to_i # id is forum to jump *from* - id = id.to_i - para "marking read, moving on..." - Thread.new { - @the_forum = @@bbs.jump(id) - @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 - visit '/first_todo' - } + cache = @@forum_cache[forum_id] + cache[:first_unread] = cache[:noteids].last + 1 + record_last_read(forum_id) + todo_list = @@bbs_cache[:todo].keys.sort + if todo_list.length > 0 + visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}" + else + visit "/bbs" + end end def with_new_bbs_connection begin bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) yield bbs rescue RuntimeError => err debug "error: #{err.message}" visit '/' end end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i record_last_read(old_id) visit "/enter_forum/#{new_id}" end def enter_forum(id) info "enter_forum #{id}" id = id.to_i background black # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread cache[:post_headers] = forum.post_headers cache[:noteids] = forum.noteids.sort cache[:name] = forum.name @@forum_cache[id] = cache visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i background black cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', - "/goto/#{id}"], + "/goto_next_from/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } - @mainstack = stack STACKSTYLE do + @mainstack = stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end @mainstack.clear do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline cache[:name] para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] stack :margin => 20, :width => 200 do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end def foruminfo(id) info "foruminfo #{id}" @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } - stack STACKSTYLE do + stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) - stack STACKSTYLE do + stack :margin => 20 do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo info "first_todo" background black - stack STACKSTYLE do + stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] visit "/enter_forum/#{forum_id}" else visit "/bbs" end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" forum_id = forum_id.to_i background black cache = @@forum_cache[forum_id] - stack STACKSTYLE do + stack :margin => 20 do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) - @forum = @@bbs.jump(forum_id) - first_unread_msg = @forum.first_unread.to_i - if msgnum.to_i < first_unread_msg - @forum.first_unread = msgnum + forum_id = forum_id.to_i; msgnum = msgnum.to_i + cache = @@forum_cache[forum_id] + if msgnum < cache[:first_unread] + cache[:first_unread] = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else + info "visiting <#{action}>" visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end def get_message_from_db(db, forum_id, msgnum) sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;" result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end def get_message(forum_id, msgnum) msg = {} post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black - stack STACKSTYLE do + stack :margin => 20 do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } # Thread.new { msg = get_message(forum_id, msgnum) body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") - stack STACKSTYLE do + stack :margin => 20 do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end # } end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black - stack STACKSTYLE do + stack :margin => 20 do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end def new_post(forum_id) background black - stack STACKSTYLE do + stack :margin => 20 do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end end Shoes.app :width => 800
edheil/shoesca
e2b6b77fa4488aa9053beba78da0a85e66713219
remove traces of db caching change /forums to /bbs
diff --git a/shoesca.rb b/shoesca.rb index eb2b564..eeab7ef 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,617 +1,584 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' -#require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 STACKSTYLE = { :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :login - url '/forums', :forums + url '/bbs', :bbs url '/quit', :quit url '/quit_from_forum/(d+)', :quit_from_forum url '/goto/(\d+)', :goto url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply - @@bbs, @@msg_store = nil, nil + @@bbs = nil @@forum_cache = {} @@bbs_cache = {} -# @@msg_store = SQLite3::Database.new('messages.db') -# @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);"); def license info "license" background black stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] if cached info "got cache" info "seeing if #{ cached[:first_unread] } > #{ cached[:server_first_unread] }" if cached[:first_unread] > cached[:server_first_unread] info "yep" forum = @@bbs.jump(forum_id) info "setting first_unread to #{cached[:first_unread]}" forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] end end end def quit_from_forum(id) info "quit_from_forum" record_last_read(id) exit() end def quit info "quit" exit() end def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @@username = @username_line.text @@password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end - visit '/forums' + visit '/bbs' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def quit exit() end def leave_forum(id) info "leave forum #{id}" record_last_read(id) - visit '/forums' + visit '/bbs' end - def forums + def bbs background black @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 - para "loading forums..." + para "loading bbs..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', '/quit' ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end end def goto(id) # id is forum to jump *from* id = id.to_i para "marking read, moving on..." Thread.new { @the_forum = @@bbs.jump(id) @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 visit '/first_todo' } end def with_new_bbs_connection begin bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) yield bbs rescue RuntimeError => err debug "error: #{err.message}" visit '/' end end - def sneakily_cache_forum(forum_id, note_ids) - # if the main message db doesn't exist, don't bother making a new one - return unless @@msg_store - Thread.new { - # this is a separate thread; we need our own bbs and db handle - with_new_bbs_connection do | bbs | - msg_store = SQLite3::Database.new('messages.db') - sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' + - Array.new(note_ids.length, '?').join(', ') +' ) ;' - already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i} - (note_ids - already_stored).each do | msgnum | - get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) - end - end - } - end - def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i record_last_read(old_id) visit "/enter_forum/#{new_id}" end def enter_forum(id) info "enter_forum #{id}" id = id.to_i background black # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread cache[:post_headers] = forum.post_headers cache[:noteids] = forum.noteids.sort - sneakily_cache_forum(id, cache[:noteids]) cache[:name] = forum.name @@forum_cache[id] = cache visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i background black cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end @mainstack.clear do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline cache[:name] para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] stack :margin => 20, :width => 200 do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end def foruminfo(id) info "foruminfo #{id}" @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo info "first_todo" background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] visit "/enter_forum/#{forum_id}" else - visit "/forums" + visit "/bbs" end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" forum_id = forum_id.to_i background black cache = @@forum_cache[forum_id] stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end def get_message_from_db(db, forum_id, msgnum) sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;" result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end - def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil) - bbs ||=@@bbs - msg_store ||=@@msg_store + def get_message(forum_id, msgnum) msg = {} - post = bbs.jump(forum_id).read(msgnum) + post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id - store_message(msg_store, msg) if msg_store - msg - end - - def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil) - bbs ||=@@bbs - msg_store ||=@@msg_store - msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store - unless msg - msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) - end msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end - Thread.new { - post_ids = @@forum_cache[forum_id][:noteids] - post_index = post_ids.index(msgnum) - remaining = post_ids.length - post_index - 1 - msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) - msg_prev = post_ids[post_index - 1] if post_index > 0 - - msg = get_message_with_caching(forum_id, msgnum) - - action_list = [] + post_ids = @@forum_cache[forum_id][:noteids] + post_index = post_ids.index(msgnum) + remaining = post_ids.length - post_index - 1 + msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) + msg_prev = post_ids[post_index - 1] if post_index > 0 + + action_list = [] + if msg_prev + action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] + end + if msg_next + action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] + end + action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] + action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ] + action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] + action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] + action_list << [ "c", "[c]opy to clipboard", + Proc.new { self.clipboard=@whole_message; + alert( "Copied to clipboard.") } ] + if direction == 'forward' + if msg_next + action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] + else + action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] + end + if msg_prev + action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] + else + action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] + end + elsif direction == 'backward' if msg_prev - action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] + action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] + else + action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next - action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] - end - action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] - action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] - action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] - action_list << [ "c", "[c]opy to clipboard", - Proc.new { self.clipboard=@whole_message; - alert( "Copied to clipboard.") } ] - if direction == 'forward' - if msg_next - action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] - else - action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] - end - if msg_prev - action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] - else - action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] - end - elsif direction == 'backward' - if msg_prev - action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] - else - action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] - end - if msg_next - action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] - else - action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] - end + action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] + else + action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end - action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] + end + action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] - linklist, keypressproc = actions(action_list) - keypress { | key | + linklist, keypressproc = actions(action_list) + keypress { | key | keypressproc.call(key) - } + } +# Thread.new { + msg = get_message(forum_id, msgnum) + body_urls = msg[:body].scan(URLRE) - + @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end - } + # } end - + def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end def new_post(forum_id) background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end end Shoes.app :width => 800
edheil/shoesca
5b3e0cbad29e1ecf9d2287e9e7ba76220a87d712
fix some spots where it wasn't saving first_unread
diff --git a/shoesca.rb b/shoesca.rb index bd4fe62..eb2b564 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,615 +1,617 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' #require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 STACKSTYLE = { :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :login url '/forums', :forums url '/quit', :quit url '/quit_from_forum/(d+)', :quit_from_forum url '/goto/(\d+)', :goto url '/login', :login url '/license', :license url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum url '/leave_forum/(\d+)', :leave_forum url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs, @@msg_store = nil, nil @@forum_cache = {} + @@bbs_cache = {} # @@msg_store = SQLite3::Database.new('messages.db') # @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);"); def license info "license" background black stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def record_last_read(forum_id) forum_id = forum_id.to_i info "record_last_read for #{forum_id}" cached = @@forum_cache[forum_id] if cached info "got cache" info "seeing if #{ cached[:first_unread] } > #{ cached[:server_first_unread] }" if cached[:first_unread] > cached[:server_first_unread] info "yep" forum = @@bbs.jump(forum_id) info "setting first_unread to #{cached[:first_unread]}" forum.first_unread = cached[:first_unread] cached[:server_first_unread] = cached[:first_unread] end end end def quit_from_forum(id) + info "quit_from_forum" record_last_read(id) exit() end def quit + info "quit" exit() end def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @@username = @username_line.text @@password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end - def quit exit() end def leave_forum(id) info "leave forum #{id}" record_last_read(id) visit '/forums' end def forums background black @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', '/quit' ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end end def goto(id) # id is forum to jump *from* id = id.to_i para "marking read, moving on..." Thread.new { @the_forum = @@bbs.jump(id) @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 visit '/first_todo' } end def with_new_bbs_connection begin bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) yield bbs rescue RuntimeError => err debug "error: #{err.message}" visit '/' end end def sneakily_cache_forum(forum_id, note_ids) # if the main message db doesn't exist, don't bother making a new one return unless @@msg_store Thread.new { # this is a separate thread; we need our own bbs and db handle with_new_bbs_connection do | bbs | msg_store = SQLite3::Database.new('messages.db') sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' + Array.new(note_ids.length, '?').join(', ') +' ) ;' already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i} (note_ids - already_stored).each do | msgnum | get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) end end } end def switch_forum(old_id, new_id) old_id, new_id = old_id.to_i, new_id.to_i record_last_read(old_id) visit "/enter_forum/#{new_id}" end def enter_forum(id) info "enter_forum #{id}" id = id.to_i background black # we pull stuff into forum_cache only when we enter a new forum. forum = @@bbs.jump(id) cache = {} first_unread = forum.first_unread.to_i cache[:server_first_unread] = first_unread cache[:first_unread] = first_unread cache[:post_headers] = forum.post_headers cache[:noteids] = forum.noteids.sort sneakily_cache_forum(id, cache[:noteids]) cache[:name] = forum.name @@forum_cache[id] = cache visit "/forum/#{id}" end def forum(id) info "forum #{id}" id = id.to_i background black cache = @@forum_cache[id] unless cache visit "/enter_forum/#{id}" end first_unread = cache[:first_unread] posts = cache[:post_headers] noteids = cache[:noteids] msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end @mainstack.clear do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline cache[:name] para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.reverse.each do | post_id | post = posts[post_id.to_s] stack :margin => 20, :width => 200 do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end end def foruminfo(id) info "foruminfo #{id}" @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo - info "first_todo #{id}" + info "first_todo" background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] -# visit "/first_unread/#{forum_id}" - visit "/forum/#{forum_id}" + visit "/enter_forum/#{forum_id}" else visit "/forums" end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" + forum_id = forum_id.to_i background black cache = @@forum_cache[forum_id] stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end noteids = cache[:noteids] first_unread_msg = cache[:first_unread] first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else - visit "/first_todo" + visit "/leave_forum/#{forum_id}" end end def mark_unread(forum_id,msgnum) @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end def get_message_from_db(db, forum_id, msgnum) sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;" result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil) bbs ||=@@bbs msg_store ||=@@msg_store msg = {} post = bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id store_message(msg_store, msg) if msg_store msg end def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil) bbs ||=@@bbs msg_store ||=@@msg_store msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store unless msg msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) end msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 msg = get_message_with_caching(forum_id, msgnum) action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end if @@forum_cache[forum_id][:first_unread] <= msgnum @@forum_cache[forum_id][:first_unread] = msgnum + 1 end } end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end def new_post(forum_id) background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end end Shoes.app :width => 800
edheil/shoesca
8bc8bc97059e948008cc11c937b25f1fa496d401
get rid of message caching db, make first_unread updates infrequent
diff --git a/shoesca.rb b/shoesca.rb index 261ac4c..bd4fe62 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,569 +1,615 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' -require 'sqlite3' +#require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 STACKSTYLE = { :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :login url '/forums', :forums + url '/quit', :quit + url '/quit_from_forum/(d+)', :quit_from_forum url '/goto/(\d+)', :goto url '/login', :login url '/license', :license + url '/enter_forum/(\d+)', :enter_forum url '/forum/(\d+)', :forum + url '/leave_forum/(\d+)', :leave_forum + url '/switch_forum/(\d+)/(\d+)', :switch_forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply - @@bbs, @msg_store = nil, nil + @@bbs, @@msg_store = nil, nil @@forum_cache = {} - @@msg_store = SQLite3::Database.new('messages.db') - @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);"); +# @@msg_store = SQLite3::Database.new('messages.db') +# @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);"); def license + info "license" background black stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end + + def record_last_read(forum_id) + forum_id = forum_id.to_i + info "record_last_read for #{forum_id}" + cached = @@forum_cache[forum_id] + if cached + info "got cache" + info "seeing if #{ cached[:first_unread] } > #{ cached[:server_first_unread] }" + if cached[:first_unread] > cached[:server_first_unread] + info "yep" + forum = @@bbs.jump(forum_id) + info "setting first_unread to #{cached[:first_unread]}" + forum.first_unread = cached[:first_unread] + cached[:server_first_unread] = cached[:first_unread] + end + end + end + + def quit_from_forum(id) + record_last_read(id) + exit() + end + + def quit + exit() + end + + + def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @@username = @username_line.text @@password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) - keypress do | key | if key == "\n" do_login end end end end + + def quit + exit() + end + + def leave_forum(id) + info "leave forum #{id}" + record_last_read(id) + visit '/forums' + end + def forums background black @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], - [ 'q', '[q]uit', Proc.new { exit() } ] + [ 'q', '[q]uit', '/quit' ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 - para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") + para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}") end end end end end end end end def goto(id) # id is forum to jump *from* id = id.to_i para "marking read, moving on..." Thread.new { @the_forum = @@bbs.jump(id) @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 visit '/first_todo' } end def with_new_bbs_connection begin bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) yield bbs rescue RuntimeError => err debug "error: #{err.message}" visit '/' end end def sneakily_cache_forum(forum_id, note_ids) # if the main message db doesn't exist, don't bother making a new one return unless @@msg_store Thread.new { # this is a separate thread; we need our own bbs and db handle with_new_bbs_connection do | bbs | msg_store = SQLite3::Database.new('messages.db') sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' + Array.new(note_ids.length, '?').join(', ') +' ) ;' already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i} (note_ids - already_stored).each do | msgnum | get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) end end } end + def switch_forum(old_id, new_id) + old_id, new_id = old_id.to_i, new_id.to_i + record_last_read(old_id) + visit "/enter_forum/#{new_id}" + end + + def enter_forum(id) + info "enter_forum #{id}" + id = id.to_i + background black + # we pull stuff into forum_cache only when we enter a new forum. + forum = @@bbs.jump(id) + cache = {} + first_unread = forum.first_unread.to_i + cache[:server_first_unread] = first_unread + cache[:first_unread] = first_unread + cache[:post_headers] = forum.post_headers + cache[:noteids] = forum.noteids.sort + sneakily_cache_forum(id, cache[:noteids]) + cache[:name] = forum.name + @@forum_cache[id] = cache + visit "/forum/#{id}" + end + def forum(id) + info "forum #{id}" id = id.to_i background black - - @mainstack = stack STACKSTYLE do - background blanchedalmond, :curve => 20 - border black, :curve => 20 - para "loading forum #{id}..." + cache = @@forum_cache[id] + unless cache + visit "/enter_forum/#{id}" end - - - Thread.new { - @@forum_cache[id] = {} - @forum = @@bbs.jump(id) - first_unread = @forum.first_unread.to_i - @@forum_cache[id][:first_unread] = first_unread - @posts = @forum.post_headers - noteids = @forum.noteids.sort - @@forum_cache[id][:noteids] = noteids - sneakily_cache_forum(id, noteids) - @@forum_cache[id][:name] = @forum.name - msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } - msgs_read = noteids.select { |msg| msg.to_i < first_unread } - info "got posts" + + first_unread = cache[:first_unread] + posts = cache[:post_headers] + noteids = cache[:noteids] + msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } + msgs_read = noteids.select { |msg| msg.to_i < first_unread } + linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], - [ 'l', 'forum [l]ist', "/forums"], - [ 'f', 'read [f]orward', + [ 'l', 'forum [l]ist', "/leave_forum/#{id}"], + [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], - [ 'q', '[q]uit', Proc.new { exit() } ] + [ 'q', '[q]uit', "/quit_from_forum/#{id}" ] ] ) keypress { | key | keypressproc.call(key) } + @mainstack = stack STACKSTYLE do + background blanchedalmond, :curve => 20 + border black, :curve => 20 + para "loading forum #{id}..." + end - - @mainstack.clear do - background blanchedalmond, :curve => 20 - border black, :curve => 20 - - para *linklist - [ [ "Unread", msgs_unread, ], - [ "Read", msgs_read, ]].each do | pair | - group_name, ordered_ids = *pair - info "adding #{group_name} stack" - stack :margin => 20 do - background white, :curve => 20 - border black, :curve => 20 - caption group_name - flow do - ordered_ids.reverse.each do | post_id | - post = @posts[post_id.to_s] - stack :margin => 20, :width => 200 do - background ivory, :curve => 10 - border black, :curve => 10 - para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") - para post[:subject] - end + @mainstack.clear do + background blanchedalmond, :curve => 20 + border black, :curve => 20 + tagline cache[:name] + para *linklist + [ [ "Unread", msgs_unread, ], + [ "Read", msgs_read, ]].each do | pair | + group_name, ordered_ids = *pair + stack :margin => 20 do + background white, :curve => 20 + border black, :curve => 20 + caption group_name + flow do + ordered_ids.reverse.each do | post_id | + post = posts[post_id.to_s] + stack :margin => 20, :width => 200 do + background ivory, :curve => 10 + border black, :curve => 10 + para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") + para post[:subject] end end end end end - } + end end def foruminfo(id) + info "foruminfo #{id}" @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], - [ "q", "[q]uit", Proc.new { exit()} ] + [ "q", "[q]uit", "/quit_from_forum/#{id}" ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo + info "first_todo #{id}" background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] # visit "/first_unread/#{forum_id}" visit "/forum/#{forum_id}" else visit "/forums" end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" background black + cache = @@forum_cache[forum_id] stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end - Thread.new { - @forum = @@bbs.jump(forum_id) - noteids = @forum.noteids.map { |n| n.to_i }.sort - first_unread_msg = @forum.first_unread.to_i - first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } - if first_unread_found - visit "/message/#{forum_id}/#{first_unread_found}/forward" - else - visit "/first_todo" - end - } - end - - def mark_read(forum_id, msgnum) - first_unread_msg = @@forum_cache[forum_id][:first_unread] - if msgnum.to_i >= first_unread_msg - @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1 - Thread.new { - with_new_bbs_connection { | bbs | bbs.jump(forum_id).first_unread = msgnum.to_i + 1 } - } - end - + noteids = cache[:noteids] + first_unread_msg = cache[:first_unread] + first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } + if first_unread_found + visit "/message/#{forum_id}/#{first_unread_found}/forward" + else + visit "/first_todo" + end end def mark_unread(forum_id,msgnum) @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end - def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end def get_message_from_db(db, forum_id, msgnum) sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;" result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil) bbs ||=@@bbs msg_store ||=@@msg_store msg = {} post = bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id store_message(msg_store, msg) if msg_store msg end def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil) bbs ||=@@bbs msg_store ||=@@msg_store msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store unless msg msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) end msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { - mark_read(forum_id, msgnum) post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 - msg = get_message_with_caching(forum_id, msgnum) - while not msg - info "waiting for message to show up in the cache..." - sleep 1 - msg = get_message_from_db(@@msg_store, forum_id, msgnum) - end action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' if msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_prev action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end elsif direction == 'backward' if msg_prev action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end if msg_next action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] else action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] end end - action_list << [ "q", "[q]uit", Proc.new { exit()} ] + action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end + if @@forum_cache[forum_id][:first_unread] <= msgnum + @@forum_cache[forum_id][:first_unread] = msgnum + 1 + end } end - + def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end def new_post(forum_id) background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end end Shoes.app :width => 800
edheil/shoesca
47be147cf4f184ff3730cfa0633a78d535ad316e
more isca-like "b" and "s" behavior in fora
diff --git a/shoesca.rb b/shoesca.rb index 96198a9..261ac4c 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,553 +1,569 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 STACKSTYLE = { :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :login url '/forums', :forums url '/goto/(\d+)', :goto url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs, @msg_store = nil, nil @@forum_cache = {} @@msg_store = SQLite3::Database.new('messages.db') @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);"); def license background black stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @@username = @username_line.text @@password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def forums background black @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end end def goto(id) # id is forum to jump *from* id = id.to_i para "marking read, moving on..." Thread.new { @the_forum = @@bbs.jump(id) @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 visit '/first_todo' } end def with_new_bbs_connection begin bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) yield bbs rescue RuntimeError => err debug "error: #{err.message}" visit '/' end end def sneakily_cache_forum(forum_id, note_ids) # if the main message db doesn't exist, don't bother making a new one return unless @@msg_store Thread.new { # this is a separate thread; we need our own bbs and db handle with_new_bbs_connection do | bbs | msg_store = SQLite3::Database.new('messages.db') sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' + Array.new(note_ids.length, '?').join(', ') +' ) ;' already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i} (note_ids - already_stored).each do | msgnum | get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) end end } end def forum(id) id = id.to_i background black @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end Thread.new { @@forum_cache[id] = {} @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i @@forum_cache[id][:first_unread] = first_unread @posts = @forum.post_headers noteids = @forum.noteids.sort @@forum_cache[id][:noteids] = noteids sneakily_cache_forum(id, noteids) @@forum_cache[id][:name] = @forum.name msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/forums"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.reverse.each do | post_id | post = @posts[post_id.to_s] stack :margin => 20, :width => 200 do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end } end def foruminfo(id) @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] # visit "/first_unread/#{forum_id}" visit "/forum/#{forum_id}" else visit "/forums" end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end Thread.new { @forum = @@bbs.jump(forum_id) noteids = @forum.noteids.map { |n| n.to_i }.sort first_unread_msg = @forum.first_unread.to_i first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/first_todo" end } end def mark_read(forum_id, msgnum) first_unread_msg = @@forum_cache[forum_id][:first_unread] if msgnum.to_i >= first_unread_msg @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1 Thread.new { with_new_bbs_connection { | bbs | bbs.jump(forum_id).first_unread = msgnum.to_i + 1 } } end end def mark_unread(forum_id,msgnum) @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end def get_message_from_db(db, forum_id, msgnum) sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;" result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil) bbs ||=@@bbs msg_store ||=@@msg_store msg = {} post = bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id store_message(msg_store, msg) if msg_store msg end def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil) bbs ||=@@bbs msg_store ||=@@msg_store msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store unless msg msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) end msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { mark_read(forum_id, msgnum) post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 msg = get_message_with_caching(forum_id, msgnum) while not msg info "waiting for message to show up in the cache..." sleep 1 msg = get_message_from_db(@@msg_store, forum_id, msgnum) end action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] - if direction == 'forward' and msg_next - action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] - elsif direction == 'backward' and msg_next - action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] - else - action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] + if direction == 'forward' + if msg_next + action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] + else + action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] + end + if msg_prev + action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ] + else + action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] + end + elsif direction == 'backward' + if msg_prev + action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] + else + action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] + end + if msg_next + action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ] + else + action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ] + end end action_list << [ "q", "[q]uit", Proc.new { exit()} ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end } end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") - @post_box = edit_box quote, :width => 500, :height => 300 + @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end def new_post(forum_id) background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") - @post_box = edit_box :width => 500, :height => 300 + @post_box = edit_box :width => 500, :height => 300, :margin => 20 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end end Shoes.app :width => 800
edheil/shoesca
733a12c36113892b824a83080f7e34e4934ceecc
smarter message pre-caching (less db calls)
diff --git a/shoesca.rb b/shoesca.rb index 4d4e983..96198a9 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,542 +1,553 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving PORT = 6145 STACKSTYLE = { :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :login url '/forums', :forums url '/goto/(\d+)', :goto url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs, @msg_store = nil, nil @@forum_cache = {} @@msg_store = SQLite3::Database.new('messages.db') - @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);"); + @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);"); def license background black stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @@username = @username_line.text @@password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def forums background black @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end end def goto(id) # id is forum to jump *from* id = id.to_i para "marking read, moving on..." Thread.new { @the_forum = @@bbs.jump(id) @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 visit '/first_todo' } end def with_new_bbs_connection begin bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, :host => HOST, :port => PORT ) yield bbs rescue RuntimeError => err debug "error: #{err.message}" visit '/' end end def sneakily_cache_forum(forum_id, note_ids) # if the main message db doesn't exist, don't bother making a new one return unless @@msg_store - Thread.new do + Thread.new { # this is a separate thread; we need our own bbs and db handle with_new_bbs_connection do | bbs | msg_store = SQLite3::Database.new('messages.db') - note_ids.each do | msgnum | - get_message_with_caching(forum_id, msgnum, bbs, msg_store) + sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' + + Array.new(note_ids.length, '?').join(', ') +' ) ;' + already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i} + (note_ids - already_stored).each do | msgnum | + get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) end end - end + } end def forum(id) id = id.to_i background black @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end Thread.new { @@forum_cache[id] = {} @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i @@forum_cache[id][:first_unread] = first_unread @posts = @forum.post_headers noteids = @forum.noteids.sort @@forum_cache[id][:noteids] = noteids sneakily_cache_forum(id, noteids) @@forum_cache[id][:name] = @forum.name msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" - linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], + linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/forums"], - [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], - [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], + [ 'f', 'read [f]orward', + "/message/#{id}/#{noteids.first}/forward"], + [ 'b', 'read [b]ackward', + "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do - info "adding background" background blanchedalmond, :curve => 20 border black, :curve => 20 + para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.reverse.each do | post_id | post = @posts[post_id.to_s] stack :margin => 20, :width => 200 do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end } end def foruminfo(id) @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], - [ 'p', '[p]ost', "/new_post/#{id}"], + [ 'p', '[e]nter msg', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] # visit "/first_unread/#{forum_id}" visit "/forum/#{forum_id}" else visit "/forums" end end def first_unread(forum_id) info "first_unread for forum_id #{forum_id}" background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end Thread.new { @forum = @@bbs.jump(forum_id) noteids = @forum.noteids.map { |n| n.to_i }.sort first_unread_msg = @forum.first_unread.to_i first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/first_todo" end } end def mark_read(forum_id, msgnum) first_unread_msg = @@forum_cache[forum_id][:first_unread] if msgnum.to_i >= first_unread_msg @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1 Thread.new { with_new_bbs_connection { | bbs | bbs.jump(forum_id).first_unread = msgnum.to_i + 1 } } end end def mark_unread(forum_id,msgnum) @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end - def get_message(db, forum_id, msgnum) - sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?"; + def get_message_from_db(db, forum_id, msgnum) + sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;" result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end + def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil) + bbs ||=@@bbs + msg_store ||=@@msg_store + msg = {} + post = bbs.jump(forum_id).read(msgnum) + [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) } + msg[:message_id] = msgnum + msg[:forum_id] = forum_id + store_message(msg_store, msg) if msg_store + msg + end + def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil) bbs ||=@@bbs msg_store ||=@@msg_store - msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store + msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store unless msg - debug "getting message #{msgnum} in #{forum_id} from bbs" - msg = {} - @post = bbs.jump(forum_id).read(msgnum) - [:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) } - msg[:message_id] = msgnum - msg[:forum_id] = forum_id - store_message(msg_store, msg) if msg_store + msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store) end msg end def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i background black stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { mark_read(forum_id, msgnum) post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 msg = get_message_with_caching(forum_id, msgnum) while not msg info "waiting for message to show up in the cache..." sleep 1 - msg = get_message(@@msg_store, forum_id, msgnum) + msg = get_message_from_db(@@msg_store, forum_id, msgnum) end action_list = [] if msg_prev action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] end if msg_next action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] end action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] action_list << [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ] if direction == 'forward' and msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] elsif direction == 'backward' and msg_next action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] else action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] end action_list << [ "q", "[q]uit", Proc.new { exit()} ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end } end def new_reply(forum_id, msgnum) @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end def new_post(forum_id) background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end end Shoes.app :width => 800
edheil/shoesca
fb49415b39ec138ed401d1f973a68634e02ba4f7
Spawns little threads with their own DB and BBS connection for utility tasks
diff --git a/shoesca.rb b/shoesca.rb index 2508974..4d4e983 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,506 +1,542 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof -# STACKSTYLE = { :width => 650, :margin => 20 } + HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving + PORT = 6145 STACKSTYLE = { :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') - url '/', :main + url '/', :login url '/forums', :forums url '/goto/(\d+)', :goto url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread - url '/message/(\d+)/(\d+)', :message + url '/message/(\d+)/(\d+)/(.*)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs, @msg_store = nil, nil @@forum_cache = {} @@msg_store = SQLite3::Database.new('messages.db') @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);"); def license background black stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login - @username = @username_line.text - @password = @password_line.text + @@username = @username_line.text + @@password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin - @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, - :host => '64.198.88.46', # bbs.iscabbs.com was not resolving - :port => 6145 + @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, + :host => HOST, + :port => PORT ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end - def main - if @@bbs - visit '/forums' - else - visit '/login' - end - end - def forums - visit '/login' unless @@bbs background black @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end end def goto(id) # id is forum to jump *from* id = id.to_i para "marking read, moving on..." Thread.new { @the_forum = @@bbs.jump(id) @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 visit '/first_todo' } end + def with_new_bbs_connection + begin + bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password, + :host => HOST, + :port => PORT + ) + yield bbs + rescue RuntimeError => err + debug "error: #{err.message}" + visit '/' + end + end + + + def sneakily_cache_forum(forum_id, note_ids) + # if the main message db doesn't exist, don't bother making a new one + return unless @@msg_store + Thread.new do + # this is a separate thread; we need our own bbs and db handle + with_new_bbs_connection do | bbs | + msg_store = SQLite3::Database.new('messages.db') + note_ids.each do | msgnum | + get_message_with_caching(forum_id, msgnum, bbs, msg_store) + end + end + end + end + def forum(id) - visit '/login' unless @@bbs id = id.to_i background black @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end + Thread.new { @@forum_cache[id] = {} @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i @@forum_cache[id][:first_unread] = first_unread @posts = @forum.post_headers noteids = @forum.noteids.sort @@forum_cache[id][:noteids] = noteids + sneakily_cache_forum(id, noteids) @@forum_cache[id][:name] = @forum.name msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/forums"], - [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}"], - [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}"], + [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"], + [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"], [ 'g', '[g]oto next forum with unread messages', "/goto/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do info "adding background" background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do - ordered_ids.each do | post_id | + ordered_ids.reverse.each do | post_id | post = @posts[post_id.to_s] stack :margin => 20, :width => 200 do background ivory, :curve => 10 border black, :curve => 10 - para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") + para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward") para post[:subject] end end end end end end } end def foruminfo(id) - visit '/login' unless @@bbs @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] # visit "/first_unread/#{forum_id}" visit "/forum/#{forum_id}" else visit "/forums" end end def first_unread(forum_id) - visit '/login' unless @@bbs info "first_unread for forum_id #{forum_id}" background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end Thread.new { @forum = @@bbs.jump(forum_id) noteids = @forum.noteids.map { |n| n.to_i }.sort first_unread_msg = @forum.first_unread.to_i first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found - visit "/message/#{forum_id}/#{first_unread_found}" + visit "/message/#{forum_id}/#{first_unread_found}/forward" else visit "/first_todo" end } end + def mark_read(forum_id, msgnum) + first_unread_msg = @@forum_cache[forum_id][:first_unread] + if msgnum.to_i >= first_unread_msg + @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1 + Thread.new { + with_new_bbs_connection { | bbs | bbs.jump(forum_id).first_unread = msgnum.to_i + 1 } + } + end + + end + def mark_unread(forum_id,msgnum) - visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end def get_message(db, forum_id, msgnum) sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?"; result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end - def get_message_with_caching(forum_id, msgnum) + def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil) + bbs ||=@@bbs + msg_store ||=@@msg_store msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store unless msg + debug "getting message #{msgnum} in #{forum_id} from bbs" msg = {} - @post = @@bbs.jump(forum_id).read(msgnum) + @post = bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id - store_message(@@msg_store, msg) if @@msg_store + store_message(msg_store, msg) if msg_store end msg end - def message(forum_id,msgnum) + def message(forum_id,msgnum, direction) forum_id=forum_id.to_i msgnum=msgnum.to_i - visit '/login' unless @@bbs background black stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { - first_unread_msg = @@forum_cache[forum_id][:first_unread] - if msgnum.to_i >= first_unread_msg - @messagestack.append { para "marking it read..." } - @forum = @@bbs.jump(forum_id) - @forum.first_unread = msgnum.to_i + 1 - @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1 - end + mark_read(forum_id, msgnum) post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 + msg = get_message_with_caching(forum_id, msgnum) while not msg info "waiting for message to show up in the cache..." sleep 1 msg = get_message(@@msg_store, forum_id, msgnum) end - - action_list = - if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + - if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + - [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], - [ "s" , "[s]top reading", "/forum/#{forum_id}" ], - [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], - [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], - [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], - [ "q", "[q]uit", Proc.new { exit()} ] ] + + action_list = [] + if msg_prev + action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"] + end + if msg_next + action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ] + end + action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ] + action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ] + action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ] + action_list << [ "c", "[c]opy to clipboard", + Proc.new { self.clipboard=@whole_message; + alert( "Copied to clipboard.") } ] + if direction == 'forward' and msg_next + action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ] + elsif direction == 'backward' and msg_next + action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ] + else + action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ] + end + action_list << [ "q", "[q]uit", Proc.new { exit()} ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end } end def new_reply(forum_id, msgnum) - visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" - para link("back", :click => "/message/#{forum_id}/#{msgnum}") + para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end def new_post(forum_id) - visit '/login' unless @@bbs background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/forum/#{forum_id}"); end end end end Shoes.app :width => 800
edheil/shoesca
303ce0179a9ba6c036bf5aafe597ce7c9e560d1f
don't immediately visit the new post you just posted. that marks remaining messages read!
diff --git a/shoesca.rb b/shoesca.rb index 5f2054e..2508974 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,506 +1,506 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof # STACKSTYLE = { :width => 650, :margin => 20 } STACKSTYLE = { :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :main url '/forums', :forums url '/goto/(\d+)', :goto url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs, @msg_store = nil, nil @@forum_cache = {} @@msg_store = SQLite3::Database.new('messages.db') @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);"); def license background black stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs background black @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | id | data = forums[id] stack :width => 200, :margin => 20 do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end end def goto(id) # id is forum to jump *from* id = id.to_i para "marking read, moving on..." Thread.new { @the_forum = @@bbs.jump(id) @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 visit '/first_todo' } end def forum(id) visit '/login' unless @@bbs id = id.to_i background black @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end Thread.new { @@forum_cache[id] = {} @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i @@forum_cache[id][:first_unread] = first_unread @posts = @forum.post_headers noteids = @forum.noteids.sort @@forum_cache[id][:noteids] = noteids @@forum_cache[id][:name] = @forum.name msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/forums"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}"], [ 'g', '[g]oto next forum with unread messages', "/goto/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do info "adding background" background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name flow do ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack :margin => 20, :width => 200 do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end end } end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] # visit "/first_unread/#{forum_id}" visit "/forum/#{forum_id}" else visit "/forums" end end def first_unread(forum_id) visit '/login' unless @@bbs info "first_unread for forum_id #{forum_id}" background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end Thread.new { @forum = @@bbs.jump(forum_id) noteids = @forum.noteids.map { |n| n.to_i }.sort first_unread_msg = @forum.first_unread.to_i first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}" else visit "/first_todo" end } end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end def get_message(db, forum_id, msgnum) sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?"; result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end def get_message_with_caching(forum_id, msgnum) msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store unless msg msg = {} @post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id store_message(@@msg_store, msg) if @@msg_store end msg end def message(forum_id,msgnum) forum_id=forum_id.to_i msgnum=msgnum.to_i visit '/login' unless @@bbs background black stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { first_unread_msg = @@forum_cache[forum_id][:first_unread] if msgnum.to_i >= first_unread_msg @messagestack.append { para "marking it read..." } @forum = @@bbs.jump(forum_id) @forum.first_unread = msgnum.to_i + 1 @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1 end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 msg = get_message_with_caching(forum_id, msgnum) while not msg info "waiting for message to show up in the cache..." sleep 1 msg = get_message(@@msg_store, forum_id, msgnum) end action_list = if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], [ "s" , "[s]top reading", "/forum/#{forum_id}" ], [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end } end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) - visit("/message/#{forum_id}/#{new_post.id}") + visit("/forum/#{forum_id}"); end end end def new_post(forum_id) visit '/login' unless @@bbs background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) - visit("/message/#{forum_id}/#{new_post.id}") + visit("/forum/#{forum_id}"); end end end end Shoes.app :width => 800
edheil/shoesca
3471d7222415a421729e2461da8a2f60b1ab27de
black background, thin messages and forums to fit more on screen, fix 'remaining' off by one
diff --git a/shoesca.rb b/shoesca.rb index e754e0a..5f2054e 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,490 +1,506 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof - STACKSTYLE = { :width => 650, :margin => 20 } +# STACKSTYLE = { :width => 650, :margin => 20 } + STACKSTYLE = { :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :main url '/forums', :forums url '/goto/(\d+)', :goto url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs, @msg_store = nil, nil @@forum_cache = {} @@msg_store = SQLite3::Database.new('messages.db') @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);"); def license + background black stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login + background black @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs + background black @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name - ordered_ids.each do | id | - data = forums[id] - stack STACKSTYLE do - if data[:todo] - background ivory, :curve => 10 - elsif data[:joined] - background lightgrey, :curve => 10 - else - background darkslateblue, :curve => 10 + flow do + ordered_ids.each do | id | + data = forums[id] + stack :width => 200, :margin => 20 do + if data[:todo] + background ivory, :curve => 10 + elsif data[:joined] + background lightgrey, :curve => 10 + else + background darkslateblue, :curve => 10 + end + border black, :curve => 10 + para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end - border black, :curve => 10 - para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end def goto(id) # id is forum to jump *from* id = id.to_i para "marking read, moving on..." Thread.new { @the_forum = @@bbs.jump(id) @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 visit '/first_todo' } end def forum(id) visit '/login' unless @@bbs id = id.to_i + background black @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end Thread.new { @@forum_cache[id] = {} @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i @@forum_cache[id][:first_unread] = first_unread @posts = @forum.post_headers noteids = @forum.noteids.sort @@forum_cache[id][:noteids] = noteids @@forum_cache[id][:name] = @forum.name msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'l', 'forum [l]ist', "/forums"], [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}"], [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}"], [ 'g', '[g]oto next forum with unread messages', "/goto/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do info "adding background" background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" - stack STACKSTYLE do + stack :margin => 20 do background white, :curve => 20 border black, :curve => 20 caption group_name - ordered_ids.each do | post_id | - post = @posts[post_id.to_s] - stack STACKSTYLE do - background ivory, :curve => 10 - border black, :curve => 10 - para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") - para post[:subject] + flow do + ordered_ids.each do | post_id | + post = @posts[post_id.to_s] + stack :margin => 20, :width => 200 do + background ivory, :curve => 10 + border black, :curve => 10 + para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") + para post[:subject] + end end end end end end } end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) + background black linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo + background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] # visit "/first_unread/#{forum_id}" visit "/forum/#{forum_id}" else visit "/forums" end end def first_unread(forum_id) visit '/login' unless @@bbs info "first_unread for forum_id #{forum_id}" + background black stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end Thread.new { @forum = @@bbs.jump(forum_id) noteids = @forum.noteids.map { |n| n.to_i }.sort first_unread_msg = @forum.first_unread.to_i first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}" else visit "/first_todo" end } end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end def get_message(db, forum_id, msgnum) sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?"; result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end def get_message_with_caching(forum_id, msgnum) msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store unless msg msg = {} @post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id store_message(@@msg_store, msg) if @@msg_store end msg end def message(forum_id,msgnum) forum_id=forum_id.to_i msgnum=msgnum.to_i visit '/login' unless @@bbs + background black stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { first_unread_msg = @@forum_cache[forum_id][:first_unread] if msgnum.to_i >= first_unread_msg @messagestack.append { para "marking it read..." } @forum = @@bbs.jump(forum_id) @forum.first_unread = msgnum.to_i + 1 + @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1 end post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) - remaining = post_ids.length - post_index + remaining = post_ids.length - post_index - 1 msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 msg = get_message_with_caching(forum_id, msgnum) while not msg info "waiting for message to show up in the cache..." sleep 1 msg = get_message(@@msg_store, forum_id, msgnum) end action_list = if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], [ "s" , "[s]top reading", "/forum/#{forum_id}" ], [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end } end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" + background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs + background black stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
076fe24cde2d46d49a917a20d8460f56cf3f9a1a
remove reference to packaged versions
diff --git a/README.txt b/README.txt index e35887b..b5ce5cf 100644 --- a/README.txt +++ b/README.txt @@ -1,26 +1,21 @@ Shoesca (until I think of a better name). Shoesca is a client for the ancient telnet-based ISCA BBS telnet://bbs.iscabbs.com/ It utilizes Wade Minter's library for accessing the bbs through the newer, non-telnet-based 'raccdoc' interface. http://github.com/minter/raccdoc/tree/master To use it you need a copy of Shoes ( http://shoooes.net/ ). Fire up Shoes, and choose "Open an app" and open the shoesca.rb file. You'll be presented with a login screen. The app will save your login credentials in a file called bbsconfig.yaml, in the same directory as the shoesca.rb file. The first time you run the app, it will download a copy of the raccdoc library; subsequent runs, it will use the copy it downloaded the first time. -Packaged, executable versions (.exe, .dmg, and .run) are -available in the packages directory; however, they may be -buggy (the .exe in particular pops up a bogus error message -about SSLEAY32.dll). Downloading shoes from http//shoooes.net -is preferable, esp. on Windows.
edheil/shoesca
99e292680f5fb9469ebe3f30921481cf512d95f4
cache forum data for faster reading
diff --git a/shoesca.rb b/shoesca.rb index 5807390..e754e0a 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,474 +1,490 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof STACKSTYLE = { :width => 650, :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :main url '/forums', :forums url '/goto/(\d+)', :goto url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs, @msg_store = nil, nil - + @@forum_cache = {} @@msg_store = SQLite3::Database.new('messages.db') @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);"); def license stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | id | data = forums[id] stack STACKSTYLE do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end def goto(id) # id is forum to jump *from* id = id.to_i para "marking read, moving on..." Thread.new { @the_forum = @@bbs.jump(id) @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 visit '/first_todo' } end def forum(id) visit '/login' unless @@bbs id = id.to_i - linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], - [ 'i', '[i]nfo', "/foruminfo/#{id}"], - [ 'b', '[b]ack to forum list', "/forums"], - [ 'g', '[g]oto next forum with unread messages', - "/goto/#{id}"], - [ ' ', '[ ]first unread', "/first_unread/#{id}"], - [ 'q', '[q]uit', Proc.new { exit() } ] - ] ) - - keypress { | key | keypressproc.call(key) } @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end Thread.new { + @@forum_cache[id] = {} @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i + @@forum_cache[id][:first_unread] = first_unread @posts = @forum.post_headers noteids = @forum.noteids.sort + @@forum_cache[id][:noteids] = noteids + @@forum_cache[id][:name] = @forum.name msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" + linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], + [ 'i', '[i]nfo', "/foruminfo/#{id}"], + [ 'l', 'forum [l]ist', "/forums"], + [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}"], + [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}"], + [ 'g', '[g]oto next forum with unread messages', + "/goto/#{id}"], + [ ' ', '[ ]first unread', "/first_unread/#{id}"], + [ 'q', '[q]uit', Proc.new { exit() } ] + ] ) + + keypress { | key | keypressproc.call(key) } + + @mainstack.clear do info "adding background" background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack STACKSTYLE do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end } end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] - visit "/first_unread/#{forum_id}" +# visit "/first_unread/#{forum_id}" + visit "/forum/#{forum_id}" else visit "/forums" end end def first_unread(forum_id) visit '/login' unless @@bbs info "first_unread for forum_id #{forum_id}" stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end Thread.new { @forum = @@bbs.jump(forum_id) noteids = @forum.noteids.map { |n| n.to_i }.sort first_unread_msg = @forum.first_unread.to_i first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}" else visit "/first_todo" end - } + } end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def store_message(db, msghash) sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) end def get_message(db, forum_id, msgnum) sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?"; result = db.get_first_row(sql, forum_id, msgnum) return nil unless result msg = {} [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | msg[k] = result[i] end return msg end def get_message_with_caching(forum_id, msgnum) msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store unless msg msg = {} @post = @@bbs.jump(forum_id).read(msgnum) [:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) } msg[:message_id] = msgnum msg[:forum_id] = forum_id store_message(@@msg_store, msg) if @@msg_store end msg end def message(forum_id,msgnum) + forum_id=forum_id.to_i msgnum=msgnum.to_i visit '/login' unless @@bbs stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { - @forum = @@bbs.jump(forum_id) - first_unread_msg = @forum.first_unread.to_i + first_unread_msg = @@forum_cache[forum_id][:first_unread] if msgnum.to_i >= first_unread_msg + @messagestack.append { para "marking it read..." } + @forum = @@bbs.jump(forum_id) @forum.first_unread = msgnum.to_i + 1 end - post_ids = @forum.noteids.map{ |n| n.to_i }.sort + post_ids = @@forum_cache[forum_id][:noteids] post_index = post_ids.index(msgnum) remaining = post_ids.length - post_index msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_prev = post_ids[post_index - 1] if post_index > 0 msg = get_message_with_caching(forum_id, msgnum) + while not msg + info "waiting for message to show up in the cache..." + sleep 1 + msg = get_message(@@msg_store, forum_id, msgnum) + end action_list = if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], [ "s" , "[s]top reading", "/forum/#{forum_id}" ], [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + "#{msg[:body]}" + - "[#{@forum.name}> msg #{msgnum} (#{ remaining } remaining)]") + "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end } end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
701ec61721c2bb554fa6d4f55634aab1e43d40d9
message caching with sqlite
diff --git a/shoesca.rb b/shoesca.rb index 5ccf125..5807390 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,432 +1,474 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' +require 'sqlite3' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof STACKSTYLE = { :width => 650, :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :main url '/forums', :forums + url '/goto/(\d+)', :goto url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply - @@bbs = nil - + @@bbs, @msg_store = nil, nil + + @@msg_store = SQLite3::Database.new('messages.db') + @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);"); def license stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end - end + end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } - # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | id | data = forums[id] stack STACKSTYLE do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end + + def goto(id) + # id is forum to jump *from* + id = id.to_i + para "marking read, moving on..." + Thread.new { + @the_forum = @@bbs.jump(id) + @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1 + visit '/first_todo' + } + end + def forum(id) visit '/login' unless @@bbs + id = id.to_i linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'b', '[b]ack to forum list', "/forums"], + [ 'g', '[g]oto next forum with unread messages', + "/goto/#{id}"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end Thread.new { @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i @posts = @forum.post_headers noteids = @forum.noteids.sort msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" @mainstack.clear do info "adding background" background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack STACKSTYLE do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end } end - + def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] - info "found todo forum: #{forum_id}" visit "/first_unread/#{forum_id}" else - info "found no todo forums: visiting forums" visit "/forums" end end def first_unread(forum_id) visit '/login' unless @@bbs info "first_unread for forum_id #{forum_id}" stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end + Thread.new { - if forum_id.length == 0 # need to find it - info "zero length forum id, looking for first unread forum" - end - info "jumping to #{forum_id}" @forum = @@bbs.jump(forum_id) - info "finding first unread" + noteids = @forum.noteids.map { |n| n.to_i }.sort first_unread_msg = @forum.first_unread.to_i - info "seeing if it exists" - first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } + first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg } if first_unread_found - info "visiting it" visit "/message/#{forum_id}/#{first_unread_found}" else - info "visiting first todo" visit "/first_todo" end } end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end + def store_message(db, msghash) + sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)" + db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority]) + end + + def get_message(db, forum_id, msgnum) + sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?"; + result = db.get_first_row(sql, forum_id, msgnum) + return nil unless result + msg = {} + [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i | + msg[k] = result[i] + end + return msg + end + + def get_message_with_caching(forum_id, msgnum) + msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store + unless msg + msg = {} + @post = @@bbs.jump(forum_id).read(msgnum) + [:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) } + msg[:message_id] = msgnum + msg[:forum_id] = forum_id + store_message(@@msg_store, msg) if @@msg_store + end + msg + end + def message(forum_id,msgnum) + msgnum=msgnum.to_i visit '/login' unless @@bbs stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i >= first_unread_msg @forum.first_unread = msgnum.to_i + 1 end - post_ids = @forum.post_headers.keys.sort.reverse + post_ids = @forum.noteids.map{ |n| n.to_i }.sort post_index = post_ids.index(msgnum) - msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) - msg_next = post_ids[post_index - 1] if post_index > 0 - @post = @forum.read(msgnum) + remaining = post_ids.length - post_index + msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1) + msg_prev = post_ids[post_index - 1] if post_index > 0 + + msg = get_message_with_caching(forum_id, msgnum) action_list = if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], - [ "b" , "[b]ack to forum", "/forum/#{forum_id}" ], + [ "s" , "[s]top reading", "/forum/#{forum_id}" ], [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } - the_body = @post.body - body_urls = the_body.scan(URLRE) + body_urls = msg[:body].scan(URLRE) @messagestack.clear do para *linklist - @whole_message = "#{@post.date} from #{@post.author}\n#{the_body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" + @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" + + "#{msg[:body]}" + + "[#{@forum.name}> msg #{msgnum} (#{ remaining } remaining)]") stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end } - end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
f53c9083c0d3250be753f75d1004c0874e3ef6a4
typo fix in keypress actions
diff --git a/shoesca.rb b/shoesca.rb index 7b336b2..5ccf125 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,432 +1,432 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof STACKSTYLE = { :width => 650, :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :main url '/forums', :forums url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def license stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | id | data = forums[id] stack STACKSTYLE do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end def forum(id) visit '/login' unless @@bbs linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], - [ 'i', '[b]ack to forum list', "/forums"], + [ 'b', '[b]ack to forum list', "/forums"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end Thread.new { @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i @posts = @forum.post_headers noteids = @forum.noteids.sort msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" @mainstack.clear do info "adding background" background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack STACKSTYLE do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end } end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist @info = @forum.forum_information the_body = @info[:body] body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" body_urls.each do | a_url | para link(a_url, :click => a_url) end end end end def first_todo stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] info "found todo forum: #{forum_id}" visit "/first_unread/#{forum_id}" else info "found no todo forums: visiting forums" visit "/forums" end end def first_unread(forum_id) visit '/login' unless @@bbs info "first_unread for forum_id #{forum_id}" stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end Thread.new { if forum_id.length == 0 # need to find it info "zero length forum id, looking for first unread forum" end info "jumping to #{forum_id}" @forum = @@bbs.jump(forum_id) info "finding first unread" first_unread_msg = @forum.first_unread.to_i info "seeing if it exists" first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } if first_unread_found info "visiting it" visit "/message/#{forum_id}/#{first_unread_found}" else info "visiting first todo" visit "/first_todo" end } end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def message(forum_id,msgnum) visit '/login' unless @@bbs stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i >= first_unread_msg @forum.first_unread = msgnum.to_i + 1 end post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 @post = @forum.read(msgnum) action_list = if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], [ "b" , "[b]ack to forum", "/forum/#{forum_id}" ], [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } the_body = @post.body body_urls = the_body.scan(URLRE) @messagestack.clear do para *linklist @whole_message = "#{@post.date} from #{@post.author}\n#{the_body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end } end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
7dbd5a5ad490891988a117174fb4c90cd9938241
remove top stuff from forum_info
diff --git a/shoesca.rb b/shoesca.rb index c83447c..7b336b2 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,428 +1,432 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof STACKSTYLE = { :width => 650, :margin => 20 } URLRE = Regexp.new('https?://[^ \n\)]+') url '/', :main url '/forums', :forums url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def license stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | id | data = forums[id] stack STACKSTYLE do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end def forum(id) visit '/login' unless @@bbs linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'i', '[b]ack to forum list', "/forums"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end Thread.new { @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i @posts = @forum.post_headers noteids = @forum.noteids.sort msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" @mainstack.clear do info "adding background" background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack STACKSTYLE do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end } end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) - + linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], + [ "q", "[q]uit", Proc.new { exit()} ] ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 - tagline( link(link("Forums", :click => "/forums")), " / ", - link( "#{@forum.name}>", :click => "/forum/#{id}") ) para *linklist @info = @forum.forum_information + the_body = @info[:body] + body_urls = the_body.scan(URLRE) stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" + body_urls.each do | a_url | + para link(a_url, :click => a_url) + end end end end - + def first_todo stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] info "found todo forum: #{forum_id}" visit "/first_unread/#{forum_id}" else info "found no todo forums: visiting forums" visit "/forums" end end def first_unread(forum_id) visit '/login' unless @@bbs info "first_unread for forum_id #{forum_id}" stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end Thread.new { if forum_id.length == 0 # need to find it info "zero length forum id, looking for first unread forum" end info "jumping to #{forum_id}" @forum = @@bbs.jump(forum_id) info "finding first unread" first_unread_msg = @forum.first_unread.to_i info "seeing if it exists" first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } if first_unread_found info "visiting it" visit "/message/#{forum_id}/#{first_unread_found}" else info "visiting first todo" visit "/first_todo" end } end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def message(forum_id,msgnum) visit '/login' unless @@bbs stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i >= first_unread_msg @forum.first_unread = msgnum.to_i + 1 end post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 @post = @forum.read(msgnum) action_list = if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], [ "b" , "[b]ack to forum", "/forum/#{forum_id}" ], [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } the_body = @post.body body_urls = the_body.scan(URLRE) @messagestack.clear do para *linklist @whole_message = "#{@post.date} from #{@post.author}\n#{the_body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message body_urls.each do | a_url | para link(a_url, :click => a_url) end end end } end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
430fd13a2ed223b2a4d2b642807eaa1a4d74149b
detect urls in message body
diff --git a/shoesca.rb b/shoesca.rb index 17dc8f9..c83447c 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,421 +1,428 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof STACKSTYLE = { :width => 650, :margin => 20 } - + URLRE = Regexp.new('https?://[^ \n\)]+') + url '/', :main url '/forums', :forums url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def license stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text @mainstack.append do para "logging in..." end Thread.new do begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para "loading forums..." end Thread.new do forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack.clear do background aliceblue, :curve => 20 border black, :curve => 20 para *linklist # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | id | data = forums[id] stack STACKSTYLE do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end end def forum(id) visit '/login' unless @@bbs linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], [ 'i', '[i]nfo', "/foruminfo/#{id}"], [ 'i', '[b]ack to forum list', "/forums"], [ ' ', '[ ]first unread', "/first_unread/#{id}"], [ 'q', '[q]uit', Proc.new { exit() } ] ] ) keypress { | key | keypressproc.call(key) } @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "loading forum #{id}..." end Thread.new { @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i @posts = @forum.post_headers noteids = @forum.noteids.sort msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } info "got posts" @mainstack.clear do info "adding background" background blanchedalmond, :curve => 20 border black, :curve => 20 para *linklist [ [ "Unread", msgs_unread, ], [ "Read", msgs_read, ]].each do | pair | group_name, ordered_ids = *pair info "adding #{group_name} stack" stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack STACKSTYLE do background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end } end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para *linklist @info = @forum.forum_information stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end def first_todo stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first forum with unread messages..." end forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort if forums_todo.length > 0 forum_id = forums_todo[0] info "found todo forum: #{forum_id}" visit "/first_unread/#{forum_id}" else info "found no todo forums: visiting forums" visit "/forums" end end def first_unread(forum_id) visit '/login' unless @@bbs info "first_unread for forum_id #{forum_id}" stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 para "finding first unread message in forum #{forum_id}..." end Thread.new { if forum_id.length == 0 # need to find it info "zero length forum id, looking for first unread forum" end info "jumping to #{forum_id}" @forum = @@bbs.jump(forum_id) info "finding first unread" first_unread_msg = @forum.first_unread.to_i info "seeing if it exists" first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } if first_unread_found info "visiting it" visit "/message/#{forum_id}/#{first_unread_found}" else info "visiting first todo" visit "/first_todo" end } end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] if action.respond_to? :call action.call else visit action end end end return linklist, keypressproc end def message(forum_id,msgnum) visit '/login' unless @@bbs stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end Thread.new { @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i >= first_unread_msg @forum.first_unread = msgnum.to_i + 1 end post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 @post = @forum.read(msgnum) action_list = if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], [ "b" , "[b]ack to forum", "/forum/#{forum_id}" ], [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } + the_body = @post.body + body_urls = the_body.scan(URLRE) + @messagestack.clear do para *linklist - @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" + @whole_message = "#{@post.date} from #{@post.author}\n#{the_body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message - end + body_urls.each do | a_url | + para link(a_url, :click => a_url) + end + end end } end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
57156c5404ddaf1299b39a3bd5a658f096e40d24
finish using threads to load data, so feedback can be provided immediately
diff --git a/shoesca.rb b/shoesca.rb index 7bc74ef..17dc8f9 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,393 +1,421 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof STACKSTYLE = { :width => 650, :margin => 20 } url '/', :main url '/forums', :forums url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo + url '/first_todo', :first_todo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def license stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text - begin - @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, - :host => '64.198.88.46', # bbs.iscabbs.com was not resolving - :port => 6145 - ) - rescue RuntimeError => err - debug "error: #{err.message}" - @@bbs = nil - @mainstack.append do - para err.message - end + @mainstack.append do + para "logging in..." end - if @@bbs - @store.transaction do - @store['username'], @store['password'] = @username, @password + Thread.new do + begin + @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, + :host => '64.198.88.46', # bbs.iscabbs.com was not resolving + :port => 6145 + ) + rescue RuntimeError => err + debug "error: #{err.message}" + @@bbs = nil + @mainstack.append do + para err.message + end + end + if @@bbs + @store.transaction do + @store['username'], @store['password'] = @username, @password + end + visit '/forums' end - visit '/forums' end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end -# if @username and @password -# do_login -# end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs - forums = @@bbs.forums('all') - forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort - forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort - forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort - forums_todo.each { |n| forums[n][:todo] = true } - forums_joined.each { |n| forums[n][:joined] = true } - - # delete mail - forums.delete(1) - - stack STACKSTYLE do + @mainstack = stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 - tagline link(link("Forums", :click => "/forums")) - - # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', - # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } - [ ["Unread", forums_todo], - ["Subscribed", forums_joined], - ["Zapped", forums_all]].each do | pair | - group_name, ordered_ids = *pair - if ordered_ids.length > 0 + para "loading forums..." + end + + Thread.new do + forums = @@bbs.forums('all') + forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort + forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort + forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort + forums_todo.each { |n| forums[n][:todo] = true } + forums_joined.each { |n| forums[n][:joined] = true } + + # delete mail + forums.delete(1) + linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"], + [ 'q', '[q]uit', Proc.new { exit() } ] + ] ) + keypress { | key | keypressproc.call(key) } + @mainstack.clear do + background aliceblue, :curve => 20 + border black, :curve => 20 + para *linklist + # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', + # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } + [ ["Unread", forums_todo], + ["Subscribed", forums_joined], + ["Zapped", forums_all]].each do | pair | + group_name, ordered_ids = *pair stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | id | data = forums[id] stack STACKSTYLE do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end - - keypress do | key | - if key == ' ' - if forums_todo.length > 0 - visit "/forum/#{forums_todo[0]}" - else - visit '/forums' - end - elsif key == 'q' - exit() - end - end end def forum(id) visit '/login' unless @@bbs - @forum = @@bbs.jump(id) - first_unread = @forum.first_unread.to_i - info "first_unread: #{first_unread}" - stack STACKSTYLE do + linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"], + [ 'i', '[i]nfo', "/foruminfo/#{id}"], + [ 'i', '[b]ack to forum list', "/forums"], + [ ' ', '[ ]first unread', "/first_unread/#{id}"], + [ 'q', '[q]uit', Proc.new { exit() } ] + ] ) + + keypress { | key | keypressproc.call(key) } + + @mainstack = stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 - tagline( link(link("Forums", :click => "/forums")), " / ", - link( "#{@forum.name}>", :click => "/forum/#{id}") ) - para "Admin is #{@forum.admin}." - para( link("post", :click => "/new_post/#{id}"), " ", - link("info", :click => "/foruminfo/#{id}") , " ", - link("first unread", :click => "/first_unread/#{id}") - ) + para "loading forum #{id}..." + end + + Thread.new { + @forum = @@bbs.jump(id) + first_unread = @forum.first_unread.to_i @posts = @forum.post_headers noteids = @forum.noteids.sort msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } - [ [ "Unread", msgs_unread ], - [ "Read", msgs_read ] ].each do | pair | - group_name, ordered_ids = *pair - if ordered_ids.length > 0 + info "got posts" + @mainstack.clear do + info "adding background" + background blanchedalmond, :curve => 20 + border black, :curve => 20 + para *linklist + [ [ "Unread", msgs_unread, ], + [ "Read", msgs_read, ]].each do | pair | + group_name, ordered_ids = *pair + info "adding #{group_name} stack" stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack STACKSTYLE do - if post_id >= first_unread - background ivory, :curve => 10 - else - background lightgrey, :curve => 10 - end + background ivory, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end - end - keypress do | key | - if key == " " - visit "/first_unread/#{id}" - elsif key == 'q' - exit() - end - end + } end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para *linklist @info = @forum.forum_information - info @info.inspect stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end - def first_unread(forum_id) - visit '/login' unless @@bbs - @forum = @@bbs.jump(forum_id) - first_unread_msg = @forum.first_unread.to_i - first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } - info "first_unread_found: #{first_unread_found.inspect}" - if first_unread_found - visit "/message/#{forum_id}/#{first_unread_found}" + def first_todo + stack STACKSTYLE do + background blanchedalmond, :curve => 20 + border black, :curve => 20 + para "finding first forum with unread messages..." + end + forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort + if forums_todo.length > 0 + forum_id = forums_todo[0] + info "found todo forum: #{forum_id}" + visit "/first_unread/#{forum_id}" else + info "found no todo forums: visiting forums" visit "/forums" end end + def first_unread(forum_id) + visit '/login' unless @@bbs + info "first_unread for forum_id #{forum_id}" + + stack STACKSTYLE do + background blanchedalmond, :curve => 20 + border black, :curve => 20 + para "finding first unread message in forum #{forum_id}..." + end + Thread.new { + if forum_id.length == 0 # need to find it + info "zero length forum id, looking for first unread forum" + end + info "jumping to #{forum_id}" + @forum = @@bbs.jump(forum_id) + info "finding first unread" + first_unread_msg = @forum.first_unread.to_i + info "seeing if it exists" + first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } + if first_unread_found + info "visiting it" + visit "/message/#{forum_id}/#{first_unread_found}" + else + info "visiting first todo" + visit "/first_todo" + end + } + end + def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] - debug "checking respond to" if action.respond_to? :call - debug "calling #{action}" action.call else visit action end end end return linklist, keypressproc end def message(forum_id,msgnum) visit '/login' unless @@bbs - @forum = @@bbs.jump(forum_id) - first_unread_msg = @forum.first_unread.to_i - if msgnum.to_i >= first_unread_msg - @forum.first_unread = msgnum.to_i + 1 + stack STACKSTYLE do + background gold, :curve => 20 + border black, :curve => 20 + @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." } end - post_ids = @forum.post_headers.keys.sort.reverse - post_index = post_ids.index(msgnum) - msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) - msg_next = post_ids[post_index - 1] if post_index > 0 - @post = @forum.read(msgnum) + Thread.new { + @forum = @@bbs.jump(forum_id) + first_unread_msg = @forum.first_unread.to_i + if msgnum.to_i >= first_unread_msg + @forum.first_unread = msgnum.to_i + 1 + end + post_ids = @forum.post_headers.keys.sort.reverse + post_index = post_ids.index(msgnum) + msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) + msg_next = post_ids[post_index - 1] if post_index > 0 + @post = @forum.read(msgnum) - action_list = + action_list = if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], [ "b" , "[b]ack to forum", "/forum/#{forum_id}" ], [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] - - linklist, keypressproc = actions(action_list) - keypress { | key | keypressproc.call(key) } - - stack STACKSTYLE do - background gold, :curve => 20 - border black, :curve => 20 - tagline (link("Forums", :click => "/forums"), - " / ", - link("#{@forum.name}>", :click => "/forum/#{forum_id}"), - " / ", - link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) - @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" - + + linklist, keypressproc = actions(action_list) + keypress { | key | + keypressproc.call(key) + } + + @messagestack.clear do + para *linklist + @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" - stack STACKSTYLE do - background aliceblue, :curve => 20 - border black, :curve => 20 - para @whole_message - end - para *linklist - - end - + stack STACKSTYLE do + background aliceblue, :curve => 20 + border black, :curve => 20 + para @whole_message + end + end + } end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
9b87956367da8d1413ad8a77fb436e4784888437
notes about packages and their issues
diff --git a/README.txt b/README.txt index b5ce5cf..e35887b 100644 --- a/README.txt +++ b/README.txt @@ -1,21 +1,26 @@ Shoesca (until I think of a better name). Shoesca is a client for the ancient telnet-based ISCA BBS telnet://bbs.iscabbs.com/ It utilizes Wade Minter's library for accessing the bbs through the newer, non-telnet-based 'raccdoc' interface. http://github.com/minter/raccdoc/tree/master To use it you need a copy of Shoes ( http://shoooes.net/ ). Fire up Shoes, and choose "Open an app" and open the shoesca.rb file. You'll be presented with a login screen. The app will save your login credentials in a file called bbsconfig.yaml, in the same directory as the shoesca.rb file. The first time you run the app, it will download a copy of the raccdoc library; subsequent runs, it will use the copy it downloaded the first time. +Packaged, executable versions (.exe, .dmg, and .run) are +available in the packages directory; however, they may be +buggy (the .exe in particular pops up a bogus error message +about SSLEAY32.dll). Downloading shoes from http//shoooes.net +is preferable, esp. on Windows.
edheil/shoesca
112ed2fb35ed6575693bafd5416e1add263ddc23
remove 'require openssl' hack that's supposed to fix windows packaging bug but doesn't
diff --git a/shoesca.rb b/shoesca.rb index b1d3fcb..7bc74ef 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,398 +1,393 @@ - - - - Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' -require 'openssl/ssl' # prevents a weird little error on packaged versions for Win class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof STACKSTYLE = { :width => 650, :margin => 20 } url '/', :main url '/forums', :forums url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def license stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end # if @username and @password # do_login # end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 tagline link(link("Forums", :click => "/forums")) # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | id | data = forums[id] stack STACKSTYLE do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end keypress do | key | if key == ' ' if forums_todo.length > 0 visit "/forum/#{forums_todo[0]}" else visit '/forums' end elsif key == 'q' exit() end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i info "first_unread: #{first_unread}" stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." para( link("post", :click => "/new_post/#{id}"), " ", link("info", :click => "/foruminfo/#{id}") , " ", link("first unread", :click => "/first_unread/#{id}") ) @posts = @forum.post_headers noteids = @forum.noteids.sort msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } [ [ "Unread", msgs_unread ], [ "Read", msgs_read ] ].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack STACKSTYLE do if post_id >= first_unread background ivory, :curve => 10 else background lightgrey, :curve => 10 end border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end end keypress do | key | if key == " " visit "/first_unread/#{id}" elsif key == 'q' exit() end end end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], [ 'p', '[p]ost', "/new_post/#{id}"], [ " ", "[ ]first unread message", "/first_unread/#{id}" ], ] keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para *linklist @info = @forum.forum_information info @info.inspect stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end def first_unread(forum_id) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } info "first_unread_found: #{first_unread_found.inspect}" if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}" else visit "/forums" end end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def actions(list) linklist = [] list.each do | item | linklist << link(item[1], :click => item[2] ) linklist << " " unless item == list.last end keypressproc = Proc.new do | key | found = list.assoc(key) if found action = found[2] debug "checking respond to" if action.respond_to? :call debug "calling #{action}" action.call else visit action end end end return linklist, keypressproc end def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i >= first_unread_msg @forum.first_unread = msgnum.to_i + 1 end post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 @post = @forum.read(msgnum) action_list = if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], [ "b" , "[b]ack to forum", "/forum/#{forum_id}" ], [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], [ "q", "[q]uit", Proc.new { exit()} ] ] linklist, keypressproc = actions(action_list) keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 tagline (link("Forums", :click => "/forums"), " / ", link("#{@forum.name}>", :click => "/forum/#{forum_id}"), " / ", link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message end para *linklist end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
11650b7e040e7a3bb0d37cf5e275043e405ad799
More cosmetics
diff --git a/shoesca.rb b/shoesca.rb index f52aedf..b1d3fcb 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,361 +1,398 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' +require 'openssl/ssl' # prevents a weird little error on packaged versions for Win class RaccdocClient < Shoes LICENSE = <<eof Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. eof STACKSTYLE = { :width => 650, :margin => 20 } url '/', :main url '/forums', :forums url '/login', :login url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def license stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para link('back', :click => '/login') para LICENSE end end def login @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end para(link( 'license', :click => '/license' )) keypress do | key | if key == "\n" do_login end end # if @username and @password # do_login # end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 tagline link(link("Forums", :click => "/forums")) # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | id | data = forums[id] stack STACKSTYLE do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end keypress do | key | if key == ' ' if forums_todo.length > 0 visit "/forum/#{forums_todo[0]}" else visit '/forums' end + elsif key == 'q' + exit() end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i info "first_unread: #{first_unread}" stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." para( link("post", :click => "/new_post/#{id}"), " ", link("info", :click => "/foruminfo/#{id}") , " ", link("first unread", :click => "/first_unread/#{id}") ) @posts = @forum.post_headers noteids = @forum.noteids.sort msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } [ [ "Unread", msgs_unread ], [ "Read", msgs_read ] ].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack STACKSTYLE do if post_id >= first_unread background ivory, :curve => 10 else background lightgrey, :curve => 10 end border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end end keypress do | key | if key == " " visit "/first_unread/#{id}" + elsif key == 'q' + exit() end end end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) + + linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"], + [ 'p', '[p]ost', "/new_post/#{id}"], + [ " ", "[ ]first unread message", "/first_unread/#{id}" ], + ] + keypress { | key | keypressproc.call(key) } stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) - para( link("post", :click => "/new_post/#{id}") ) + para *linklist @info = @forum.forum_information info @info.inspect stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end def first_unread(forum_id) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } info "first_unread_found: #{first_unread_found.inspect}" if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}" else visit "/forums" end end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end + + def actions(list) + linklist = [] + list.each do | item | + linklist << link(item[1], :click => item[2] ) + linklist << " " unless item == list.last + end + + keypressproc = Proc.new do | key | + found = list.assoc(key) + if found + action = found[2] + debug "checking respond to" + if action.respond_to? :call + debug "calling #{action}" + action.call + else + visit action + end + end + end + return linklist, keypressproc + end + def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i >= first_unread_msg @forum.first_unread = msgnum.to_i + 1 end post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 @post = @forum.read(msgnum) + + + action_list = + if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end + + if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end + + [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ], + [ "b" , "[b]ack to forum", "/forum/#{forum_id}" ], + [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ], + [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ], + [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ], + [ "q", "[q]uit", Proc.new { exit()} ] ] + + linklist, keypressproc = actions(action_list) + keypress { | key | keypressproc.call(key) } + stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 tagline (link("Forums", :click => "/forums"), " / ", link("#{@forum.name}>", :click => "/forum/#{forum_id}"), " / ", link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" - para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, - " ", - if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, - " ", - link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}"), - " ", - link("mark unread", :click => "/mark_unread/#{forum_id}/#{msgnum}"), - " ", - link("copy post to clipboard") { self.clipboard=@whole_message; info @whole_message } - ) + stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message end -# para @post.inspect - end - keypress do | key | - if key == " " - visit "/first_unread/#{forum_id}" - end + para *linklist + end + end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack STACKSTYLE do background lime, :curve => 20 - border black, :curve => 10 + border black, :curve => 20 tagline "New Post" - para link("back", :click => "/forum/#{forum_id}") + para link("back", :click => "/message/#{forum_id}/#{msgnum}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end - end def new_post(forum_id) visit '/login' unless @@bbs stack STACKSTYLE do background lime, :curve => 20 - border black, :curve => 10 + border black, :curve => 20 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
f969bb67c099407103c437ed76b18e0b07d831a1
add packages for mac, linux, windows
diff --git a/packages/shoesca.dmg b/packages/shoesca.dmg new file mode 100644 index 0000000..fe5b668 Binary files /dev/null and b/packages/shoesca.dmg differ diff --git a/packages/shoesca.exe b/packages/shoesca.exe new file mode 100644 index 0000000..0e61758 Binary files /dev/null and b/packages/shoesca.exe differ diff --git a/packages/shoesca.run b/packages/shoesca.run new file mode 100755 index 0000000..05808bb --- /dev/null +++ b/packages/shoesca.run @@ -0,0 +1,387 @@ +#!/bin/sh +# This script was generated using Makeself 2.1.4 +FULLSIZE=12301 +CRCsum="0000000000" +MD5="0aeae809d4eb1a8ca4d2a26c217d8c70" +TMPROOT=${TMPDIR:=/tmp} + +label="Shoesca" +script="./sh-install" +scriptargs="" +targetdir="dist" +filesizes="3478" +keep=n + +print_cmd_arg="" +if type printf > /dev/null; then + print_cmd="printf" +elif test -x /usr/ucb/echo; then + print_cmd="/usr/ucb/echo" +else + print_cmd="echo" +fi + +unset CDPATH + +MS_Printf() +{ + $print_cmd $print_cmd_arg "$1" +} + +MS_Progress() +{ + while read a; do + MS_Printf . + done +} + +MS_dd() +{ + blocks=`expr $3 / 1024` + bytes=`expr $3 % 1024` + dd if="$1" ibs=$2 skip=1 obs=1024 conv=sync 2> /dev/null | \ + { test $blocks -gt 0 && dd ibs=1024 obs=1024 count=$blocks ; \ + test $bytes -gt 0 && dd ibs=1 obs=1024 count=$bytes ; } 2> /dev/null +} + +MS_Help() +{ + cat << EOH >&2 +Makeself version 2.1.4 + 1) Getting help or info about $0 : + $0 --help Print this message + $0 --info Print embedded info : title, default target directory, embedded script ... + $0 --lsm Print embedded lsm entry (or no LSM) + $0 --list Print the list of files in the archive + $0 --check Checks integrity of the archive + + 2) Running $0 : + $0 [options] [--] [additional arguments to embedded script] + with following options (in that order) + --confirm Ask before running embedded script + --noexec Do not run embedded script + --keep Do not erase target directory after running + the embedded script + --nox11 Do not spawn an xterm + --nochown Do not give the extracted files to the current user + --target NewDirectory Extract in NewDirectory + --tar arg1 [arg2 ...] Access the contents of the archive through the tar command + -- Following arguments will be passed to the embedded script +EOH +} + +MS_Check() +{ + OLD_PATH=$PATH + PATH=${GUESS_MD5_PATH:-"$OLD_PATH:/bin:/usr/bin:/sbin:/usr/local/ssl/bin:/usr/local/bin:/opt/openssl/bin"} + MD5_PATH=`exec 2>&-; which md5sum || type md5sum | cut -c 11-` + MD5_PATH=${MD5_PATH:-`exec 2>&-; which md5 || type md5 | cut -c 8-`} + PATH=$OLD_PATH + MS_Printf "Verifying archive integrity..." + offset=`head -n 375 "$1" | wc -c | tr -d " "` + verb=$2 + i=1 + for s in $filesizes + do + crc=`echo $CRCsum | cut -d" " -f$i` + if test -x "$MD5_PATH"; then + md5=`echo $MD5 | cut -d" " -f$i` + if test $md5 = "00000000000000000000000000000000"; then + test x$verb = xy && echo " $1 does not contain an embedded MD5 checksum." >&2 + else + md5sum=`MS_dd "$1" $offset $s | "$MD5_PATH" | cut -b-32`; + if test "$md5sum" != "$md5"; then + echo "Error in MD5 checksums: $md5sum is different from $md5" >&2 + exit 2 + else + test x$verb = xy && MS_Printf " MD5 checksums are OK." >&2 + fi + crc="0000000000"; verb=n + fi + fi + if test $crc = "0000000000"; then + test x$verb = xy && echo " $1 does not contain a CRC checksum." >&2 + else + sum1=`MS_dd "$1" $offset $s | CMD_ENV=xpg4 cksum | awk '{print $1}'` + if test "$sum1" = "$crc"; then + test x$verb = xy && MS_Printf " CRC checksums are OK." >&2 + else + echo "Error in checksums: $sum1 is different from $crc" + exit 2; + fi + fi + i=`expr $i + 1` + offset=`expr $offset + $s` + done + echo " All good." +} + +UnTAR() +{ + tar $1vf - 2>&1 || { echo Extraction failed. > /dev/tty; kill -15 $$; } +} + +finish=true +xterm_loop= +nox11=n +copy=none +ownership=y +verbose=n + +initargs="$@" + +while true +do + case "$1" in + -h | --help) + MS_Help + exit 0 + ;; + --info) + echo Identification: "$label" + echo Target directory: "$targetdir" + echo Uncompressed size: 13 KB + echo Compression: gzip + echo Date of packaging: Sun Mar 15 16:32:22 -0400 2009 + echo Built with Makeself version 2.1.4 on + echo Build command was: "/usr/bin/makeself \\ + \"dist\" \\ + \"pkg/shoesca.rb.run\" \\ + \"Shoesca\" \\ + \"./sh-install\"" + if test x$script != x; then + echo Script run after extraction: + echo " " $script $scriptargs + fi + if test x"" = xcopy; then + echo "Archive will copy itself to a temporary location" + fi + if test x"n" = xy; then + echo "directory $targetdir is permanent" + else + echo "$targetdir will be removed after extraction" + fi + exit 0 + ;; + --dumpconf) + echo LABEL=\"$label\" + echo SCRIPT=\"$script\" + echo SCRIPTARGS=\"$scriptargs\" + echo archdirname=\"dist\" + echo KEEP=n + echo COMPRESS=gzip + echo filesizes=\"$filesizes\" + echo CRCsum=\"$CRCsum\" + echo MD5sum=\"$MD5\" + echo OLDUSIZE=13 + echo OLDSKIP=376 + exit 0 + ;; + --lsm) +cat << EOLSM +No LSM. +EOLSM + exit 0 + ;; + --list) + echo Target directory: $targetdir + offset=`head -n 375 "$0" | wc -c | tr -d " "` + for s in $filesizes + do + MS_dd "$0" $offset $s | eval "gzip -cd" | UnTAR t + offset=`expr $offset + $s` + done + exit 0 + ;; + --tar) + offset=`head -n 375 "$0" | wc -c | tr -d " "` + arg1="$2" + shift 2 + for s in $filesizes + do + MS_dd "$0" $offset $s | eval "gzip -cd" | tar "$arg1" - $* + offset=`expr $offset + $s` + done + exit 0 + ;; + --check) + MS_Check "$0" y + exit 0 + ;; + --confirm) + verbose=y + shift + ;; + --noexec) + script="" + shift + ;; + --keep) + keep=y + shift + ;; + --target) + keep=y + targetdir=${2:-.} + shift 2 + ;; + --nox11) + nox11=y + shift + ;; + --nochown) + ownership=n + shift + ;; + --xwin) + finish="echo Press Return to close this window...; read junk" + xterm_loop=1 + shift + ;; + --phase2) + copy=phase2 + shift + ;; + --) + shift + break ;; + -*) + echo Unrecognized flag : "$1" >&2 + MS_Help + exit 1 + ;; + *) + break ;; + esac +done + +case "$copy" in +copy) + tmpdir=$TMPROOT/makeself.$RANDOM.`date +"%y%m%d%H%M%S"`.$$ + mkdir "$tmpdir" || { + echo "Could not create temporary directory $tmpdir" >&2 + exit 1 + } + SCRIPT_COPY="$tmpdir/makeself" + echo "Copying to a temporary location..." >&2 + cp "$0" "$SCRIPT_COPY" + chmod +x "$SCRIPT_COPY" + cd "$TMPROOT" + exec "$SCRIPT_COPY" --phase2 + ;; +phase2) + finish="$finish ; rm -rf `dirname $0`" + ;; +esac + +if test "$nox11" = "n"; then + if tty -s; then # Do we have a terminal? + : + else + if test x"$DISPLAY" != x -a x"$xterm_loop" = x; then # No, but do we have X? + if xset q > /dev/null 2>&1; then # Check for valid DISPLAY variable + GUESS_XTERMS="xterm rxvt dtterm eterm Eterm kvt konsole aterm" + for a in $GUESS_XTERMS; do + if type $a >/dev/null 2>&1; then + XTERM=$a + break + fi + done + chmod a+x $0 || echo Please add execution rights on $0 + if test `echo "$0" | cut -c1` = "/"; then # Spawn a terminal! + exec $XTERM -title "$label" -e "$0" --xwin "$initargs" + else + exec $XTERM -title "$label" -e "./$0" --xwin "$initargs" + fi + fi + fi + fi +fi + +if test "$targetdir" = "."; then + tmpdir="." +else + if test "$keep" = y; then + echo "Creating directory $targetdir" >&2 + tmpdir="$targetdir" + dashp="-p" + else + tmpdir="$TMPROOT/selfgz$$$RANDOM" + dashp="" + fi + mkdir $dashp $tmpdir || { + echo 'Cannot create target directory' $tmpdir >&2 + echo 'You should try option --target OtherDirectory' >&2 + eval $finish + exit 1 + } +fi + +location="`pwd`" +if test x$SETUP_NOCHECK != x1; then + MS_Check "$0" +fi +offset=`head -n 375 "$0" | wc -c | tr -d " "` + +if test x"$verbose" = xy; then + MS_Printf "About to extract 13 KB in $tmpdir ... Proceed ? [Y/n] " + read yn + if test x"$yn" = xn; then + eval $finish; exit 1 + fi +fi + +MS_Printf "Uncompressing $label" +res=3 +if test "$keep" = n; then + trap 'echo Signal caught, cleaning up >&2; cd $TMPROOT; /bin/rm -rf $tmpdir; eval $finish; exit 15' 1 2 3 15 +fi + +for s in $filesizes +do + if MS_dd "$0" $offset $s | eval "gzip -cd" | ( cd "$tmpdir"; UnTAR x ) | MS_Progress; then + if test x"$ownership" = xy; then + (PATH=/usr/xpg4/bin:$PATH; cd "$tmpdir"; chown -R `id -u` .; chgrp -R `id -g` .) + fi + else + echo + echo "Unable to decompress $0" >&2 + eval $finish; exit 1 + fi + offset=`expr $offset + $s` +done +echo + +cd "$tmpdir" +res=0 +if test x"$script" != x; then + if test x"$verbose" = xy; then + MS_Printf "OK to execute: $script $scriptargs $* ? [Y/n] " + read yn + if test x"$yn" = x -o x"$yn" = xy -o x"$yn" = xY; then + eval $script $scriptargs $*; res=$?; + fi + else + eval $script $scriptargs $*; res=$? + fi + if test $res -ne 0; then + test x"$verbose" = xy && echo "The program '$script' returned an error code ($res)" >&2 + fi +fi +if test "$keep" = n; then + cd $TMPROOT + /bin/rm -rf $tmpdir +fi +eval $finish; exit $res +‹Öe½IíZ{sÛ6Ïßü[:3’®6%¹¶“*±'nê4™sc;Óɹ•!‰5I°|XQc}÷ÛŃ%ÊQš4éõÂ[Äb±X`¿IçÎ_u:{{ûûøÛéÜ;¨þªëN·ÛÝ¿·{°{o—èݽÝ;°ÿt»“§™›à”Ÿc®¿á•Nwü· þº9„½×Û·ƒ6¯Ø¿‹ðÝø,6ù?·ÿÖ7í¡µÓ©•N9KSžf‡ö4Ëâ^»=uGW,›Ó±ÌV<yÚwKþv|5i~”¿m ¢meS?x~røk<ó~µä8ӜMýÑD³e[þ.aç-Øwõ%úð²)‹,=v‰Åûjü ”©öôåó“¶#Zr¤“ä‘-‡#XÀFSö|Üõühçb¸ã€maÿ<ñ“4ۆ,™ÃlÂ2‰ô{hÓØùv^ŽMT/(ˆ¶Öm€»F[rWtèýĽµa÷¨í±ëv”AK̵´PZѕ´¹À[©Ì…8‚*Õ¡6줶$‘.Š‚ +Jâ+´‰J¤Ô©›fÁ\ª5L=³l4uT·ÔNÄnq¹[…–ºGÿ„–›é©ò$AeG<¼¨‘Á؏<¡%ðDîª]ŽxëgÐ} ÚèNŹ–V}­*†…‹=¡e’Ý-Æ “Qx…þ;1˜^Lã®Ýª@N GJ²Œ¦!÷³®&‘VrœhÃΎvŽŒ‘ë$CÛúÒIéëõÙ®ÒìÝÏ÷öÖàÿîþ½{üß;øŠÿŸã²ð’¸–²,Áã˜<~b¡“ò<až8„ˆ*&,L‰ŸMó¡3âa»± •®$ÎÇ<™0ÿµ}”„th„~”±d'qG#‹<ËJØï¹Ÿ0hä‚2wàf<a ËnšÂ™dzø,Êࡄb”úìñɋóÔòáCÆÇÖcÏ2Í`·ÓùN¼™›xð”ù4ySqãf-#0….µ<NÍZ–uéâ„O7¼'ŒAÊÇJa=˜óFn óü4Küaž1@p#¯ ×Ï-$ä‘ÇÀu‡)ð±hüôâ5nmÄ̯òaààÔ±(eàâ¼DI§ÌƒáÜ"ö'4û¹šžp”êf>Gghœàš%)¶á;=’¶peá*IáxLƒZ¨å7+Ç9« .×å ™Sã2¦( 6óƒ† ò”ó`ÛBNøùÙÅӗ¯/àøÅøùøììøÅśșM9ö²k&åøaŒÆC8u“č²9êl=?9{üùxvúìâ ¡ì“g/NÎÏáÉË38†WÇgÏ¿>=>ƒW¯Ï^½<?qÎ)Ĭ[¶s,́»æ± œâRß ñ0Ù!²ÃÔ½fhÄó¯Q!ñ>ž¿ßF–piZdƾ¡FÏÆq¬SÔ졊ˆÙlæL¢\„B %¤í#Ç"/EÇ=¿8~üïó‹7§ä»ï 7ó=”{xûmè…n2A`{· @[ƒBûü¨ àJó0%²¼+:Žˆ.nJ²TEt¨uUDµ›¿xß¶ +yÕN?ó%"•LTò(a®gðԂ5diêN˜ä*y¹ds“«Š@ƒµì*Ø#6Ät")¸4¥Â’°8˜/Ë+:õÑ£áR_äm¾ÇÆPnw‰LŠ´I×;& Å*¸4bä=,Ñç„95#O(I PË»‰‹“FWÍ %G(ñŠ˜´y[&¯Ê…‚D)Vþ×Ú+/Àµ‰ÌŠ‹{süü´×;§žîf8Í0ñhìOÊÀJø#Œõ$rC\Å£Sñ õ–;³-¶§édØ©;¢tÓ̒œµÊmY#E¼lèÞF» i6#ÅZäj<>(dH'‘ú~€{‡:±·™æ2'Ö÷+\CVÊ-AáO¯÷˜GK{Ö£ÙÈ"Æ{å<GåDۅÌ÷]=:(+ì9Ýïï;÷ï;{hÿ-@eË5úEÆdšRæÁd–òàÏ›OóDLrÐÝÛßx”ö7œo”38Ë£ÌÙI’p± ,I +Qæ°õõ`ëÞ8*ºöÊþjO4Jp"Â7ŽÑî¥Ñ%|ݐVžÈ„ÏWïðô'¦(…¯¸jUúfiú™áÑ5ª\û)"g‘©—TnmU—Ò7J0©„Tü™ì’¹ò|°O)Ž´AÄÞÚze={9¾D´ zXeòÞÞzg„ߢ*HïK)¨v«‚ŠÈYبuÊF NJÙDè±æÈÐj¶H¶i½¥¬Pd ©NSäRhhæSE…VËÒ£®Ø<FODzˆÃ µà¦˜ ‹‡‡`ÿن-)±ì–[¥_»†õ£áC[+’¶V]¦’ÛUA°âíužÇ‚”-uK(©]ËìXã´5r>ùðCðRh͑Ífà 4”HÊ ã¸Ÿ‡Ð¬²µÑr2>pÐßÁÍîùe§ ؁Ën¿…G’$3ýÆÑq¼UQ’^+Œd™j¬‘Œ:“XÙº]ŒRb#±Ôç0w4Ŋï&ºQä˨Ù£.J+äéXð­¬rÍ0Ùi T=0<œÐ ǐåHr³Û²>[£,eÄ?û‰ÐÆ6#ÐV^j·Z:üÐí»uRœñkqâD" î$Áñ4þ†¨¼b ãùinÄ£yÈs*KyåՓåŠ;ç!®pr’Š§Í Uv}OQ]/”Õ¸äþ1÷˜­¬p —ökQ‡"«aé~ ù—öyŽÅ­˜Á¤Œg²ý‡Ï`AGì÷¥íEŠ]?1²™(H†`ÞÀ÷(ÿEœf¶2º€E<mA§à¸ÍV\b6õ³zwØÐ)ä5rÅÑÔXE¥ÛÔ¸Üß3Ö//<»¸d¾×_êßÊÔ‘ˆ5‘±|ÿšÓcâr]ÝÎÊ̳…HeçۅôÔb’° ³Û%yx0J餿´uҌB¥µÆz5ÃË3 +·ï-Ž°Ð“k&köu!ÞœvkIز&Õ¶ÙZ­ó +¤_Ø%^7 aƅ™škãBâ^©¼1€Àx#PµL}Ý·N}ýßÄݦïµÞ ½ÔÿH°Èû[ÆÅXóôM‚Õ1©„oòõæÁ6û¨r7Ûj¹:P4š2OT©ÞG¡GssôØÚ`Y_]²øC/U@þ¹8ºÍ?¡r¸¶ø)"(,³äUzÚôÄaIvñhB‰'=íê¡PŽ%#Ôé%¾hÝ֎Ƃ\ÃQEŠùt¦.uë陖ÎBÍÁG±D—–‘hô~JBYò„é$-¯`Àd”Q%ƒý7Ä$üŽ«®º0¥l(ãa½h(ÚTËÄ^°Ï Ù _±×Ä^á5‹Êo.™$ý“P¬'ZrŠOËïAύqø"g±ÞÆ%Ý_öÜ<›ò¤_V™ÑLý?VñU?TÁ­Xu`«æW¢dñ¼lªdúݏ1‘’ +¬]MUk1ÓDLʑŸ5ÿGQî£q Q6”¥ý- Åû*mq⼎¥1zœê¸-'|@`n|:éÉÍ¥v,q3žÔÁ:ÀÏÜTL¥½’CÝÆ'!Kⳉò˜¢×# DÔÁ Ã9<÷¯Xˆ¥Yn¬CîÍû¸¿1Me‚3ª"LéÄÇ÷’þ±0_m¥àx,SH.É7 +ã—3¿˜t±¦H•3ô`©V•dílj ýqrV5û”iTï%ÓÕaJäÊ#µ"NëMe¼¸*¶y×åá3n‹Ô ®":ÖW… h9´’ùkOM•ÈÍ͐{ýw݈7Ü`'äØo¡[Ù…Æk +káPEÂè =3E{‹Ã´GšæVáý¡öÚàº4Æ¢.ý²°¤‡Ð,ä©¢tº¥´ˆ½ÍÖHÛY•¦ëÙGº”+Nn깦NxðqH +›€è2x®?7n§¥¯‘]/ZnÏúZÎLBš·U€ïlÊ6Pܸñ¤+ÙÀ!ŒYÀ8á!h’,*¿Dš@ಸ\ZYŠ© YÔ§ÂÐ H½pð£I«oW^°¨àžó@-î7]™ˆk{@!Sݬ•Ó®šŠ\^OE÷>ϗͽ~:°átrñy@MY$¿'Xc©$&ԟÚÍ/ 6œ¡~ +ñ•‹ˆÎŒN¹›xXǽ<O‚tXõ©ªr«:Ú¢2ƒöÆ K¹Û_)lt†URU§²D’7ú½™dþnžŸøŒR8S¾;ó +—)Q>ötŽ­½ÕŒ‹¹t@q®è"è4ü¬Iï.[êÕåͰé.Ý.lX8ôäZ2 Q¿çâÍH™cTBY‚=Ê+z6L2ú½èF)?ðÃ{ÁÔ]y“ý‚Íà[Œœ¤|Ÿ&zÒÖ)Ud»!«ßOÓ­Xú¶ñÖ~‡¾Óš2ñ±!¶¿ë«Ôâ eF@&µo~v ÏWë K}MѪºbs]ŠÓsq5^Y<tÖ>ðüð°ï?ʰò¿0±ü¶×cc…÷qE_ú»ã¯××ëëõå¯ÿ~W< \ No newline at end of file
edheil/shoesca
d371923eceddb26e0671c0f8d5a1ac771e9bfa7b
add COPYING
diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>.
edheil/shoesca
1123e4870837d5aebccd814bb0d208ef2f7a09c8
Add GPL
diff --git a/shoesca.rb b/shoesca.rb index 84ccb6f..f52aedf 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,326 +1,361 @@ + + + + Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes + LICENSE = <<eof +Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm ) + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see <http://www.gnu.org/licenses/>. +eof + STACKSTYLE = { :width => 650, :margin => 20 } url '/', :main url '/forums', :forums url '/login', :login + url '/license', :license url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil - def login(error=nil) + + def license + stack STACKSTYLE do + background aliceblue, :curve => 20 + border black, :curve => 20 + para link('back', :click => '/login') + para LICENSE + end + end + + def login @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end + para(link( 'license', :click => '/license' )) + + keypress do | key | if key == "\n" do_login end end # if @username and @password # do_login # end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 tagline link(link("Forums", :click => "/forums")) # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } [ ["Unread", forums_todo], ["Subscribed", forums_joined], ["Zapped", forums_all]].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | id | data = forums[id] stack STACKSTYLE do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end end end end keypress do | key | if key == ' ' if forums_todo.length > 0 visit "/forum/#{forums_todo[0]}" else visit '/forums' end end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i info "first_unread: #{first_unread}" stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." para( link("post", :click => "/new_post/#{id}"), " ", link("info", :click => "/foruminfo/#{id}") , " ", link("first unread", :click => "/first_unread/#{id}") ) @posts = @forum.post_headers noteids = @forum.noteids.sort msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } [ [ "Unread", msgs_unread ], [ "Read", msgs_read ] ].each do | pair | group_name, ordered_ids = *pair if ordered_ids.length > 0 stack STACKSTYLE do background white, :curve => 20 border black, :curve => 20 caption group_name ordered_ids.each do | post_id | post = @posts[post_id.to_s] stack STACKSTYLE do if post_id >= first_unread background ivory, :curve => 10 else background lightgrey, :curve => 10 end border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end end end keypress do | key | if key == " " visit "/first_unread/#{id}" end end end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para( link("post", :click => "/new_post/#{id}") ) @info = @forum.forum_information info @info.inspect stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end def first_unread(forum_id) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } info "first_unread_found: #{first_unread_found.inspect}" if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}" else visit "/forums" end end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i >= first_unread_msg @forum.first_unread = msgnum.to_i + 1 end post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 @post = @forum.read(msgnum) stack STACKSTYLE do background gold, :curve => 20 border black, :curve => 20 tagline (link("Forums", :click => "/forums"), " / ", link("#{@forum.name}>", :click => "/forum/#{forum_id}"), " / ", link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, " ", if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, " ", link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}"), " ", link("mark unread", :click => "/mark_unread/#{forum_id}/#{msgnum}"), " ", link("copy post to clipboard") { self.clipboard=@whole_message; info @whole_message } ) stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 para @whole_message end # para @post.inspect end keypress do | key | if key == " " visit "/first_unread/#{forum_id}" end end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
dda663c993ade4d4293e6f696fa7261afe8e9c52
visual overhaul
diff --git a/shoesca.rb b/shoesca.rb index 8a36f37..84ccb6f 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,301 +1,326 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes + STACKSTYLE = { :width => 650, :margin => 20 } url '/', :main url '/forums', :forums url '/login', :login url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def login(error=nil) @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end - @mainstack = stack :width => 700, :margin => 50 do + @mainstack = stack STACKSTYLE do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end keypress do | key | if key == "\n" do_login end end # if @username and @password # do_login # end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) - stack :width => 700, :margin => 50 do + stack STACKSTYLE do background aliceblue, :curve => 20 border black, :curve => 20 tagline link(link("Forums", :click => "/forums")) # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } - @ordered_ids = forums_todo + forums_joined + forums_all - @ordered_ids.each do | id | - data = forums[id] - stack :width => 0.90, :margin => 3 do - if data[:todo] - background ivory, :curve => 10 - elsif data[:joined] - background lightgrey, :curve => 10 - else - background darkslateblue, :curve => 10 + [ ["Unread", forums_todo], + ["Subscribed", forums_joined], + ["Zapped", forums_all]].each do | pair | + group_name, ordered_ids = *pair + if ordered_ids.length > 0 + stack STACKSTYLE do + background white, :curve => 20 + border black, :curve => 20 + caption group_name + ordered_ids.each do | id | + data = forums[id] + stack STACKSTYLE do + if data[:todo] + background ivory, :curve => 10 + elsif data[:joined] + background lightgrey, :curve => 10 + else + background darkslateblue, :curve => 10 + end + border black, :curve => 10 + para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") + end + end end - border black, :curve => 10 - para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end keypress do | key | if key == ' ' if forums_todo.length > 0 visit "/forum/#{forums_todo[0]}" else visit '/forums' end end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) first_unread = @forum.first_unread.to_i info "first_unread: #{first_unread}" - stack :width => 700, :margin => 50 do + stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." para( link("post", :click => "/new_post/#{id}"), " ", link("info", :click => "/foruminfo/#{id}") , " ", link("first unread", :click => "/first_unread/#{id}") ) @posts = @forum.post_headers noteids = @forum.noteids.sort msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } msgs_read = noteids.select { |msg| msg.to_i < first_unread } - ordered_ids = msgs_unread + msgs_read - - ordered_ids.each do | post_id | - post = @posts[post_id.to_s] - stack :width => 0.90 do - if post_id >= first_unread - background ivory, :curve => 10 - else - background lightgrey, :curve => 10 + [ [ "Unread", msgs_unread ], + [ "Read", msgs_read ] ].each do | pair | + group_name, ordered_ids = *pair + if ordered_ids.length > 0 + stack STACKSTYLE do + background white, :curve => 20 + border black, :curve => 20 + caption group_name + ordered_ids.each do | post_id | + post = @posts[post_id.to_s] + stack STACKSTYLE do + if post_id >= first_unread + background ivory, :curve => 10 + else + background lightgrey, :curve => 10 + end + border black, :curve => 10 + para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") + para post[:subject] + end + end end - border black, :curve => 10 - para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") - para post[:subject] end end end keypress do | key | if key == " " visit "/first_unread/#{id}" end end end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) - stack :width => 700, :margin => 50 do + stack STACKSTYLE do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para( link("post", :click => "/new_post/#{id}") ) @info = @forum.forum_information info @info.inspect - stack :width => 0.90 do + stack STACKSTYLE do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end def first_unread(forum_id) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } info "first_unread_found: #{first_unread_found.inspect}" if first_unread_found visit "/message/#{forum_id}/#{first_unread_found}" else visit "/forums" end end def mark_unread(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i < first_unread_msg @forum.first_unread = msgnum end visit "/forum/#{forum_id}" end def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) first_unread_msg = @forum.first_unread.to_i if msgnum.to_i >= first_unread_msg @forum.first_unread = msgnum.to_i + 1 end post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 @post = @forum.read(msgnum) - stack :width => 700, :margin => 50 do + stack STACKSTYLE do background gold, :curve => 20 - border black, :curve => 10 + border black, :curve => 20 tagline (link("Forums", :click => "/forums"), " / ", link("#{@forum.name}>", :click => "/forum/#{forum_id}"), " / ", link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" - para @whole_message + para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, " ", if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, " ", link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}"), " ", link("mark unread", :click => "/mark_unread/#{forum_id}/#{msgnum}"), " ", - link("copy post to clipboard") { self.clipboard=@whole_message; info @whole_message } + link("copy post to clipboard") { self.clipboard=@whole_message; info @whole_message } ) - + stack STACKSTYLE do + background aliceblue, :curve => 20 + border black, :curve => 20 + para @whole_message + end # para @post.inspect end keypress do | key | if key == " " visit "/first_unread/#{forum_id}" end end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" - stack :width => 700, :margin => 50 do + stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs - stack :width => 700, :margin => 50 do + stack STACKSTYLE do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
54af4fa8f9011e6b179afde52acba1952a372a56
mark_unread
diff --git a/shoesca.rb b/shoesca.rb index 6894624..8a36f37 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,267 +1,301 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes url '/', :main url '/forums', :forums url '/login', :login url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message + url '/mark_unread/(\d+)/(\d+)', :mark_unread url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def login(error=nil) @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end visit '/forums' end end @mainstack = stack :width => 700, :margin => 50 do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true button "login" do do_login end keypress do | key | if key == "\n" do_login end end # if @username and @password # do_login # end end end def main if @@bbs visit '/forums' else visit '/login' end end def forums visit '/login' unless @@bbs forums = @@bbs.forums('all') forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort forums_todo.each { |n| forums[n][:todo] = true } forums_joined.each { |n| forums[n][:joined] = true } # delete mail forums.delete(1) stack :width => 700, :margin => 50 do background aliceblue, :curve => 20 border black, :curve => 20 tagline link(link("Forums", :click => "/forums")) # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } @ordered_ids = forums_todo + forums_joined + forums_all @ordered_ids.each do | id | data = forums[id] stack :width => 0.90, :margin => 3 do if data[:todo] background ivory, :curve => 10 elsif data[:joined] background lightgrey, :curve => 10 else background darkslateblue, :curve => 10 end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") end end end keypress do | key | if key == ' ' if forums_todo.length > 0 visit "/forum/#{forums_todo[0]}" else visit '/forums' end end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) - first_unread = @forum.first_unread + first_unread = @forum.first_unread.to_i info "first_unread: #{first_unread}" stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." para( link("post", :click => "/new_post/#{id}"), " ", - link("info", :click => "/foruminfo/#{id}") ) + link("info", :click => "/foruminfo/#{id}") , " ", + link("first unread", :click => "/first_unread/#{id}") + ) @posts = @forum.post_headers - @post_ids = @posts.keys.sort.reverse - @post_ids.each do | post_id | - post = @posts[post_id] + noteids = @forum.noteids.sort + msgs_unread = noteids.select { |msg| msg.to_i >= first_unread } + msgs_read = noteids.select { |msg| msg.to_i < first_unread } + ordered_ids = msgs_unread + msgs_read + + ordered_ids.each do | post_id | + post = @posts[post_id.to_s] stack :width => 0.90 do if post_id >= first_unread background ivory, :curve => 10 else background lightgrey, :curve => 10 end border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end keypress do | key | if key == " " + visit "/first_unread/#{id}" end end - - - end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para( link("post", :click => "/new_post/#{id}") ) @info = @forum.forum_information info @info.inspect stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end def first_unread(forum_id) + visit '/login' unless @@bbs + @forum = @@bbs.jump(forum_id) + first_unread_msg = @forum.first_unread.to_i + first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg } + info "first_unread_found: #{first_unread_found.inspect}" + if first_unread_found + visit "/message/#{forum_id}/#{first_unread_found}" + else + visit "/forums" + end + end + def mark_unread(forum_id,msgnum) + visit '/login' unless @@bbs + @forum = @@bbs.jump(forum_id) + first_unread_msg = @forum.first_unread.to_i + if msgnum.to_i < first_unread_msg + @forum.first_unread = msgnum + end + visit "/forum/#{forum_id}" end def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) + first_unread_msg = @forum.first_unread.to_i + if msgnum.to_i >= first_unread_msg + @forum.first_unread = msgnum.to_i + 1 + end post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 - info post_ids.inspect - info msgnum - info msg_prev - info msg_next @post = @forum.read(msgnum) stack :width => 700, :margin => 50 do background gold, :curve => 20 border black, :curve => 10 tagline (link("Forums", :click => "/forums"), " / ", link("#{@forum.name}>", :click => "/forum/#{forum_id}"), " / ", link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) - tagline "#{@post.date} from #{@post.author}" - para @post.body - tagline "[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" + @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" + para @whole_message para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, " ", if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, " ", - link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}") ) + link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}"), + " ", + link("mark unread", :click => "/mark_unread/#{forum_id}/#{msgnum}"), + " ", + link("copy post to clipboard") { self.clipboard=@whole_message; info @whole_message } + ) # para @post.inspect end + keypress do | key | + if key == " " + visit "/first_unread/#{forum_id}" + end + end + end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
d77089334329fb28d36f23ae4db931c52a3e6cd6
reduce to a single 'forums' screen with different fora color coded
diff --git a/shoesca.rb b/shoesca.rb index 2713f85..6894624 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,251 +1,267 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes url '/', :main - url '/forums/(\w+)', :forums + url '/forums', :forums url '/login', :login url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo + url '/first_unread/(\d+)', :first_unread url '/message/(\d+)/(\d+)', :message url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def login(error=nil) @store = YAML::Store.new('bbsconfig.yaml') @username, @password = nil, nil @store.transaction(true) do @username, @password = @store['username'], @store['password'] end def do_login @username = @username_line.text @password = @password_line.text begin @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) rescue RuntimeError => err debug "error: #{err.message}" @@bbs = nil @mainstack.append do para err.message end end if @@bbs @store.transaction do @store['username'], @store['password'] = @username, @password end - visit '/forums/joined' + visit '/forums' end end @mainstack = stack :width => 700, :margin => 50 do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ @username }" para "password:" @password_line = edit_line "#{ @password }", :secret => true - - button "login" do do_login end keypress do | key | if key == "\n" do_login end end - - +# if @username and @password +# do_login +# end end end def main - if @bbs - visit '/forums/joined' + if @@bbs + visit '/forums' else visit '/login' end end - def forums( forumarg='todo') + def forums visit '/login' unless @@bbs - forums = @@bbs.forums(forumarg) - # filter out Mail, which doesn't work yet. - forums.delete(1) + forums = @@bbs.forums('all') + forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort + forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort + forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort + forums_todo.each { |n| forums[n][:todo] = true } + forums_joined.each { |n| forums[n][:joined] = true } - # also available, but not used: public, private - # not supported by isca: named, threads + # delete mail + forums.delete(1) - forumargs = %w[ todo joined all ] stack :width => 700, :margin => 50 do background aliceblue, :curve => 20 border black, :curve => 20 tagline link(link("Forums", :click => "/forums")) - tagline *forumargs.map{ |arg| [ link( "#{arg}.", :click => "/forums/#{arg}"), " "] }.flatten # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } - @ordered_ids = forums.keys.sort + @ordered_ids = forums_todo + forums_joined + forums_all @ordered_ids.each do | id | data = forums[id] stack :width => 0.90, :margin => 3 do - background lightgrey, :curve => 10 + if data[:todo] + background ivory, :curve => 10 + elsif data[:joined] + background lightgrey, :curve => 10 + else + background darkslateblue, :curve => 10 + end border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") -# para "#{data.inspect}" end end end keypress do | key | if key == ' ' - if forumarg == 'todo' - if @ordered_ids.length > 0 - unread_forum = @ordered_ids[0] - visit "/forum/#{unread_forum}" - else - visit "/forums/todo" - end + if forums_todo.length > 0 + visit "/forum/#{forums_todo[0]}" else - visit '/forums/todo' + visit '/forums' end end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) - + first_unread = @forum.first_unread + info "first_unread: #{first_unread}" stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." para( link("post", :click => "/new_post/#{id}"), " ", link("info", :click => "/foruminfo/#{id}") ) @posts = @forum.post_headers @post_ids = @posts.keys.sort.reverse @post_ids.each do | post_id | post = @posts[post_id] stack :width => 0.90 do - background lightgrey, :curve => 10 + if post_id >= first_unread + background ivory, :curve => 10 + else + background lightgrey, :curve => 10 + end border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end - end + keypress do | key | + if key == " " + end + end + + + end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para( link("post", :click => "/new_post/#{id}") ) @info = @forum.forum_information info @info.inspect stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end + def first_unread(forum_id) + + end + def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 info post_ids.inspect info msgnum info msg_prev info msg_next @post = @forum.read(msgnum) stack :width => 700, :margin => 50 do background gold, :curve => 20 border black, :curve => 10 tagline (link("Forums", :click => "/forums"), " / ", link("#{@forum.name}>", :click => "/forum/#{forum_id}"), " / ", link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) tagline "#{@post.date} from #{@post.author}" para @post.body tagline "[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, " ", if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, " ", link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}") ) # para @post.inspect end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
b6b8083c3d6168d0354562a55c68a3201f850d0b
login error rescue
diff --git a/shoesca.rb b/shoesca.rb index 9f1fd32..2713f85 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,206 +1,251 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes url '/', :main url '/forums/(\w+)', :forums url '/login', :login url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)', :message url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil - def login - store = YAML::Store.new('bbsconfig.yaml') - username, password = nil, nil - store.transaction(true) do - username, password = store['username'], store['password'] + def login(error=nil) + @store = YAML::Store.new('bbsconfig.yaml') + @username, @password = nil, nil + @store.transaction(true) do + @username, @password = @store['username'], @store['password'] end - stack :width => 700, :margin => 50 do + def do_login + @username = @username_line.text + @password = @password_line.text + begin + @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password, + :host => '64.198.88.46', # bbs.iscabbs.com was not resolving + :port => 6145 + ) + rescue RuntimeError => err + debug "error: #{err.message}" + @@bbs = nil + @mainstack.append do + para err.message + end + end + if @@bbs + @store.transaction do + @store['username'], @store['password'] = @username, @password + end + visit '/forums/joined' + end + end + + + @mainstack = stack :width => 700, :margin => 50 do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" - @username_line = edit_line "#{ username }" + @username_line = edit_line "#{ @username }" para "password:" - @password_line = edit_line "#{ password }", :secret => true + @password_line = edit_line "#{ @password }", :secret => true + + + button "login" do - username = @username_line.text - password = @password_line.text - store.transaction do - store['username'], store['password'] = username, password + do_login + end + + keypress do | key | + if key == "\n" + do_login end - @@bbs = Raccdoc::Connection.new(:user => username, :password => password, - :host => '64.198.88.46', # bbs.iscabbs.com was not resolving - :port => 6145 - ) - visit '/forums/joined' end + + end end def main if @bbs visit '/forums/joined' else visit '/login' end end def forums( forumarg='todo') visit '/login' unless @@bbs forums = @@bbs.forums(forumarg) + + # filter out Mail, which doesn't work yet. forums.delete(1) -# forumargs = %w[ all joined public private todo named threads ] + + # also available, but not used: public, private + # not supported by isca: named, threads + forumargs = %w[ todo joined all ] stack :width => 700, :margin => 50 do background aliceblue, :curve => 20 border black, :curve => 20 tagline link(link("Forums", :click => "/forums")) tagline *forumargs.map{ |arg| [ link( "#{arg}.", :click => "/forums/#{arg}"), " "] }.flatten # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } -# ordered_ids = forums.keys.sort { |a,b| forums[a][:name] <=> forums[b][:name] } - ordered_ids = forums.keys.sort - ordered_ids.each do | id | + @ordered_ids = forums.keys.sort + @ordered_ids.each do | id | data = forums[id] stack :width => 0.90, :margin => 3 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") # para "#{data.inspect}" end end end - end + keypress do | key | + if key == ' ' + if forumarg == 'todo' + if @ordered_ids.length > 0 + unread_forum = @ordered_ids[0] + visit "/forum/#{unread_forum}" + else + visit "/forums/todo" + end + else + visit '/forums/todo' + end + end + end + end + def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." para( link("post", :click => "/new_post/#{id}"), " ", link("info", :click => "/foruminfo/#{id}") ) @posts = @forum.post_headers @post_ids = @posts.keys.sort.reverse @post_ids.each do | post_id | post = @posts[post_id] stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para( link("post", :click => "/new_post/#{id}") ) @info = @forum.forum_information info @info.inspect stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 info post_ids.inspect info msgnum info msg_prev info msg_next @post = @forum.read(msgnum) stack :width => 700, :margin => 50 do background gold, :curve => 20 border black, :curve => 10 tagline (link("Forums", :click => "/forums"), " / ", link("#{@forum.name}>", :click => "/forum/#{forum_id}"), " / ", link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) tagline "#{@post.date} from #{@post.author}" para @post.body tagline "[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, " ", if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, " ", link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}") ) # para @post.inspect end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
f7de7b0acc2cb6ef81e25e8aa13a3e2cf75daecd
filter list of fora as "joined" or "todo"
diff --git a/shoesca.rb b/shoesca.rb index d7af22e..9f1fd32 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,191 +1,206 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes url '/', :main + url '/forums/(\w+)', :forums url '/login', :login url '/forum/(\d+)', :forum url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)', :message url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def login store = YAML::Store.new('bbsconfig.yaml') username, password = nil, nil store.transaction(true) do username, password = store['username'], store['password'] end stack :width => 700, :margin => 50 do background salmon, :curve => 20 border black, :curve => 20 tagline "Login" para "username:" @username_line = edit_line "#{ username }" para "password:" @password_line = edit_line "#{ password }", :secret => true button "login" do username = @username_line.text password = @password_line.text store.transaction do store['username'], store['password'] = username, password end @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) - visit '/' + visit '/forums/joined' end end end def main + if @bbs + visit '/forums/joined' + else + visit '/login' + end + end + + def forums( forumarg='todo') visit '/login' unless @@bbs + forums = @@bbs.forums(forumarg) + forums.delete(1) +# forumargs = %w[ all joined public private todo named threads ] + forumargs = %w[ todo joined all ] stack :width => 700, :margin => 50 do background aliceblue, :curve => 20 border black, :curve => 20 - tagline link(link("Forums", :click => "/")) - forums = @@bbs.forums + tagline link(link("Forums", :click => "/forums")) + tagline *forumargs.map{ |arg| [ link( "#{arg}.", :click => "/forums/#{arg}"), " "] }.flatten + # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } - ordered_ids = forums.keys.sort { |a,b| forums[a][:name] <=> forums[b][:name] } +# ordered_ids = forums.keys.sort { |a,b| forums[a][:name] <=> forums[b][:name] } + ordered_ids = forums.keys.sort ordered_ids.each do | id | data = forums[id] stack :width => 0.90, :margin => 3 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") # para "#{data.inspect}" end end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 - tagline( link(link("Forums", :click => "/")), " / ", + tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." para( link("post", :click => "/new_post/#{id}"), " ", link("info", :click => "/foruminfo/#{id}") ) @posts = @forum.post_headers @post_ids = @posts.keys.sort.reverse @post_ids.each do | post_id | post = @posts[post_id] stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end def foruminfo(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 - tagline( link(link("Forums", :click => "/")), " / ", + tagline( link(link("Forums", :click => "/forums")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para( link("post", :click => "/new_post/#{id}") ) @info = @forum.forum_information info @info.inspect stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." caption "Forum info last updated #{@info[:date]} by Mikemike" para "#{@info[:body]}" end end end def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 info post_ids.inspect info msgnum info msg_prev info msg_next @post = @forum.read(msgnum) stack :width => 700, :margin => 50 do background gold, :curve => 20 border black, :curve => 10 - tagline (link("Forums", :click => "/"), + tagline (link("Forums", :click => "/forums"), " / ", link("#{@forum.name}>", :click => "/forum/#{forum_id}"), " / ", link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) tagline "#{@post.date} from #{@post.author}" para @post.body tagline "[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, " ", if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, " ", link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}") ) # para @post.inspect end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
502969cd39149582af03d917325603d28cc2d41e
change 'titles' to the smaller 'tagline'
diff --git a/shoesca.rb b/shoesca.rb index 8cd0a5b..d7af22e 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,164 +1,191 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes url '/', :main url '/login', :login url '/forum/(\d+)', :forum + url '/foruminfo/(\d+)', :foruminfo url '/message/(\d+)/(\d+)', :message url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def login store = YAML::Store.new('bbsconfig.yaml') username, password = nil, nil store.transaction(true) do username, password = store['username'], store['password'] end stack :width => 700, :margin => 50 do background salmon, :curve => 20 border black, :curve => 20 - title "Login" + tagline "Login" para "username:" @username_line = edit_line "#{ username }" para "password:" @password_line = edit_line "#{ password }", :secret => true button "login" do username = @username_line.text password = @password_line.text store.transaction do store['username'], store['password'] = username, password end @@bbs = Raccdoc::Connection.new(:user => username, :password => password, :host => '64.198.88.46', # bbs.iscabbs.com was not resolving :port => 6145 ) visit '/' end end end def main visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background aliceblue, :curve => 20 border black, :curve => 20 - title link(link("Forums", :click => "/")) + tagline link(link("Forums", :click => "/")) forums = @@bbs.forums + # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous', + # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" } ordered_ids = forums.keys.sort { |a,b| forums[a][:name] <=> forums[b][:name] } ordered_ids.each do | id | data = forums[id] stack :width => 0.90, :margin => 3 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") # para "#{data.inspect}" end end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) + stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 - title( link(link("Forums", :click => "/")), " / ", + tagline( link(link("Forums", :click => "/")), " / ", link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." - para( link("post", :click => "/new_post/#{id}") ) + para( link("post", :click => "/new_post/#{id}"), " ", + link("info", :click => "/foruminfo/#{id}") ) @posts = @forum.post_headers @post_ids = @posts.keys.sort.reverse @post_ids.each do | post_id | post = @posts[post_id] stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end + def foruminfo(id) + visit '/login' unless @@bbs + @forum = @@bbs.jump(id) + + stack :width => 700, :margin => 50 do + background blanchedalmond, :curve => 20 + border black, :curve => 20 + tagline( link(link("Forums", :click => "/")), " / ", + link( "#{@forum.name}>", :click => "/forum/#{id}") ) + para( link("post", :click => "/new_post/#{id}") ) + @info = @forum.forum_information + info @info.inspect + stack :width => 0.90 do + background lightgrey, :curve => 10 + border black, :curve => 10 + caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}." + caption "Forum info last updated #{@info[:date]} by Mikemike" + para "#{@info[:body]}" + end + end + end + def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 info post_ids.inspect info msgnum info msg_prev info msg_next @post = @forum.read(msgnum) stack :width => 700, :margin => 50 do background gold, :curve => 20 border black, :curve => 10 - title (link("Forums", :click => "/"), + tagline (link("Forums", :click => "/"), " / ", link("#{@forum.name}>", :click => "/forum/#{forum_id}"), " / ", link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) tagline "#{@post.date} from #{@post.author}" para @post.body tagline "[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, " ", if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, " ", link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}") ) # para @post.inspect end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 - title "New Post" + tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 - title "New Post" + tagline "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
2b3971473e4b80afd8ed480c9f1f53ca6ebc7f22
hardcode ip address organize links and titles
diff --git a/shoesca.rb b/shoesca.rb index cb7902f..8cd0a5b 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,160 +1,164 @@ Shoes.setup do Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes url '/', :main url '/login', :login url '/forum/(\d+)', :forum url '/message/(\d+)/(\d+)', :message url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def login store = YAML::Store.new('bbsconfig.yaml') username, password = nil, nil store.transaction(true) do username, password = store['username'], store['password'] end stack :width => 700, :margin => 50 do background salmon, :curve => 20 border black, :curve => 20 title "Login" para "username:" @username_line = edit_line "#{ username }" para "password:" @password_line = edit_line "#{ password }", :secret => true button "login" do username = @username_line.text password = @password_line.text store.transaction do store['username'], store['password'] = username, password end - @@bbs = Raccdoc::Connection.new(:user => username, :password => password) + @@bbs = Raccdoc::Connection.new(:user => username, :password => password, + :host => '64.198.88.46', # bbs.iscabbs.com was not resolving + :port => 6145 + ) visit '/' end end end def main visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background aliceblue, :curve => 20 border black, :curve => 20 - title "Forums" + title link(link("Forums", :click => "/")) forums = @@bbs.forums ordered_ids = forums.keys.sort { |a,b| forums[a][:name] <=> forums[b][:name] } ordered_ids.each do | id | data = forums[id] stack :width => 0.90, :margin => 3 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") # para "#{data.inspect}" end end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 - title "#{@forum.name}>" + title( link(link("Forums", :click => "/")), " / ", + link( "#{@forum.name}>", :click => "/forum/#{id}") ) para "Admin is #{@forum.admin}." - para( link("back", :click => "/"), - " ", - link("post", :click => "/new_post/#{id}") ) + para( link("post", :click => "/new_post/#{id}") ) @posts = @forum.post_headers @post_ids = @posts.keys.sort.reverse @post_ids.each do | post_id | post = @posts[post_id] stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 info post_ids.inspect info msgnum info msg_prev info msg_next @post = @forum.read(msgnum) stack :width => 700, :margin => 50 do background gold, :curve => 20 border black, :curve => 10 - title "Message" + title (link("Forums", :click => "/"), + " / ", + link("#{@forum.name}>", :click => "/forum/#{forum_id}"), + " / ", + link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}")) tagline "#{@post.date} from #{@post.author}" para @post.body tagline "[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, " ", if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, " ", - link("forum", :click => "/forum/#{forum_id}"), - " ", link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}") ) # para @post.inspect end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 title "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 title "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
64e9ef5ea137f249de40a8a2a0b40f8237b0f031
Explicit gem sources include github
diff --git a/shoesca.rb b/shoesca.rb index 9a44516..cb7902f 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,159 +1,160 @@ Shoes.setup do + Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/'] gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes url '/', :main url '/login', :login url '/forum/(\d+)', :forum url '/message/(\d+)/(\d+)', :message url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def login store = YAML::Store.new('bbsconfig.yaml') username, password = nil, nil store.transaction(true) do username, password = store['username'], store['password'] end stack :width => 700, :margin => 50 do background salmon, :curve => 20 border black, :curve => 20 title "Login" para "username:" @username_line = edit_line "#{ username }" para "password:" @password_line = edit_line "#{ password }", :secret => true button "login" do username = @username_line.text password = @password_line.text store.transaction do store['username'], store['password'] = username, password end @@bbs = Raccdoc::Connection.new(:user => username, :password => password) visit '/' end end end def main visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background aliceblue, :curve => 20 border black, :curve => 20 title "Forums" forums = @@bbs.forums ordered_ids = forums.keys.sort { |a,b| forums[a][:name] <=> forums[b][:name] } ordered_ids.each do | id | data = forums[id] stack :width => 0.90, :margin => 3 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") # para "#{data.inspect}" end end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 title "#{@forum.name}>" para "Admin is #{@forum.admin}." para( link("back", :click => "/"), " ", link("post", :click => "/new_post/#{id}") ) @posts = @forum.post_headers @post_ids = @posts.keys.sort.reverse @post_ids.each do | post_id | post = @posts[post_id] stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end def message(forum_id,msgnum) visit '/login' unless @@bbs @forum = @@bbs.jump(forum_id) post_ids = @forum.post_headers.keys.sort.reverse post_index = post_ids.index(msgnum) msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) msg_next = post_ids[post_index - 1] if post_index > 0 info post_ids.inspect info msgnum info msg_prev info msg_next @post = @forum.read(msgnum) stack :width => 700, :margin => 50 do background gold, :curve => 20 border black, :curve => 10 title "Message" tagline "#{@post.date} from #{@post.author}" para @post.body tagline "[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, " ", if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, " ", link("forum", :click => "/forum/#{forum_id}"), " ", link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}") ) # para @post.inspect end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") quote = "#{@post.author} wrote:\n#{old_body}\n\n" stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 title "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 title "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end Shoes.app :width => 800
edheil/shoesca
4e90079fcf3472e2b2569ebb99eb5c32357ae13a
"previous" and "next"
diff --git a/shoesca.rb b/shoesca.rb index a67bb48..9a44516 100644 --- a/shoesca.rb +++ b/shoesca.rb @@ -1,140 +1,159 @@ Shoes.setup do gem 'minter-raccdoc' end require 'raccdoc' require 'yaml/store' class RaccdocClient < Shoes url '/', :main url '/login', :login url '/forum/(\d+)', :forum url '/message/(\d+)/(\d+)', :message url '/new_post/(\d+)', :new_post url '/new_reply/(\d+)/(\d+)', :new_reply @@bbs = nil def login store = YAML::Store.new('bbsconfig.yaml') username, password = nil, nil store.transaction(true) do username, password = store['username'], store['password'] end - stack :width => 600, :margin => 50 do + stack :width => 700, :margin => 50 do background salmon, :curve => 20 border black, :curve => 20 title "Login" para "username:" @username_line = edit_line "#{ username }" para "password:" @password_line = edit_line "#{ password }", :secret => true button "login" do username = @username_line.text password = @password_line.text store.transaction do store['username'], store['password'] = username, password end @@bbs = Raccdoc::Connection.new(:user => username, :password => password) visit '/' end end end def main visit '/login' unless @@bbs - stack :width => 600, :margin => 50 do + stack :width => 700, :margin => 50 do background aliceblue, :curve => 20 border black, :curve => 20 title "Forums" forums = @@bbs.forums ordered_ids = forums.keys.sort { |a,b| forums[a][:name] <=> forums[b][:name] } ordered_ids.each do | id | data = forums[id] stack :width => 0.90, :margin => 3 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{id}> #{data[:name]}", :click => "/forum/#{id}") # para "#{data.inspect}" end end end end def forum(id) visit '/login' unless @@bbs @forum = @@bbs.jump(id) - stack :width => 600, :margin => 50 do + stack :width => 700, :margin => 50 do background blanchedalmond, :curve => 20 border black, :curve => 20 - title "#{id}> #{@forum.name}" + title "#{@forum.name}>" para "Admin is #{@forum.admin}." - para link("back", :click => "/") - para link("post", :click => "/new_post/#{id}") + para( link("back", :click => "/"), + " ", + link("post", :click => "/new_post/#{id}") ) @posts = @forum.post_headers @post_ids = @posts.keys.sort.reverse @post_ids.each do | post_id | post = @posts[post_id] stack :width => 0.90 do background lightgrey, :curve => 10 border black, :curve => 10 para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}") para post[:subject] end end end end def message(forum_id,msgnum) visit '/login' unless @@bbs - @post = @@bbs.jump(forum_id).read(msgnum) - stack :width => 600, :margin => 50 do + @forum = @@bbs.jump(forum_id) + post_ids = @forum.post_headers.keys.sort.reverse + post_index = post_ids.index(msgnum) + msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1) + msg_next = post_ids[post_index - 1] if post_index > 0 + info post_ids.inspect + info msgnum + info msg_prev + info msg_next + @post = @forum.read(msgnum) + stack :width => 700, :margin => 50 do background gold, :curve => 20 border black, :curve => 10 - title "#{msgnum} #{@post.date} #{@post.author}>" - para link("back", :click => "/forum/#{forum_id}") - para link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}") + title "Message" + tagline "#{@post.date} from #{@post.author}" para @post.body - para @post.inspect + tagline "[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]" + para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end, + " ", + if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end, + " ", + link("forum", :click => "/forum/#{forum_id}"), + " ", + link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}") ) + +# para @post.inspect end end def new_reply(forum_id, msgnum) visit '/login' unless @@bbs @post = @@bbs.jump(forum_id).read(msgnum) old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n") - stack :width => 600, :margin => 50 do + quote = "#{@post.author} wrote:\n#{old_body}\n\n" + stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 title "New Post" para link("back", :click => "/forum/#{forum_id}") - @post_box = edit_box old_body, :width => 500, :height => 300 + @post_box = edit_box quote, :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end def new_post(forum_id) visit '/login' unless @@bbs - stack :width => 600, :margin => 50 do + stack :width => 700, :margin => 50 do background lime, :curve => 20 border black, :curve => 10 title "New Post" para link("back", :click => "/forum/#{forum_id}") @post_box = edit_box :width => 500, :height => 300 button "post" do text = @post_box.text new_post = @@bbs.jump(forum_id).post(text) visit("/message/#{forum_id}/#{new_post.id}") end end end end -Shoes.app :width => 700 +Shoes.app :width => 800
LTS5/connectomeviewer
7dc71f0fe2c2b9117cba17a2ce2daf694d56e699
creating list from generator returned by networkx
diff --git a/cviewer/libs/pyconto/groupstatistics/nbs/_nbs.py b/cviewer/libs/pyconto/groupstatistics/nbs/_nbs.py index 7614790..3bdf5ad 100644 --- a/cviewer/libs/pyconto/groupstatistics/nbs/_nbs.py +++ b/cviewer/libs/pyconto/groupstatistics/nbs/_nbs.py @@ -1,344 +1,344 @@ import numpy as np import networkx as netwx def ttest2(X,Y): """ Compute the two-sided t-statistic of X,Y """ t = np.mean(X) - np.mean(Y) n1 = len(X) * 1. n2 = len(Y) * 1. s = np.sqrt( ( (n1-1) * np.var(X,ddof=1) + (n2-1)*np.var(Y,ddof=1) ) / (n1+n2-2.) ) t = t / (s*np.sqrt(1/n1+1/n2)) return t def compute_nbs(X, Y, THRESH, K = 1000, TAIL = 'both'): """ Computes the network-based statistic (NBS) as described in [1]. Performs the NBS for populations X and Y for a T-statistic threshold of THRESH. The third dimension of X and Y references a particular member of the populations. The first two dimensions reference the connectivity value of a particular edge comprising the connectivity matrix. For example, X[i,j,k] stores the connectivity value corresponding to the edge between i and j for the kth memeber of the population. PVAL is a vector of corrected p-values for each component identified. If at least one of the p-values is less than 0.05, then the omnibus null hypothesis can be rejected at 5% significance. The null hypothesis is that the value of connectivity at each edge comes from distributions of equal mean between the two populations. Parameters ---------- X, Y : ndarray THRES : float K : integer, default = 1000, optional. Enables specification of the number of permutations to be generated to estimate the empirical null distribution of maximal component size. TAIL : {'equal', 'left', 'right'}, optional Enables specification of the type of alternative hypothesis to test. If TAIL: 'equal' - alternative hypothesis is means are not equal (default) 'left' - mean of population X < mean of population Y 'right' - mean of population X > mean of population Y Returns ------- PVAL : ndarray p-values for each component ADJ : ndarray Returns an adjacency matrix identifying the edges comprising each component. Edges corresponding to the first p-value stored in the vector PVAL are assigned the value 1 in the adjacency matrix ADJ, edges corresponding to the second p-value are assigned the value 2, etc. NULL : ndarray Returns a vector of K samples from the the null distribution of maximal component size. ALGORITHM DESCRIPTION The NBS is a nonparametric statistical test used to isolate the components of an N x N undirected connectivity matrix that differ significantly between two distinct populations. Each element of the connectivity matrix stores a connectivity value and each member of the two populations possesses a distinct connectivity matrix. A component of a connectivity matrix is defined as a set of interconnected edges. The NBS is essentially a procedure to control the family-wise error rate, in the weak sense, when the null hypothesis is tested independently at each of the N(N-1)/2 edges comprising the connectivity matrix. The NBS can provide greater statistical power than conventional procedures for controlling the family-wise error rate, such as the false discovery rate, if the set of edges at which the null hypothesis is rejected constitues a large component or components. The NBS comprises fours steps: 1. Perfrom a two-sample T-test at each edge indepedently to test the hypothesis that the value of connectivity between the two populations come from distributions with equal means. 2. Threshold the T-statistic available at each edge to form a set of suprathreshold edges. 3. Identify any components in the adjacency matrix defined by the set of suprathreshold edges. These are referred to as observed components. Compute the size of each observed component identified; that is, the number of edges it comprises. 4. Repeat K times steps 1-3, each time randomly permuting members of the two populations and storing the size of the largest component identified for each permuation. This yields an empirical estimate of the null distribution of maximal component size. A corrected p-value for each observed component is then calculated using this null distribution. [1] Zalesky A, Fornito A, Bullmore ET (2010) Network-based statistic: Identifying differences in brain networks. NeuroImage. 10.1016/j.neuroimage.2010.06.041 Written by: Andrew Zalesky, [email protected] Rewritten for Python: Stephan Gerhard, [email protected] """ # check input matrices Ix,Jx,nx = X.shape Iy,Jy,ny = Y.shape assert Ix == Iy assert Jx == Jy assert Ix == Jx assert Iy == Jy # number of nodes N = Ix # Only consider elements above upper diagonal due to symmetry ind_mask = ( np.triu(np.ones( (N,N) ),1) == 1 ) ind_i, ind_j = np.nonzero( np.triu(np.ones( (N,N) ),1) ) # Number of edges M = N * (N - 1) / 2 # Look up table ind2ij = np.zeros( (M,2) , dtype = np.int16) ind2ij[:,0] = ind_i ind2ij[:,1] = ind_j # Vectorize connectivity matrices # Not necessary, but may speed up indexing # Uses more memory since cmat temporarily replicates X cmat = np.zeros( (M, nx) ) pmat = np.zeros( (M, ny) ) for i in range(nx): cmat[:,i] = X[ind2ij[:,0], ind2ij[:,1],i].ravel() for i in range(ny): pmat[:,i] = Y[ind2ij[:,0], ind2ij[:,1],i].ravel() # Perform T-test at each edge t_stat = np.zeros( M ) for i in range(M): # compute ttest2, assume independent random samples t = ttest2(cmat[i,:], pmat[i,:]) t_stat[i] = t if TAIL == 'both': t_stat = np.abs( t_stat ) elif TAIL == 'left': t_stat = -t_stat elif TAIL == 'right': pass else: raise('Tail option not recognized') # Threshold ind_t = np.where( t_stat > THRESH ) # Suprathreshold adjacency matrix ADJ = np.zeros( (N,N) ) reledg = ind2ij[ind_t[0]] # relevant edges ADJ[ reledg[:,0], reledg[:,1] ] = 1 # this yields a binary matrix, selecting the edges that are above threshold ADJ = ADJ + ADJ.T # Find network components G = netwx.from_numpy_matrix(ADJ) # Return connected components as subgraphs. - comp_list = netwx.connected_component_subgraphs(G) + comp_list = list(netwx.connected_component_subgraphs(G)) # store the number of edges for each subgraph component nr_edges_per_component = np.zeros( len(comp_list) ) nr_edges_per_component_bigenough = [] for idx, componentG in enumerate(comp_list): nr_edges_per_component[idx] = componentG.number_of_edges() # if number of edges bigger than zero if nr_edges_per_component[idx] > 0: nr_edges_per_component_bigenough.append(nr_edges_per_component[idx]) # store the number of edges of the component as value in the adjacency matrix for ed in componentG.edges(): ADJ[ed[0],ed[1]] = ADJ[ed[1],ed[0]] = idx + 1 # if we would like to store the number of edges per component # ADJ[ed[0],ed[1]] = ADJ[ed[1],ed[0]] = nr_edges_per_component[idx] # renaming sz_links = nr_edges_per_component_bigenough if len(sz_links) > 0: max_sz = np.max(sz_links) else: max_sz = 0 if False: # additionally, store all the components in the matrix with the value of their number of edges all_components = np.zeros( (N,N) ) for idx, componentG in enumerate(comp_list): tmp_max = netwx.to_numpy_matrix( componentG , nodelist = range(N) ) # set nonzero to number of edges tmp_max[tmp_max!=0.0] = componentG.number_of_edges() all_components[:,:] = all_components[:,:] + tmp_max print "Max component size is: %s" % max_sz # Empirically estimate null distribution of maximum component size by # generating K independent permutations. print "=====================================================" print "Estimating null distribution with permutation testing" print "=====================================================" hit=0.0 NULL = np.zeros( (K, 1) ) # stack matrices for permutation d_stacked = np.hstack( (cmat, pmat) ) for k in range(K): # Randomize indperm = np.random.permutation( nx+ny ) d = d_stacked[:, indperm].copy() ################# # Perform T-test at each edge t_stat_perm = np.zeros( M ) for i in range(M): # assume independent random samples t = ttest2(d[i,:nx], d[i,nx:nx+ny]) t_stat_perm[i] = t if TAIL == 'both': t_stat_perm = np.abs( t_stat_perm ) elif TAIL == 'left': t_stat_perm = -t_stat_perm elif TAIL == 'right': pass else: raise('Tail option not recognized') # Threshold ind_t = np.where( t_stat_perm > THRESH ) # Suprathreshold adjacency matrix adj_perm = np.zeros( (N,N) ) reledg = ind2ij[ind_t[0]] # relevant edges adj_perm[ reledg[:,0], reledg[:,1] ] = 1 # this yields a binary matrix, selecting the edges that are above threshold adj_perm = adj_perm + adj_perm.T # Find network components G = netwx.from_numpy_matrix(adj_perm) # Return connected components as subgraphs. - comp_list = netwx.connected_component_subgraphs(G) + comp_list = list(netwx.connected_component_subgraphs(G)) # store the number of edges for each subgraph component nr_edges_per_component = np.zeros( len(comp_list) ) for idx, componentG in enumerate(comp_list): nr_edges_per_component[idx] = componentG.number_of_edges() # more then one node (= at least one edge) nr_edges_per_component_bigenough = nr_edges_per_component[nr_edges_per_component>0] # renaming sz_links_perm = nr_edges_per_component_bigenough if len(sz_links_perm) > 0: sz_links_perm_max = np.max(sz_links_perm) else: sz_links_perm_max = 0 NULL[k] = sz_links_perm_max # if the component size of this random permutation is bigger than # the component size of the group difference computed above, this is a hit if NULL[k] >= max_sz: hit = hit + 1 print "Perm %d of %d. Perm max is: %d. Observed max is: %d. P-val estimate is: %0.3f" % ((k+1),K,NULL[k],max_sz,hit/(k+1)) # Calculate p-values for each component PVAL = np.zeros( len(sz_links) ) for i in range( len(sz_links) ): PVAL[i] = len( NULL[NULL >= sz_links[i]] ) * 1.0 / K return (PVAL, ADJ, NULL) def setdiff2d(X, Y): """ Differences of two index arrays Parameters ---------- X, Y : ndarray (n,2) arrays representing indices Returns ------- Z : ndarray array of elements in X, that are not in Y """ n = X.shape[0] m = Y.shape[0] Z = [] for i in xrange(n): test = X[i,:] hit = False for j in xrange(m): if test[0] == Y[j,0] and test[1] == Y[j,1]: hit = True break if not hit: Z.append(test) return np.array(Z) def intersect2d(X, Y): """ Intersection of two index arrays Parameters ---------- X, Y : ndarray (n,2) arrays representing indices Returns ------- Z : ndarray array of elements in X, that are also in Y """ n = X.shape[0] m = Y.shape[0] Z = [] for i in xrange(n): test = X[i,:] hit = False for j in xrange(m): if test[0] == Y[j,0] and test[1] == Y[j,1]: hit = True break if hit: Z.append(test) return np.array(Z)
LTS5/connectomeviewer
9614b92a8dc70075885dc78499d70d3950adff85
Fix the File Open dialog that does not show
diff --git a/cviewer/action/load_cff.py b/cviewer/action/load_cff.py index f86d3f1..9d18e2a 100644 --- a/cviewer/action/load_cff.py +++ b/cviewer/action/load_cff.py @@ -1,242 +1,242 @@ """ Helper class to load CFF files """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library imports import os.path # Enthought library imports from apptools.io.api import File from traits.api import Str, Bool from pyface.action.api import Action from pyface.api import FileDialog, OK from pyface.image_resource import ImageResource # Connectome Viewer imports from common import IMAGE_PATH from cviewer.plugins.ui.preference_manager import preference_manager import cfflib # Logging imports import logging logger = logging.getLogger('root.'+__name__) class OpenFile(Action): name = "Open file" description = "Open the File Dialog where you can select a neuroimaging file" tooltip = "Open file" path = Str("MenuBar/File/LoadDataMenu") image = ImageResource("cff-open.png", search_path=[IMAGE_PATH]) # Is the action enabled? enabled = Bool(True) # Is the action visible? visible = Bool(True) ########################################################################### # 'Action' interface. ########################################################################### def perform(self, event, cfile=None): """ Performs the action. """ logger.info('Performing open connectome file action') # helper variable to use this function not only in the menubar exec_as_funct = True if cfile is None: # get the instance of the current CFile # with the help of the Service Registry cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') exec_as_funct = False - wildcard = "All files (*.*)|*.*" \ + wildcard = "All files (*.*)|*.*|" \ "Nifti-1 (*.nii.gz)|*.nii.gz|" \ "Gifti (*.gii)|*.gii|" \ "TrackVis tracks (*.trk)|*.trk|" \ "Network Pickle (*.gpickle)|*.gpickle|" \ "Network GraphML (*.graphml)|*.graphml|" \ "Numpy Data (*.npy)|*.npy|" \ "Pickle Data (*.pkl)|*.pkl|" \ "Text Data (*.txt)|*.txt|" \ "CSV Data (*.csv)|*.csv|" dlg = FileDialog(wildcard=wildcard,title="Choose a file",\ resizeable=False, \ default_directory=preference_manager.cviewerui.cffpath,) if dlg.open() == OK: if not os.path.isfile(dlg.path): logger.error("File '%s' does not exist!"%dlg.path) return logger.info('Read file: %s'%dlg.path) fname = os.path.split(dlg.paths[0])[-1] if os.path.exists(dlg.paths[0]) and (fname.endswith('.nii.gz') or fname.endswith('.nii')): cvol = cfflib.CVolume.create_from_nifti( name = fname,nii_filename = dlg.paths[0]) cfile.obj.add_connectome_volume(cvol) elif os.path.exists(dlg.paths[0]) and fname.endswith('.gii'): csurf = cfflib.CSurface.create_from_gifti( name = fname, gii_filename = dlg.paths[0]) cfile.obj.add_connectome_surface(csurf) elif os.path.exists(dlg.paths[0]) and fname.endswith('.trk'): ctrk = cfflib.CTrack( name = fname, src = dlg.paths[0]) cfile.obj.add_connectome_track(ctrk) elif os.path.exists(dlg.paths[0]) and fname.endswith('.gpickle'): ctrk = cfflib.CNetwork(name = fname, src = dlg.paths[0], fileformat="NXGPickle") cfile.obj.add_connectome_network(ctrk) elif os.path.exists(dlg.paths[0]) and fname.endswith('.graphml'): ctrk = cfflib.CNetwork.create_from_graphml(name = fname, ml_filename = dlg.paths[0]) cfile.obj.add_connectome_network(ctrk) elif os.path.exists(dlg.paths[0]) and fname.endswith('.npy'): cdat = cfflib.CData(name = fname, src = dlg.paths[0], fileformat = 'NumPy') cfile.obj.add_connectome_data(cdat) elif os.path.exists(dlg.paths[0]) and fname.endswith('.csv'): cdat = cfflib.CData(name = fname, src = dlg.paths[0], fileformat = 'CSV') cfile.obj.add_connectome_data(cdat) elif os.path.exists(dlg.paths[0]) and fname.endswith('.txt'): cdat = cfflib.CData(name = fname, src = dlg.paths[0], fileformat = 'TXT') cfile.obj.add_connectome_data(cdat) elif os.path.exists(dlg.paths[0]) and fname.endswith('.pkl'): cdat = cfflib.CData(name = fname, src = dlg.paths[0], fileformat = 'Pickle') cfile.obj.add_connectome_data(cdat) else: logger.info('Could not load file: '+ dlg.paths) cfile.update_children() ###################################################################### # `OpenCFFFile` class. ###################################################################### class OpenCFile(Action): """ An action that opens a data file depending on the supported extensions. """ name = "Open CFF File" description = "Open the File Dialog where you can select a .cff or meta.cml file" tooltip = "Open a CFF file" path = Str("MenuBar/File/LoadDataMenu") image = ImageResource("cff-open.png", search_path=[IMAGE_PATH]) # Is the action enabled? enabled = Bool(True) # Is the action visible? visible = Bool(True) ########################################################################### # 'Action' interface. ########################################################################### def perform(self, event, cfile=None): """ Performs the action. """ logger.info('Performing open connectome file action') # helper variable to use this function not only in the menubar exec_as_funct = True if cfile is None: # get the instance of the current CFile # with the help of the Service Registry cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') exec_as_funct = False wildcard = "Connectome Markup File v2.0 (meta.cml)|meta.cml|" \ "Connectome File Format v2.0 (*.cff)|*.cff|" \ "All files (*.*)|*.*" dlg = FileDialog(wildcard=wildcard,title="Choose a Connectome File",\ resizeable=False, \ default_directory=preference_manager.cviewerui.cffpath,) if dlg.open() == OK: if not os.path.isfile(dlg.path): logger.error("File '%s' does not exist!"%dlg.path) return # if file exists and has .cff ending if os.path.exists(dlg.paths[0]) and (dlg.paths[0]).endswith('.cff'): # close the cfile if one is currently loaded cfile.close_cfile() # load cfile data cfile.load_cfile(dlg.paths[0]) self.window.status_bar_manager.message='' elif os.path.exists(dlg.paths[0]) and (dlg.paths[0]).endswith('meta.cml'): cfile.close_cfile() cfile.load_cfile(dlg.paths[0], ismetacml = True) else: logger.info('Could not load file: '+ dlg.paths) class SaveCFile(Action): """ An action that save aconnectome file """ name = "Save CFF File" description = "Save the connectome file" tooltip = "Save a CFF file" path = Str("MenuBar/File/LoadDataMenu") image = ImageResource("cff-open.png", search_path=[IMAGE_PATH]) # Is the action enabled? enabled = Bool(True) # Is the action visible? visible = Bool(True) ########################################################################### # 'Action' interface. ########################################################################### def perform(self, event, cfile=None): """ Performs the action. """ logger.info('Performing save connectome file action') # helper variable to use this function not only in the menubar exec_as_funct = True cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') wildcard = "Connectome File Format v2.0 (*.cff)|*.cff|" \ "All files (*.*)|*.*" dlg = FileDialog(wildcard=wildcard,title="Save as Connectome File",\ resizeable=False, action = 'save as',\ default_directory=preference_manager.cviewerui.cffpath,) if dlg.open() == OK: if (dlg.paths[0]).endswith('.cff'): cfflib.save_to_cff(cfile.obj, dlg.paths[0]) logger.info("Saved connectome file to %s" % dlg.paths[0])
LTS5/connectomeviewer
715aae1b7210529270c39515713faa9e5c9970f1
Read other data files more easily
diff --git a/cviewer/action/load_cff.py b/cviewer/action/load_cff.py index 3efd813..079910d 100644 --- a/cviewer/action/load_cff.py +++ b/cviewer/action/load_cff.py @@ -1,144 +1,242 @@ """ Helper class to load CFF files """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library imports import os.path # Enthought library imports from enthought.io.api import File from enthought.traits.api import Str, Bool from enthought.pyface.action.api import Action from enthought.pyface.api import FileDialog, OK from enthought.pyface.image_resource import ImageResource # Connectome Viewer imports from common import IMAGE_PATH from cviewer.plugins.ui.preference_manager import preference_manager import cfflib # Logging imports import logging logger = logging.getLogger('root.'+__name__) - + +class OpenFile(Action): + name = "Open file" + description = "Open the File Dialog where you can select a neuroimaging file" + tooltip = "Open file" + path = Str("MenuBar/File/LoadDataMenu") + image = ImageResource("cff-open.png", search_path=[IMAGE_PATH]) + + # Is the action enabled? + enabled = Bool(True) + + # Is the action visible? + visible = Bool(True) + + ########################################################################### + # 'Action' interface. + ########################################################################### + def perform(self, event, cfile=None): + """ Performs the action. """ + + logger.info('Performing open connectome file action') + + # helper variable to use this function not only in the menubar + exec_as_funct = True + + if cfile is None: + # get the instance of the current CFile + # with the help of the Service Registry + cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') + exec_as_funct = False + + wildcard = "Nifti-1 (*.nii.gz)|*.nii.gz|" \ + "Gifti (*.gii)|*.gii|" \ + "TrackVis tracks (*.trk)|*.trk|" \ + "Network Pickle (*.gpickle)|*.gpickle|" \ + "Network GraphML (*.graphml)|*.graphml|" \ + "Numpy Data (*.npy)|*.npy|" \ + "Pickle Data (*.pkl)|*.pkl|" \ + "Text Data (*.txt)|*.txt|" \ + "CSV Data (*.csv)|*.csv|" \ + "All files (*.*)|*.*" + dlg = FileDialog(wildcard=wildcard,title="Choose a file",\ + resizeable=False, \ + default_directory=preference_manager.cviewerui.cffpath,) + + if dlg.open() == OK: + + if not os.path.isfile(dlg.path): + logger.error("File '%s' does not exist!"%dlg.path) + return + + logger.info('Read file: %s'%dlg.path) + fname = os.path.split(dlg.paths[0])[-1] + + if os.path.exists(dlg.paths[0]) and (fname.endswith('.nii.gz') or + fname.endswith('.nii')): + cvol = cfflib.CVolume.create_from_nifti( + name = fname,nii_filename = dlg.paths[0]) + cfile.obj.add_connectome_volume(cvol) + + elif os.path.exists(dlg.paths[0]) and fname.endswith('.gii'): + csurf = cfflib.CSurface.create_from_gifti( + name = fname, gii_filename = dlg.paths[0]) + cfile.obj.add_connectome_surface(csurf) + + # these assume internal knowledge of how cfflib works + elif os.path.exists(dlg.paths[0]) and fname.endswith('.trk'): + ctrk = cfflib.CTrack( + name = fname, src = dlg.paths[0]) + cfile.obj.add_connectome_track(ctrk) + + elif os.path.exists(dlg.paths[0]) and fname.endswith('.gpickle'): + ctrk = cfflib.CNetwork(name = fname, src = dlg.paths[0], + fileformat="NXGPickle") + cfile.obj.add_connectome_network(ctrk) + + elif os.path.exists(dlg.paths[0]) and fname.endswith('.graphml'): + ctrk = cfflib.CNetwork.create_from_graphml(name = fname, + ml_filename = dlg.paths[0]) + cfile.obj.add_connectome_network(ctrk) + + elif os.path.exists(dlg.paths[0]) and fname.endswith('.npy'): + cdat = cfflib.CData(name = fname, src = dlg.paths[0], + fileformat = 'NumPy') + cfile.obj.add_connectome_data(cdat) + + elif os.path.exists(dlg.paths[0]) and fname.endswith('.csv'): + cdat = cfflib.CData(name = fname, src = dlg.paths[0], + fileformat = 'CSV') + cfile.obj.add_connectome_data(cdat) + + elif os.path.exists(dlg.paths[0]) and fname.endswith('.txt'): + cdat = cfflib.CData(name = fname, src = dlg.paths[0], + fileformat = 'TXT') + cfile.obj.add_connectome_data(cdat) + + elif os.path.exists(dlg.paths[0]) and fname.endswith('.pkl'): + cdat = cfflib.CData(name = fname, src = dlg.paths[0], + fileformat = 'Pickle') + cfile.obj.add_connectome_data(cdat) + + else: + logger.info('Could not load file: '+ dlg.paths) + + cfile.update_children() + ###################################################################### # `OpenCFFFile` class. ###################################################################### class OpenCFile(Action): """ An action that opens a data file depending on the supported extensions. """ name = "Open CFF File" description = "Open the File Dialog where you can select a .cff or meta.cml file" tooltip = "Open a CFF file" path = Str("MenuBar/File/LoadDataMenu") image = ImageResource("cff-open.png", search_path=[IMAGE_PATH]) # Is the action enabled? enabled = Bool(True) # Is the action visible? visible = Bool(True) ########################################################################### # 'Action' interface. ########################################################################### def perform(self, event, cfile=None): """ Performs the action. """ - + logger.info('Performing open connectome file action') - + # helper variable to use this function not only in the menubar exec_as_funct = True - + if cfile is None: # get the instance of the current CFile # with the help of the Service Registry cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') exec_as_funct = False - + wildcard = "Connectome Markup File v2.0 (meta.cml)|meta.cml|" \ "Connectome File Format v2.0 (*.cff)|*.cff|" \ - "Nifti-1 (*.nii.gz)|*.nii.gz|" \ "All files (*.*)|*.*" dlg = FileDialog(wildcard=wildcard,title="Choose a Connectome File",\ resizeable=False, \ default_directory=preference_manager.cviewerui.cffpath,) - + if dlg.open() == OK: - + if not os.path.isfile(dlg.path): logger.error("File '%s' does not exist!"%dlg.path) return - + # if file exists and has .cff ending if os.path.exists(dlg.paths[0]) and (dlg.paths[0]).endswith('.cff'): - + # close the cfile if one is currently loaded cfile.close_cfile() - + # load cfile data cfile.load_cfile(dlg.paths[0]) - + self.window.status_bar_manager.message='' elif os.path.exists(dlg.paths[0]) and (dlg.paths[0]).endswith('meta.cml'): cfile.close_cfile() cfile.load_cfile(dlg.paths[0], ismetacml = True) - elif os.path.exists(dlg.paths[0]) and (dlg.paths[0]).endswith('.nii.gz'): - cvol = cfflib.CVolume(name="xxx", - src=os.path.join('QBALL.nii.gz'), - fileformat='Nifti1GZ') - cfile.obj.add_connectome_volume(cvol) - else: logger.info('Could not load file: '+ dlg.paths) - - + + class SaveCFile(Action): """ An action that save aconnectome file """ name = "Save CFF File" description = "Save the connectome file" tooltip = "Save a CFF file" path = Str("MenuBar/File/LoadDataMenu") image = ImageResource("cff-open.png", search_path=[IMAGE_PATH]) # Is the action enabled? enabled = Bool(True) # Is the action visible? visible = Bool(True) ########################################################################### # 'Action' interface. ########################################################################### def perform(self, event, cfile=None): """ Performs the action. """ logger.info('Performing save connectome file action') # helper variable to use this function not only in the menubar exec_as_funct = True cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') wildcard = "Connectome File Format v2.0 (*.cff)|*.cff|" \ "All files (*.*)|*.*" dlg = FileDialog(wildcard=wildcard,title="Save as Connectome File",\ resizeable=False, action = 'save as',\ default_directory=preference_manager.cviewerui.cffpath,) if dlg.open() == OK: if (dlg.paths[0]).endswith('.cff'): cfflib.save_to_cff(cfile.obj, dlg.paths[0]) logger.info("Saved connectome file to %s" % dlg.paths[0]) diff --git a/cviewer/plugins/ui/cviewer_ui_action_set.py b/cviewer/plugins/ui/cviewer_ui_action_set.py index 95d801b..95e72fd 100644 --- a/cviewer/plugins/ui/cviewer_ui_action_set.py +++ b/cviewer/plugins/ui/cviewer_ui_action_set.py @@ -1,268 +1,277 @@ """Connectome Viewer action set for menus and actions """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Partly added actions from mayavi_ui_action_set.py # Author: Prabhu Ramachandran <prabhu [at] aero . iitb . ac . in> # Copyright (c) 2008, Enthought, Inc. # License: BSD Style. # Enthought library imports. from enthought.envisage.ui.action.api import Action, Group, Menu, ToolBar from enthought.envisage.ui.workbench.api import WorkbenchActionSet from enthought.mayavi.core.registry import registry ######################################## # Groups file_group = Group( id='ConnectomeFileGroup', path='MenuBar/File', before='ExitGroup' ) visualize_group = Group( id='VisualizeGroup', path='MenuBar/VisualizeMenu', ) modules_group = Group( id='ModulesGroup', path='MenuBar/VisualizeMenu/ModulesMenu', ) filters_group = Group( id='FiltersGroup', path='MenuBar/VisualizeMenu/FiltersMenu', ) ######################################## # Menus open_menu = Menu( id = "LoadDataMenu", name = "&Load data", path = 'MenuBar/File', group = 'ConnectomeFileGroup' ) visualize_menu = Menu( id = "VisualizeMenu", name = "Visuali&ze", path = "MenuBar", before = "View" ) modules_menu = Menu( id = "ModulesMenu", name = "&Modules", path = "MenuBar/VisualizeMenu", ) filters_menu = Menu( id = "FiltersMenu", name = "&Filters", path = "MenuBar/VisualizeMenu", after = "ModulesMenu", ) plugins_menu = Menu( id = "PluginsMenu", name = "&Plugins", path = "MenuBar", before = "Help" ) #################### # Source actions. # MODIFY open_file = Action( id = "OpenFile", class_name = "enthought.mayavi.action.sources.OpenFile", name = "&Open file ...", path = "MenuBar/File/LoadDataMenu" ) +open_file2 = Action( + id = "ConnectomeFile", + name = "&Open data file ...", + class_name = "cviewer.action.load_cff:" + "OpenFile", + path = "MenuBar/File", + group = 'ConnectomeFileGroup', + before = "LoadDataMenu" +) open_cff = Action( id = "ConnectomeFile", name = "&Open Connectome File ...", class_name = "cviewer.action.load_cff:" "OpenCFile", path = "MenuBar/File", group = 'ConnectomeFileGroup', before = "LoadDataMenu" ) save_cff = Action( id = "ConnectomeFileSave", name = "&Save Connectome File ...", class_name = "cviewer.action.load_cff:" "SaveCFile", path = "MenuBar/File", group = 'ConnectomeFileGroup', before = "LoadDataMenu" ) -SOURCE_ACTIONS = [open_cff, save_cff, open_file] +SOURCE_ACTIONS = [open_file2, open_cff, save_cff, open_file] # #for src in registry.sources: # if len(src.extensions) == 0: # action = Action(id=src.id, # class_name="enthought.mayavi.action.sources." + src.id, # name= src.menu_name, # path="MenuBar/File/LoadDataMenu" # ) # SOURCE_ACTIONS.append(action) #################### # Save/load actions. save_viz = Action( id = "SaveVisualization", class_name = "enthought.mayavi.action.save_load.SaveVisualization", name = "&Save Visualization", group = "ConnectomeFileGroup", path = "MenuBar/File", ) load_viz = Action( id = "LoadVisualization", class_name = "enthought.mayavi.action.save_load.LoadVisualization", name = "&Load Visualization", group = "ConnectomeFileGroup", path = "MenuBar/File", ) #### # Building a schedule manager, might become a plugin run_script = Action( id = "RunScript", class_name = "cviewer.action.run_script.RunScript", name = "&Run Python Script", path = "MenuBar/PluginsMenu/Scheduler", ) ######################################## # Visualize menu items. add_mm = Action( id = "AddModuleManager", class_name = "enthought.mayavi.action.modules.AddModuleManager", name = "&Add ModuleManager", path="MenuBar/VisualizeMenu", after="FiltersMenu" ) ######################################## # Modules. MODULE_ACTIONS = [] for module in registry.modules: action = Action(id=module.id, class_name="enthought.mayavi.action.modules." + module.id, name= module.menu_name, group = "ModulesGroup", path="MenuBar/VisualizeMenu/ModulesMenu" ) MODULE_ACTIONS.append(action) ######################################## # Filter items. ######################################## FILTER_ACTIONS = [] for filter in registry.filters: action = Action(id=filter.id, class_name="enthought.mayavi.action.filters." + filter.id, name= filter.menu_name, group = "FiltersGroup", path="MenuBar/VisualizeMenu/FiltersMenu" ) FILTER_ACTIONS.append(action) ######################################## # Help menu items. help_cviewer = Action( id = "HelpCViewer", class_name = "cviewer.action.help.HelpIndex", name = "User Guide &Connectome Viewer", path = "MenuBar/Help" ) help_index = Action( id = "HelpIndex", class_name = "enthought.mayavi.action.help.HelpIndex", name = "User Guide &MayaVi2", path = "MenuBar/Help" ) bugfix = Action( id = "Bugfix", class_name = "cviewer.action.help.Bugfix", name = "&Report Bugs ...", path = "MenuBar/Help" ) keybindings = Action( id = "Keybindings", class_name = "cviewer.action.help.Keybindings", name = "&Key Bindings", path = "MenuBar/Help" ) tvtk_class_browser = Action( id = "TVTKClassBrowser", class_name = "enthought.mayavi.action.help.TVTKClassBrowser", name = "&VTK Class Browser", path = "MenuBar/Help", ) ################################################################################ # `CViewerUIActionSet` class. ################################################################################ class CViewerUIActionSet(WorkbenchActionSet): """ All the default actions available in the Connectome Viewer UI """ id = "cviewer.plugins.ui.action_set" groups = [file_group, visualize_group, modules_group, filters_group, #plugins_group, ] menus = [open_menu, visualize_menu, modules_menu, filters_menu, plugins_menu, ] actions = SOURCE_ACTIONS + \ [save_viz, # Save load actions. load_viz, run_script, # Add module manager. add_mm, ] + \ MODULE_ACTIONS + \ FILTER_ACTIONS + \ [help_cviewer, help_index, bugfix, keybindings, tvtk_class_browser, ]
LTS5/connectomeviewer
25e884d99fd1a32466eb8cc30c8662b3e2c30ad9
Connectome object
diff --git a/cviewer/action/load_cff.py b/cviewer/action/load_cff.py index 83daa4a..3efd813 100644 --- a/cviewer/action/load_cff.py +++ b/cviewer/action/load_cff.py @@ -1,136 +1,144 @@ """ Helper class to load CFF files """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library imports import os.path # Enthought library imports from enthought.io.api import File from enthought.traits.api import Str, Bool from enthought.pyface.action.api import Action from enthought.pyface.api import FileDialog, OK from enthought.pyface.image_resource import ImageResource # Connectome Viewer imports from common import IMAGE_PATH from cviewer.plugins.ui.preference_manager import preference_manager import cfflib # Logging imports import logging logger = logging.getLogger('root.'+__name__) ###################################################################### # `OpenCFFFile` class. ###################################################################### class OpenCFile(Action): """ An action that opens a data file depending on the supported extensions. """ name = "Open CFF File" description = "Open the File Dialog where you can select a .cff or meta.cml file" tooltip = "Open a CFF file" path = Str("MenuBar/File/LoadDataMenu") image = ImageResource("cff-open.png", search_path=[IMAGE_PATH]) # Is the action enabled? enabled = Bool(True) # Is the action visible? visible = Bool(True) ########################################################################### # 'Action' interface. ########################################################################### def perform(self, event, cfile=None): """ Performs the action. """ logger.info('Performing open connectome file action') # helper variable to use this function not only in the menubar exec_as_funct = True if cfile is None: # get the instance of the current CFile # with the help of the Service Registry cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') exec_as_funct = False wildcard = "Connectome Markup File v2.0 (meta.cml)|meta.cml|" \ "Connectome File Format v2.0 (*.cff)|*.cff|" \ + "Nifti-1 (*.nii.gz)|*.nii.gz|" \ "All files (*.*)|*.*" dlg = FileDialog(wildcard=wildcard,title="Choose a Connectome File",\ resizeable=False, \ default_directory=preference_manager.cviewerui.cffpath,) if dlg.open() == OK: if not os.path.isfile(dlg.path): logger.error("File '%s' does not exist!"%dlg.path) return # if file exists and has .cff ending if os.path.exists(dlg.paths[0]) and (dlg.paths[0]).endswith('.cff'): # close the cfile if one is currently loaded cfile.close_cfile() # load cfile data cfile.load_cfile(dlg.paths[0]) self.window.status_bar_manager.message='' elif os.path.exists(dlg.paths[0]) and (dlg.paths[0]).endswith('meta.cml'): cfile.close_cfile() cfile.load_cfile(dlg.paths[0], ismetacml = True) + + elif os.path.exists(dlg.paths[0]) and (dlg.paths[0]).endswith('.nii.gz'): + cvol = cfflib.CVolume(name="xxx", + src=os.path.join('QBALL.nii.gz'), + fileformat='Nifti1GZ') + cfile.obj.add_connectome_volume(cvol) + else: logger.info('Could not load file: '+ dlg.paths) class SaveCFile(Action): """ An action that save aconnectome file """ name = "Save CFF File" description = "Save the connectome file" tooltip = "Save a CFF file" path = Str("MenuBar/File/LoadDataMenu") image = ImageResource("cff-open.png", search_path=[IMAGE_PATH]) # Is the action enabled? enabled = Bool(True) # Is the action visible? visible = Bool(True) ########################################################################### # 'Action' interface. ########################################################################### def perform(self, event, cfile=None): """ Performs the action. """ logger.info('Performing save connectome file action') # helper variable to use this function not only in the menubar exec_as_funct = True cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') wildcard = "Connectome File Format v2.0 (*.cff)|*.cff|" \ "All files (*.*)|*.*" dlg = FileDialog(wildcard=wildcard,title="Save as Connectome File",\ resizeable=False, action = 'save as',\ default_directory=preference_manager.cviewerui.cffpath,) if dlg.open() == OK: if (dlg.paths[0]).endswith('.cff'): cfflib.save_to_cff(cfile.obj, dlg.paths[0]) logger.info("Saved connectome file to %s" % dlg.paths[0]) diff --git a/cviewer/plugins/cff2/cfile.py b/cviewer/plugins/cff2/cfile.py index 2d287d6..071ad2f 100644 --- a/cviewer/plugins/cff2/cfile.py +++ b/cviewer/plugins/cff2/cfile.py @@ -1,231 +1,233 @@ """ The class for the main data object holding all information about a loaded connectome file """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library imports import os, os.path import tempfile from threading import Thread # Enthought library imports from enthought.traits.api import HasTraits, Instance, Any, Str, File, List, Bool, Property, cached_property # ConnectomeViewer imports from cmetadata import CMetadata from cnetwork import CNetwork from csurface import CSurface from cvolume import CVolume from ctimeseries import CTimeseries from cdata import CData from cscript import CScript from cimagestack import CImagestack from ctrack import CTrack import cfflib # Logging imports import logging logger = logging.getLogger('root.'+__name__) ###################################################################### # CFile` class. ###################################################################### class CFile(HasTraits): """This is a wrapper class for a connectome file """ # The name of the selected cff file file_name = File # Full pathname to file including filename fullpathtofile = Str # standard name dname = Str('Connectome File') obj = Instance(cfflib.connectome) ####################################### # Private traits. ####################################### # zipfile _filezip = Any # data loaded _data_loaded = Bool(False) # reference to the current window for statusbar updates # not nice MVC-style _workbenchwin = Instance('enthought.pyface.workbench.api.WorkbenchWindow') connectome_meta = Property(Any) connectome_network = Property(List) connectome_surface = Property(List) connectome_volume = Property(List) connectome_track = Property(List) connectome_timeserie = Property(List) connectome_data = Property(List) connectome_script = Property(List) connectome_imagestack = Property(List) children = List def _obj_changed(self): self.update_children() def update_children(self): # remove all internal structures self._connectome_surface = None self._connectome_network = None self._connectome_volume = None self._connectome_track = None self._connectome_timeserie = None self._connectome_data = None self._connectome_script = None self._connectome_imagestack = None self.children = self.connectome_network + self.connectome_surface + \ self.connectome_volume + self.connectome_track + \ self.connectome_timeserie + self.connectome_data + \ self.connectome_script + self.connectome_imagestack def _get_connectome_meta(self): if self.obj is None: return None else: return CMetadata(obj=self.obj.connectome_meta) def _get_connectome_network(self): if self.obj is None: return [] else: if self._connectome_network is None: self._connectome_network = [CNetwork(obj=ele) for ele in self.obj.connectome_network] return self._connectome_network else: return self._connectome_network def _get_connectome_surface(self): if self.obj is None: return [] else: if self._connectome_surface is None: self._connectome_surface = [CSurface(obj=ele) for ele in self.obj.connectome_surface] return self._connectome_surface else: return self._connectome_surface def _get_connectome_volume(self): if self.obj is None: return [] else: if self._connectome_volume is None: self._connectome_volume = [CVolume(obj=ele) for ele in self.obj.connectome_volume] return self._connectome_volume else: return self._connectome_volume def _get_connectome_track(self): if self.obj is None: return [] else: if self._connectome_track is None: self._connectome_track = [CTrack(obj=ele) for ele in self.obj.connectome_track] return self._connectome_track else: return self._connectome_track def _get_connectome_timeserie(self): if self.obj is None: return [] else: if self._connectome_timeserie is None: self._connectome_timeserie = [CTimeseries(obj=ele) for ele in self.obj.connectome_timeseries] return self._connectome_timeserie else: return self._connectome_timeserie def _get_connectome_data(self): if self.obj is None: return [] else: if self._connectome_data is None: self._connectome_data = [CData(obj=ele) for ele in self.obj.connectome_data] return self._connectome_data else: return self._connectome_data def _get_connectome_script(self): if self.obj is None: return [] else: if self._connectome_script is None: self._connectome_script = [CScript(obj=ele) for ele in self.obj.connectome_script] return self._connectome_script else: return self._connectome_script def _get_connectome_imagestack(self): if self.obj is None: return [] else: if self._connectome_imagestack is None: self._connectome_imagestack = [CImagestack(obj=ele) for ele in self.obj.connectome_imagestack] return self._connectome_imagestack else: return self._connectome_imagestack ###################################################################### # `object` interface. ###################################################################### def __init__(self, **traits): super(CFile, self).__init__(**traits) self._connectome_surface = None self._connectome_network = None self._connectome_volume = None self._connectome_track = None self._connectome_timeserie = None self._connectome_data = None self._connectome_script = None self._connectome_imagestack = None + + self.obj = cfflib.connectome() def load_cfile(self, filepath, ismetacml = False): """ Load a given cfile as path and initializes the attributes """ if not os.path.isfile(filepath): logger.error('Not existing file: %s' %filepath) return # set the fullpath to internal trait self.fullpathtofile = filepath # set the file name and make it visible in the TraitsUIView self.file_name = os.path.split(filepath)[1] self.obj = cfflib.load(filepath) def close_cfile(self): # if not self.obj.iszip: # logger.info("Save connectome file data.") pass # save all the objects # remove all the lists def show_surface(self): # invokes a code oracle # get loaded surfaces from cviewer.plugins.codeoracle.csurface_action import SurfaceParameter so = SurfaceParameter() so.edit_traits() \ No newline at end of file diff --git a/cviewer/plugins/cff2/ui/cff_view.py b/cviewer/plugins/cff2/ui/cff_view.py index 34ea745..6cdfb0d 100644 --- a/cviewer/plugins/cff2/ui/cff_view.py +++ b/cviewer/plugins/cff2/ui/cff_view.py @@ -1,193 +1,194 @@ """ The Connectome File View as a Tree Structure """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library import import os, os.path # Enthought library imports from enthought.traits.api import Instance, HasTraits, Any, Delegate, List, Either, Property from enthought.pyface.image_cache import ImageCache from enthought.traits.ui.api import (Item, TreeEditor, TreeNode, View, Handler, UIInfo) from enthought.pyface.image_resource import ImageResource from enthought.pyface.api import FileDialog, OK from enthought.pyface.action.api import Action # ConnectomeViewer imports from cviewer.plugins.cff2.cnetwork import CNetwork from cviewer.plugins.cff2.cfile import CFile from cviewer.plugins.cff2.csurface import CSurface from cnetwork_tree_node import CNetworkTreeNode from csurface_tree_node import CSurfaceTreeNode from cfile_tree_node import CFileTreeNode from cdata_tree_node import CDataTreeNode from cimagestack_tree_node import CImagestackTreeNode from cscript_tree_node import CScriptTreeNode from ctimeseries_tree_node import CTimeseriesTreeNode from cvolume_tree_node import CVolumeTreeNode from ctrack_tree_node import CTrackTreeNode from csurface_darray_tree_node import CSurfaceDarrayTreeNode from cviewer.action.common import IMAGE_PATH # Logging import import logging logger = logging.getLogger('root.'+__name__) class CFFViewHandler(Handler): """ A handler for the CFFView object """ def _on_dclick(self, object): """ Called when a node in the tree is double-clicked. """ if isinstance(object, CFile): pass else: if not object.loaded: object.load() else: object.close() # if isinstance(object, CNetwork): # logger.info("Network doubleclicked") # else: # pass ############################################################################## # CFFView class. ############################################################################## class CFFView(HasTraits): """ A view displaying the cfile's object tree. """ # The connectome file we are viewing cfile = Instance(CFile, allow_none=True) # Path used to search for images _image_path = [IMAGE_PATH, ] # The icon of the dialog icon = ImageResource('favicon.ico', search_path=_image_path) # Nodes on the tree nodes = Any # TreeEditor tree_editor = Instance(TreeEditor) # render actions #renderactions = List(Action) # childrenlist = Property(List, depends_on = ['cfile'] ) # # def _get_childrenlist(self): # print "get childrenlist" # return self.cfile.connectome_network ########################################################################### # `object` interface. ########################################################################### def __init__(self, **traits): super(CFFView, self).__init__(**traits) + ########################################################################### # `HasTraits` interface. ########################################################################### def default_traits_view(self): """ The Connectome File Tree View """ view = View(Item(name='cfile', id='cfile', editor=self.tree_editor, resizable=True, show_label=False), id='cviewer.plugins.cff2.cfile', help=False, resizable=True, scrollable=True, undo=False, revert=False, ok=False, cancel=False, icon=self.icon, title = 'Connectome File View', handler=CFFViewHandler) return view def _nodes_default(self): """ The default value of the cached nodes list. """ # Now setup the view. nodes = [ CFileTreeNode( node_for=[CFile], children='children', icon_path=IMAGE_PATH, ), CNetworkTreeNode( children='', icon_path=IMAGE_PATH, auto_open=False, ), CSurfaceTreeNode( children='children', icon_path=IMAGE_PATH, auto_open=True, ), CSurfaceDarrayTreeNode( children='', icon_path=IMAGE_PATH, auto_open=False, ), CDataTreeNode( children='', icon_path=IMAGE_PATH, auto_open=False, ), CScriptTreeNode( children='', icon_path=IMAGE_PATH, auto_open=False, ), CVolumeTreeNode( children='', icon_path=IMAGE_PATH, auto_open=False, ), CTimeseriesTreeNode( children='', icon_path=IMAGE_PATH, auto_open=False, ), CImagestackTreeNode( children='', icon_path=IMAGE_PATH, auto_open=False, ), CTrackTreeNode( children='', icon_path=IMAGE_PATH, auto_open=False, ), ] return nodes def _tree_editor_default(self): return TreeEditor(editable=False, hide_root=False, on_dclick='handler._on_dclick', orientation='vertical', nodes=self.nodes ) \ No newline at end of file
LTS5/connectomeviewer
6396eec04086e5b523a75497e9cfaba18d4bd3c1
Set medium slice index for image plane widget
diff --git a/cviewer/plugins/codeoracle/scripts.py b/cviewer/plugins/codeoracle/scripts.py index 3318fc9..89b3f38 100644 --- a/cviewer/plugins/codeoracle/scripts.py +++ b/cviewer/plugins/codeoracle/scripts.py @@ -1,1026 +1,1024 @@ writegexf = ''' """ Convert a connectome network to the GEXF format readable by Gephi for further analysis and visualization """ import networkx as nx import numpy as np cnet = cfile.obj.get_by_name('connectome_freesurferaparc') cnet.load() outpath = 'out.gexf' def fix_float_for_gexf(network): for u,v,d in network.edges_iter(data=True): for k,v in d.items(): if isinstance(d[k], np.float64): d[k] = float( d[k] ) for u,d in network.nodes_iter(data=True): for k,v in d.items(): if isinstance(d[k], np.float64): d[k] = float( d[k] ) return network G = fix_float_for_gexf(cnet.data) nx.write_gexf(cnet.data, outpath) ''' corticocortico =''' """ Extract cortio-cortico fibers from tractography outputs of CMTK, apply clustering and visualize them. The basic idea is to remove sets of fibers such as the corpus callosum first, and then inspect various histograms of start-endpoint-distances, mean curvature etc. and downsample to incrementally filter out fibers until only cortico-cortico fibers remain. The remaining fibers are then clustered to yield bundles of cortico-cortical fibers. This script shows the outcome of the power of interactively working with scientific datasets for exploration and parameter estimation. Stephan Gerhard, May 2011 """ import numpy as np import nibabel as ni from os.path import join as j import os.path as op import time from nibabel import trackvis import cfflib as cf from dipy.tracking import metrics as tm from dipy.tracking import distances as td from dipy.io import pickles as pkl from dipy.tracking.metrics import length, mean_curvature import dipy.viz.fvtk as fvtk from fos import World, Window from fos.actor.curve import InteractiveCurves # Load the relevant data files # load connectome file object con = cfile.obj # alternatively when loading from Ipython directly with cfflib # con = cf.load('meta.cml') def load_data(con): fibobj = con.get_by_name('Final Tractography (freesurferaparc)') fibobj.load() fibers = fibobj.get_fibers_as_numpy() fibershdr = fibers.data[1] epmmobj = con.get_by_name('Fiber mean curvature') eleobj = con.get_by_name('Final fiber lengths (freesurferaparc)') eleobj.load() lenghts = eleobj.data emobj = con.get_by_name('Fiber mean curvature') emobj.load() meancurv = emobj.data print "Compute endpoints [mm] array" endpoints = np.zeros( (len(fibers), 2, 3), dtype = np.float32 ) for i in xrange(len(fibers)): endpoints[i,0,:] = fibers[i][0,:] endpoints[i,1,:] = fibers[i][-1,:] return fibers, fibershdr, lenghts, meancurv, endpoints # load stuff, can uncomment for rerunning the script in ipython with # run -i script.py fibers, fibershdr, lenghts, meancurv, endpoints = load_data(con) # Helper functions def compute_start_end_distances(endpoints): n = endpoints.shape[0] di = np.zeros( (n, 1) ) for i in xrange(n): d = np.abs(endpoints[i,0,:]-endpoints[i,1,:]) di[i,0] = np.sqrt(np.dot(d,d)) return di def sidx(arr, value): """ Returns the indices that are smaller or equal to the given array """ return np.where( arr <= value)[0] def randcolarr(arr): """ Returns a random color for each row in arr """ return np.random.rand(1,3).repeat(len(arr),axis=0) def filterfibers(fibarr, filtarr, lower, upper): return fibarr[ np.where((filtarr>lower) & (filtarr<upper))[0] ] def filterfibersidx(filtarr, lower, upper): return np.where((filtarr>lower) & (filtarr<upper))[0] def filterfibersidxcomplement(filtarr, lower, upper): return np.where((filtarr<=lower) | (filtarr>=upper))[0] def filterhemisphere(endpointsmean, xcut, hemi = 0): if hemi == 1: return np.where( (endpointsmean < xcut) )[0] elif hemi == 2: return np.where( (endpointsmean > xcut) )[0] def filterfibersidx2(filtarr, lower, upper, curvarr, value): return np.where((filtarr>lower) & (filtarr<upper) & (curvarr >value) )[0] def filterccidx(endpoints, xcenterline): """ Returns the index of all fibers where the start or endpoint of each fiber is opposite the x centerline """ return np.where((endpoints[:,0,0]>xcenterline) & (endpoints[:,1,0]<xcenterline))[0] def compfilterccidx(endpoints, xcenterline, onlyleft = True): """ Returns the index of all fibers where the start or endpoint of each fiber is opposite the x centerline """ if onlyleft: return np.where( (((endpoints[:,0,0]>xcenterline) & (endpoints[:,1,0]>xcenterline)) | ((endpoints[:,0,0]<xcenterline) & (endpoints[:,1,0]<xcenterline))) & ((endpoints[:,0,0]<xcenterline) & (endpoints[:,1,0]<xcenterline)) )[0] else: return np.where( ((endpoints[:,0,0]>xcenterline) & (endpoints[:,1,0]>xcenterline)) | ((endpoints[:,0,0]<xcenterline) & (endpoints[:,1,0]<xcenterline)) )[0] def showfibfvtk(fibarr, colarr, percentage = 100): fibarr2 = fibarr[::percentage] colarr2 = colarr[::percentage] fibarr2list = fibarr2.tolist() r=fvtk.ren(); #fvtk.add(r,fvtk.axes()) r.SetBackground(1, 1, 1) [fvtk.add(r,fvtk.line(ele, colarr2[i,:])) for i, ele in enumerate(fibarr2list)]; fvtk.show(r, title = "Fibers", size = (500,500)) def showfibfos(fibarr, colarr, percentage = 100): fibarr2 = fibarr[::percentage] colarr2 = colarr[::percentage].astype('f4') cu = InteractiveCurves(curves = fibarr2.tolist(), colors = colarr2) w=World() w.add(cu) wi = Window(caption="Multi-Modal 1", width = 800, height = 800) wi.attach(w) def preparecolorarray(clustering, number_of_fibers): colors=np.zeros((number_of_fibers,4)) for c in clustering: color=np.random.rand(1,4) for i in clustering[c]['indices']: colors[i]=color colors[:,3] = 1.0 # need alpha channel return colors def angle(x,y): return np.rad2deg(np.arccos(np.dot(x,y)/np.sqrt(np.dot(x,x))/np.sqrt(np.dot(y,y)))) def compute_angle_array(tracksobj, downsampling = 3): n = tracksobj.shape[0] fiberangles = np.zeros( (n, 1) ) if downsampling == 3: for i in xrange(n): x=tracksobj[i][0]-tracksobj[i][1] y=tracksobj[i][2]-tracksobj[i][1] fiberangles[i] = angle(x,y) return fiberangles # start script # Compute the distance array dist = compute_start_end_distances(endpoints) # Inspect histogram to find xcenterline # hist(endpoints[:,0,0],200) # -> e.g. found x coordinate 103 # compute distance mean distmean = np.mean(endpoints[:,:,0],axis=1) # noccidx = filterfibersidx(distmean, 70, 104) # good to have cc and few corticospinal noccidx = filterfibersidxcomplement(distmean, 70, 104) # good to have cc and few corticospinal # change hemi parameter to switch hemisphere onlyleftidx = filterhemisphere(distmean, 84, hemi = 1) noccidx = np.intersect1d(noccidx , onlyleftidx) # 4. filter out corpous callosum fibers # noccidx = compfilterccidx(endpoints, 84, False) noccfibers = fibers[noccidx] # 5. show fibers without cc #showfibfvtk(noccfibers,randcolarr(noccfibers), 1000) # 6. look at distance histogram #hist(dist,100) # 7. compute new distance histogram for fibers without cc distnocc = compute_start_end_distances(endpoints[noccidx,:,:]) meancuvnocc = meancurv[noccidx] #hist(distnocc,100) #hist(meancuvnocc,100) # 8. find short fibers and show them #shortfibers = noccfibers[filterfibersidx(distnocc, 0, 30)] #showfibfvtk(shortfibers,randcolarr(shortfibers), 100) # using meancurvature shortfibers = noccfibers[filterfibersidx2(distnocc, 10, 30, meancuvnocc, 0.05)] #showfibfvtk(shortfibers,randcolarr(shortfibers), 10) #shortfibers = noccfibers[filterfibersidx(dist, 8, 40)] # 120-180: long range # around 85: some projection, cortico spinal, temporal association # 8-40: enough U fibers # 9. fiber clustering fiblist = shortfibers.tolist() print("Downsampling...") tracks=[tm.downsample(t,3) for t in fiblist] # calculate the angle of downsampled fibers tracksobj=np.array(tracks, dtype=np.object) fiberangles = compute_angle_array(tracksobj) # filter fibers fiberangleidx = filterfibersidx(fiberangles, 20, 80) # create new short fiber set shortfibersnew = shortfibers[fiberangleidx] tracksobjnew = tracksobj[fiberangleidx] print("Clustering....") now=time.clock() C=td.local_skeleton_clustering(tracksobjnew.tolist(),d_thr=10) print('Done in %.2f s' % (time.clock()-now,)) # 10. prepare color array and show mycols = preparecolorarray(C, len(shortfibersnew)) #showfibfvtk(shortfibersnew,mycols, 10) #mycols = preparecolorarray(C, len(shortfibers)) #mycols = randcolarr(shortfibers) #showfibfvtk(shortfibers,mycols, 50) # only show left hemisphere # show number of fibers in each bundle histogram a=np.array([(id,v['N']) for id, v in C.items()]) idx=np.where(a[:,1] < 100)[0] allidx = np.arange(tracksobjnew.shape[0]) for i in idx: idxremove = C[i]['indices'] allidx = np.lib.arraysetops.setdiff1d(allidx, C[i]['indices']) #del C[i] shortfibersnew2 = shortfibersnew[allidx] tracksobjnew2 = tracksobjnew[allidx] C2=td.local_skeleton_clustering(tracksobjnew2.tolist(),d_thr=9) mycols2 = preparecolorarray(C2, len(shortfibersnew2)) # show with fos showfibfvtk(shortfibersnew2,mycols2, 10) #showfibfos(shortfibersnew2,mycols2, 50) #hist(a,100) # use fos to show with bigger sized tubes """ percentage=1 fibarr2 = shortfibersnew2[::percentage] colarr2 = mycols2[::percentage].astype('f4') cu = InteractiveCurves(curves = fibarr2.tolist(), colors = colarr2, line_width = 6.0) w=World() w.add(cu) wi = Window(caption="Multi-Modal 1", width = 1200, height = 900, bgcolor = (1,1,1,0)) wi.attach(w) # w.delete(cu) """ ''' threedviz2 = """ # Modified from NetworkX drawing # https://networkx.lanl.gov/trac/browser/networkx/examples/drawing/mayavi2_spring.py import networkx as nx import numpy as np from enthought.mayavi import mlab # Retrieve NetworkX graph G = cfile.obj.get_by_name("connectome_freesurferaparc").data # Key value on the nodes to transform to scalar value for node coloring node_scalar_key = "dn_correspondence_id" # Network Layouting: 2d circular layout pos=nx.circular_layout(G,dim=2,scale=1) # numpy array of x,y,z positions in sorted node order xyz=np.array([pos[v] for v in sorted(G)]) # adding zero z coordinate xyz = np.hstack( (xyz, np.zeros( (len(xyz), 1) ) ) ) # Network Layouting: 3d spring layout #pos=nx.spring_layout(G,dim=3) # numpy array of x,y,z positions in sorted node order #xyz=np.array([pos[v] for v in sorted(G)]) # If you do not want to apply a layouting algorithm # You can create the xyz array from your node positions # as displayed in Code Oracle "3D Network" # scalar colors scalars = np.zeros( (len(G.nodes()),) ) for i,data in enumerate(G.nodes(data=True)): scalars[i] = float(data[1][node_scalar_key]) mlab.figure(1, bgcolor=(0, 0, 0)) mlab.clf() pts = mlab.points3d(xyz[:,0], xyz[:,1], xyz[:,2], scalars, scale_factor=0.05, scale_mode='none', colormap='Blues', resolution=20) # Defines only the connectivity # You can combine this script with the "3D Network" Code Oracle pts.mlab_source.dataset.lines = np.array(G.edges()) tube = mlab.pipeline.tube(pts, tube_radius=0.008) mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8)) # You can store the resulting figure programmatically # mlab.savefig('mynetwork.png') """ nipypebet = """ # Prerequisite: # 1. You need to have Nipype installed on your system. You can check this by entering # import nipype # In the IPython console. If it gives an error, you might want to install it from NeuroDebian. # See http://neuro.debian.net/ - Documentation is on http://nipy.sourceforge.net/nipype/ # 2. For this simple brain extraction script, you need to have FSL installed. # Goal: # This script shows how to extract the brain using BET through the Nipype interface. # It is derived from http://nipy.sourceforge.net/nipype/users/dartmouth_workshop_2010.html # As an input, you need a T1-weighted image that as an input to the Nipype node. rawimage = cfile.obj.get_by_name('MYRAWT1IMAGE') -# Let's check if the metadata agrees with what is expected (it should say "T1-weighted") -print rawimage.dtype - # We do not necessarily need to load the connectome object - if the connectome file is extracted # locally. We just need to retrieve the absolute file path rawimage_pwd = rawimage.get_abs_path() # We need the Nipype FSL interface import nipype.interfaces.fsl as fsl # We set the FSL default output type to compressed Nifti-1 fsl.FSLCommand.set_default_output_type('NIFTI_GZ') # We want to store the processed file in the temporary folder for now. fname_out = '/tmp/only_brain.nii.gz' # Now, we run the Nipype BET node, providing the correct input result = fsl.BET(in_file=rawimage_pwd, out_file = fname_out ).run() # We can print the result print result.outputs # To add the processed data file to the currently loaded connectome file, ... #cvol = cf.CVolume(name="BETed brain", src=fname_out, fileformat='Nifti1GZ', dtype='T1-weighted') #cfile.obj.add_connectome_volume(cvol) # Make sure that you save the connectome file if you want to keep the processed file. """ pushpull = """ # Prerequisite: # 1. For this script to run, you need to have PyXNAT installed # on your PYTHONPATH system. You can get it from http://packages.python.org/pyxnat/ # 2. You need to have access to an XNAT server and a project # You can create a login and project here: # http://central.xnat.org/ # http://sandbox.xnat.org/ # Goal: # 1. We want to push a connectome file to an XNAT server # 2. We want to pull a connectome file from an XNAT server # Hint: # If you plan to retrieve or upload big datasets, it is recommended to run this # script in an external Python shell, as long script executions block the IPython # shell within the Connectome Viewer. # We assume that a connectome file is currently loaded. For testing purposes, # it is beneficial if the files are not too big. # We need to load cfflib import cfflib as cf # Retrieve the currently loaded connectome object to push to the XNAT Server a = cfile.obj # You need to setup the XNAT connection cf.set_xnat_connection({'server': 'http://sandbox.xnat.org', 'user':'YOURUSERNAME', 'password':'YOURPASSWORD'}) # You need to have write access on the XNAT Server given. You will need the projectid to push # data to the server. In addition, you need to provide a subjectid and an experimentid. If overwrite # is set to True, remote files are overwritten by the local files. # Then, you can push the connectome file to XNAT cf.xnat_push( connectome_obj = a, projectid = "YOURPROJECTID", subjectid = "SUBJECTID", experimentid = "EXPID", overwrite = False) # NB: On the remote server, unique identifier for the subject and experiment id are generated, using the project id. # The push operation may take some time. # Similarly as you pushed a connectome file to XNAT, you can pull it again from the server. # You need the same identifiers to retrieve the data again. In addition, you need to provide a storage # path for the retrieved files. #cf.xnat_pull( projectid = "YOURPROJECTID", subjectid = "SUBJECTID", experimentid = "EXPID", '/YOUR/FILE/STORAGE/PATH') # In case you want to load the pulled connectome object, you can load it using cfflib #import cfflib as cf; mynewcon = cf.load( '/YOUR/FILE/STORAGE/PATH/meta.cml' ) """ surfscript = """ # Importing Mayavi mlab interface from enthought.mayavi import mlab # Retrieving the data # ------------------- # surface data from connectome file surface_file_vertices = cfile.obj.get_by_name("%s") vertices = surface_file_vertices.data.darrays[%s].data surface_file_faces = cfile.obj.get_by_name("%s") faces = surface_file_faces.data.darrays[%s].data labelname = "%s" surface_file_labels = cfile.obj.get_by_name(labelname) # Sanity check # ------------ # ensure that (triangluar) faces have dimension (N,3) if len(faces.shape) == 1: faces = faces.reshape( (len(faces) / 3, 3) ) # check for labels if labelname == "None": labels = None else: labels = surface_file_labels.data.darrays[%s].data # Ensure correct dimension (1-D) for labels labels = labels.ravel() # Ensure that each vertices has a corresponding label assert vertices.shape[0] == len(labels) # Perform task # ------------ # Create triangular surface mesh x, y, z = vertices[:,0], vertices[:,1], vertices[:,2] mlab.triangular_mesh(x, y, z, faces, scalars = labels) """ conmatrix = """ # Importing NetworkX import networkx as nx # Import the Connectome Matrix Viewer from cviewer.visualization.matrix.con_matrix_viewer import ConnectionMatrixViewer # Retrieving the data # ------------------- # retrieve the graph g = cfile.obj.get_by_name("%s").data # set the node key to use the labels nodelabelkey = "%s" # Defining some helper functions # ------------------------------ def relabel_to_int(graph): " Relabel string node ids to integer " def intmap(x): return int(x) return nx.relabel_nodes(graph,intmap) def get_nodelabels(graph, nodekey = 'dn_label'): " Retrieve a list of node labels " g = relabel_to_int(graph) a = [] return [v[nodekey] for n,v in g.nodes_iter(data=True)] def get_edge_values(graph): " Retrieve valid edge keys " if len(graph.edges()) == 0: return edi = graph.edges_iter(data=True) u,v,ed = edi.next() ret = [] for k,v in ed.items(): if isinstance(v, float) or isinstance(v, int): ret.append(k) return ret def get_matdict(graph): matdict = {} g = relabel_to_int(graph) # grab keys from the first edge, discarding id dl = get_edge_values(g) # create numpy matrix for each key using recarray matrec = nx.to_numpy_recarray(g, dtype=zip(dl, [float]*len(dl)) ) for k in dl: matdict[k] = matrec[k] return matdict def invoke_matrix_viewer(graph, nodelabelkey = 'dn_label'): " Invoke the Connectome Matrix Viewer " cmatrix_viewer = ConnectionMatrixViewer(get_nodelabels(graph, nodekey = nodelabelkey), get_matdict(graph)) cmatrix_viewer.edit_traits() # Perform task # ------------ invoke_matrix_viewer(g, nodelabelkey) """ conmatrixpyplot = """ # Importing NetworkX import networkx as nx # Import Pylab from pylab import imshow, show, cm # Import Numpy import numpy as np # Retrieving the data # ------------------- # retrieve the graph g = cfile.obj.get_by_name("%s").data # define the edge key to plot edgekey = "%s" # binarize matrix binarize = False # Defining some helper functions # ------------------------------ def show_matrix(a, edge, binarize = False): for u,v,d in a.edges_iter(data=True): a.edge[u][v]['weight'] = a.edge[u][v][edge] bb=nx.to_numpy_matrix(a) if binarize: c=np.zeros(bb.shape) c[bb>0] = 1 b = c else: b = bb imshow(b, interpolation='nearest', cmap=cm.jet, vmin = b.min(), vmax=b.max()) show() # Perform task # ------------ show_matrix(g, edgekey, binarize) """ ctrackedge = """ # Importing Numpy import numpy as np # Import Dipy Visualization import dipy.viz.fvtk as fvtk # Retrieving the data and set parameters # -------------------------------------- a = cfile.obj.get_by_name("Final Tractography (freesurferaparc)").get_fibers_as_numpy() fiberlabels = cfile.obj.get_by_name("Final fiber labels (freesurferaparc)").data fromid = 8 toid = 10 # Defining some helper functions # ------------------------------ def sidx(arr, fromval, toval): " Returns the indices that are equal to a given value " return np.where( (arr[:,0] == fromval) & (arr[:,1] == toval) )[0] def randcolarr(arr): " Returns a random color for each row in arr " return np.random.rand(1,3).repeat(len(arr),axis=0) def showfibfvtk(fibarr, colarr, percentage = 100): fibarr2 = fibarr[::percentage] colarr2 = colarr[::percentage] fibarr2list = fibarr2.tolist() r=fvtk.ren() #fvtk.add(r,fvtk.axes()) r.SetBackground(1, 1, 1) [fvtk.add(r,fvtk.line(ele, colarr2[i,:])) for i, ele in enumerate(fibarr2list)]; fvtk.show(r, title = "Fibers", size = (500,500)) # Perform task # ------------ idx = sidx(fiberlabels, fromid, toid) showfibfvtk(a[idx], randcolarr(a[idx]), 100) """ netscript = """ # Importing NumPy import numpy as np # Importing Mayavi mlab and tvtk packages from enthought.mayavi import mlab from enthought.tvtk.api import tvtk # Retrieving the data and set parameters # -------------------------------------- # load graph data g = cfile.obj.get_by_name("%s").data position_key = "%s" edge_key = "%s" node_label_key = "%s" # Node ids you want to create labels for create_label = [] # Assume node id's are integers nr_nodes = len(g.nodes()) position_array = np.zeros( (nr_nodes, 3) ) for i,nodeid in enumerate(g.nodes()): pos = g.node[nodeid][position_key] # apply a conversion procedure if the position # is a tuple store as string # we need a numpy array in the end if type(pos) is str or unicode: pos = tuple(float(s) for s in pos[1:-1].split(',')) pos = np.array(pos) position_array[i,:] = pos x, y, z = position_array[:,0], position_array[:,1], position_array[:,2] # Retrieve the edges and create a Numpy array edges = np.array(g.edges()) nr_edges = len(edges) # Retrieve edge values ev = np.zeros( (nr_edges, 1) ) for i,d in enumerate(g.edges_iter(data=True)): ev[i] = d[2][edge_key] # ensure that we are setting the correct edge assert d[0] == edges[i,0] and d[1] == edges[i,1] # Need to subtract one because the array index starts at zero edges = edges - 1 # Create vectors which will become edges start_positions = position_array[edges[:, 0], :].T end_positions = position_array[edges[:, 1], :].T vectors = end_positions - start_positions # Perform task # ------------ # create a new figure mlab.figure() nodesource = mlab.pipeline.scalar_scatter(x, y, z, name = 'Node Source') nodes = mlab.pipeline.glyph(nodesource, scale_factor=3.0, scale_mode='none',\ name = 'Nodes', mode='cube') nodes.glyph.color_mode = 'color_by_scalar' vectorsrc = mlab.pipeline.vector_scatter(start_positions[0], start_positions[1], start_positions[2], vectors[0], vectors[1], vectors[2], name = 'Connectivity Source') # add scalar array da = tvtk.DoubleArray(name=edge_key) da.from_array(ev) vectorsrc.mlab_source.dataset.point_data.add_array(da) vectorsrc.mlab_source.dataset.point_data.scalars = da.to_array() vectorsrc.mlab_source.dataset.point_data.scalars.name = edge_key # need to update the boundaries vectorsrc.outputs[0].update() # Add a thresholding filter to threshold the edges thres = mlab.pipeline.threshold(vectorsrc, name="Thresholding") myvectors = mlab.pipeline.vectors(thres,colormap='OrRd', #mode='cylinder', name='Connections', #scale_factor=1, #resolution=20, # make the opacity of the actor depend on the scalar. #transparent=True, scale_mode = 'vector') myvectors.glyph.glyph_source.glyph_source.glyph_type = 'dash' # vectors.glyph.glyph_source.glyph_source.radius = 0.01 myvectors.glyph.color_mode = 'color_by_scalar' myvectors.glyph.glyph.clamping = False # create labels for la in create_label: row_index = la - 1 label = g.node[la][node_label_key] mlab.text3d(position_array[row_index,0], position_array[row_index,1], position_array[row_index,2], ' ' + label, name = 'Node ' + label) """ nbsscript = """ # Import Numpy import numpy as np # Import pylab for plotting from pylab import imshow, show, title # Import NetworkX import networkx as nx # Import Network based statistic import cviewer.libs.pyconto.groupstatistics.nbs as nbs # For documentation of Network-based statistic parameters # do in IPython: nbs.compute_nbs? # https://github.com/LTS5/connectomeviewer/blob/master/cviewer/libs/pyconto/groupstatistics/nbs/_nbs.py # Retrieving the data and set parameters # -------------------------------------- # Define the two groups of networks you want to compare, # setting the connectome network name. These objects need # to exist in the loaded connectome file. first = ['FirstNetwork_control', 'SecondNetwork_control'] # The same for the second group: second = ['FirstNetwork_patient', 'SecondNetwork_patient'] # Select the edge value to use for the first group first_edge_value = 'number_of_fibers' # Select the edge value to use for the second group second_edge_value = 'number_of_fibers' # More parameters for threshold (THRESH) # andd the number of # permutations (K) THRESH=3 K=10 # Can be one of 'left', 'equal', 'right' TAIL='left' SHOW_MATRIX = True # Perform task # ------------ # Get the connectome objects for the given connectome network names firstgroup = [cfile.obj.get_by_name(n) for n in first] secondgroup = [cfile.obj.get_by_name(n) for n in second] # Make sure that all networks are loaded in memory for net in firstgroup: net.load() for net in secondgroup: net.load() # Convert your network data for each group into numpy arrays nr1_networks = len(firstgroup) nr1_nrnodes = len(firstgroup[0].data.nodes()) nr2_networks = len(secondgroup) nr2_nrnodes = len(secondgroup[0].data.nodes()) X = np.zeros( (nr1_nrnodes, nr1_nrnodes, nr1_networks) ) Y = np.zeros( (nr2_nrnodes, nr2_nrnodes, nr2_networks) ) # Fill in the data from the networks for i, sub in enumerate(firstgroup): graph=sub.data # Setting the edge requested edge value as weight value for u,v,d in graph.edges(data=True): graph[u][v]['weight']=d[first_edge_value] # Retrieve the matrix X[:,:,i] = nx.to_numpy_matrix(graph) for i, sub in enumerate(secondgroup): graph=sub.data # Setting the edge requested edge value as weight value for u,v,d in graph.edges(data=True): graph[u][v]['weight']=d[second_edge_value] # Retrieve the matrix Y[:,:,i] = nx.to_numpy_matrix(graph) # Perform task # ------------ # Compute NBS, this might take a long time # and might better be done in a seperate script PVAL, ADJ, NULL = nbs.compute_nbs(X,Y,THRESH,K,TAIL) # We can now look at the connectivity matrix identified with matplotlib if SHOW_MATRIX: imshow(ADJ, interpolation='nearest') title('Edges identified by the NBS') show() # we create a networkx graph again from the adjacency matrix nbsgraph = nx.from_numpy_matrix(ADJ) # relabel nodes because the should not start at zero for our convention nbsgraph=nx.relabel_nodes(nbsgraph, lambda x: x + 1) # populate node dictionaries with attributes from first network of the first group # it must include some location information to display it for nid, ndata in firstgroup[0].data.nodes_iter(data=True): nbsgraph.node[nid] = ndata # Find a date import datetime as dt a=dt.datetime.now() ostr = '%s:%s:%s' % (a.hour, a.minute, a.second) # You can now add now the results to the connectome file # Make sure that the name is not existing yet in the connectome file cfile.obj.add_connectome_network_from_nxgraph('NBS result at %s' % ostr, nbsgraph, dtype='NBSResult') cfile.update_children() """ volrendering = """ from enthought.mayavi import mlab import numpy as np data=np.random.random( (10,10,10)) min = data.min() max = data.max() source=mlab.pipeline.scalar_field(data) vol = mlab.pipeline.volume(source, vmin=min+0.65*(max-min), vmax=min+0.9*(max-min)) """ volslice = """ # Import Mayavi mlab interface from enthought.mayavi import mlab # Import NumPy import numpy as np # Retrieving the data and set parameters # -------------------------------------- # the CVolume name volname="%s" # Retrieve volume data (as Nibabel Image) voldat = cfile.obj.get_by_name(volname).data # Retrieve the image data data = voldat.get_data() # Retrieve the affine affine = voldat.get_affine() center = np.r_[0, 0, 0, 1] # Perform task # ------------ # create A ScalarField with spacing and origin from the affine data_src = mlab.pipeline.scalar_field(data) data_src.spacing = np.diag(affine)[:3] data_src.origin = np.dot(affine, center)[:3] # Create an outline mlab.pipeline.outline(data_src) # Create a simple x-aligned image plane widget image_plane_widget = mlab.pipeline.image_plane_widget(data_src, name=volname) image_plane_widget.ipw.plane_orientation = 'x_axes' -image_plane_widget.ipw.reslice_interpolate = 'nearest_neighbour' +image_plane_widget.ipw.reslice_interpolate = 'nearest_neighbour' +image_plane_widget.ipw.slice_index = int(data.shape[0]/2) """ reportlab = """ # Credits # http://www.protocolostomy.com/2008/10/22/generating-reports-with-charts-using-python-reportlab/ from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import networkx as nx import numpy as np import datetime import tempfile import os.path PAGE_HEIGHT=defaultPageSize[1] styles = getSampleStyleSheet() Title = "Connectome Report for " Elements=[] HeaderStyle = styles["Heading1"] ParaStyle = styles["Normal"] PreStyle = styles["Code"] today = datetime.date.today() tmpdir = tempfile.gettempdir() # Retrieving the data # ------------------- # the network for the reporting net = cfile.obj.get_by_name('connectome_freesurferaparc') net.load() # the edge key de_key = 'number_of_fibers' # output file name fname = os.path.join(tmpdir, 'out.pdf') date = today.strftime('Reported on %dth, %h %Y') netw = net.data def header(txt, style=HeaderStyle, klass=Paragraph, sep=0.3): s = Spacer(0.2*inch, sep*inch) para = klass(txt, style) sect = [s, para] result = KeepTogether(sect) return result def p(txt): return header(txt, style=ParaStyle, sep=0.1) def pre(txt): s = Spacer(0.1*inch, 0.1*inch) p = Preformatted(txt, PreStyle) precomps = [s,p] result = KeepTogether(precomps) return result def go(fname): doc = SimpleDocTemplate(fname) doc.build(Elements) mytitle = header(Title + '"' + cfile.obj.get_connectome_meta().get_title() + '"') mydate = header(date, sep=0.1, style=ParaStyle) mytitlenet = header(net.get_name() + " (CNetwork)") for u,v,d in netw.edges_iter(data=True): edgval = netw.edge[u][v][de_key] if edgval > 0: netw.edge[u][v]['weight'] = 1 else: netw.edge[u][v]['weight'] = 1 b=nx.to_numpy_matrix(netw) fig = plt.figure() fig.suptitle("Binary Connection matrix") aa= plt.imshow(b, interpolation='nearest', cmap=plt.cm.Greys, vmin = b.min(), vmax=b.max()) fig.savefig(os.path.join(tmpdir, 'matrix.png')) fig.clear() fig.suptitle("Degree distribution") plt.hist(netw.degree().values(),30) fig.savefig(os.path.join(tmpdir,'distri.png')) # measures if nx.is_connected(netw): isit = "Yes" else: isit = "No" me1 = p("Number of Nodes: " + str(netw.number_of_nodes())) me2 = p("Number of Edges: " + str(netw.number_of_edges())) me3 = p("Is network connected: " + isit) me4 = p("Number of connected components: " + str(nx.number_connected_components(netw))) me44 = p("Average node degree: %.2f" % np.mean(netw.degree().values())) me5 = p("Average unweighted shortest path length: %.2f" % nx.average_shortest_path_length(netw, weighted = False)) me6 = p("Average clustering coefficient: %.2f" % nx.average_clustering(netw)) logo = os.path.join(tmpdir, "matrix.png") im1 = Image(logo, 300,225) logo = os.path.join(tmpdir, "distri.png") im2 = Image(logo, 250,188) codesection = [mytitle, mydate, mytitlenet, me1, me2, me3, me4,me44, me5, me6, im1, im2] src = KeepTogether(codesection) Elements.append(src) go(fname) """
LTS5/connectomeviewer
d2374d9fcf2eca8ad37ba5a14b7894b7f70ad2f7
Remove unused preferences entries
diff --git a/cviewer/plugins/ui/cviewer_ui_preferences_helper.py b/cviewer/plugins/ui/cviewer_ui_preferences_helper.py index de3fc39..1b2e560 100644 --- a/cviewer/plugins/ui/cviewer_ui_preferences_helper.py +++ b/cviewer/plugins/ui/cviewer_ui_preferences_helper.py @@ -1,53 +1,45 @@ """ The ConnectomeViewer User Interface Preferences """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Enthought library imports from enthought.preferences.api import PreferencesHelper from enthought.traits.api import Bool, Directory from enthought.traits.ui.api import View, Group, Item class CViewerUIPreferencesHelper(PreferencesHelper): """ Helper for the Connectome Viewer UI preferences """ # The preferences path for which we use. preferences_path = 'cviewer.plugins.ui' # actually, the same as in cviewer_preferences_page.py #### Preferences ########################################################## - # Load labels automatically - labelload = Bool(desc='if to load and show all node labels in the 3D View') - # Use IPython in Shell useipython = Bool(desc='if to use IPython as default Shell') # Default path to load cff files cffpath = Directory(desc='the default path to open Connectome files from') # default path for scripts scriptpath = Directory(desc='the default path to find executable Python scripts') - # Path to Trackvis - trackvispath = Directory(desc='the path where the TrackVis executables reside') - # show the ConnectomeViewer splash screen show_splash_screen = Bool(desc='if the Connectome Viewer splashscreen is shown on startup') ###################################################################### # Traits UI view. trait_view = View(Group( Item('show_splash_screen', label='Show Splash Screen:'), - Item('labelload', label='Load All Node Labels:'), Item('useipython', label='Use IPython:'), Item('cffpath', label='Connectome File Path:'), Item('scriptpath', label='Python Script Path:'), - Item('trackvispath', label='TrackVis Executable Path:') ), resizable=True ) \ No newline at end of file diff --git a/cviewer/plugins/ui/cviewer_ui_preferences_page.py b/cviewer/plugins/ui/cviewer_ui_preferences_page.py index ad98d82..26655bd 100644 --- a/cviewer/plugins/ui/cviewer_ui_preferences_page.py +++ b/cviewer/plugins/ui/cviewer_ui_preferences_page.py @@ -1,59 +1,51 @@ """ The preferences for the ConnectomeViewer UI Plugin. """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Enthought library imports from enthought.preferences.ui.api import PreferencesPage from enthought.traits.api import Bool, Directory from enthought.traits.ui.api import View, Group, Item class CViewerUIPreferencesPage(PreferencesPage): """ The preferences page for the Connectome Viewer UI Plugin. """ #### 'PreferencesPage' interface ########################################## # The page's category (e.g. 'General/Appearance'). The empty string means # that this is a top-level page. category = '' # The page name (this is what is shown in the preferences dialog. name = 'Connectome Viewer' # The path to the preference node that contains the preferences. preferences_path = 'cviewer.plugins.ui' #### Preferences ########################################################## - # Load labels automatically - labelload = Bool(desc='if to load and show all node labels in the 3D View') - # Use IPython in Shell useipython = Bool(desc='if to use IPython as default Shell') # Default path to load cff files cffpath = Directory(desc='the default path to open Connectome files from') # default path for scripts scriptpath = Directory(desc='the default path to find executable Python scripts') - # Path to Trackvis - trackvispath = Directory(desc='the path where the TrackVis executables reside') - # show the ConnectomeViewer splash screen show_splash_screen = Bool(desc='if the Connectome Viewer splashscreen is shown on startup') #### Traits UI views ###################################################### trait_view = View(Group( Item('show_splash_screen', label='Show Splash Screen:'), - Item('labelload', label='Load All Node Labels:'), Item('useipython', label='Use IPython:'), Item('cffpath', label='Connectome File Path:'), Item('scriptpath', label='Python Script Path:'), - Item('trackvispath', label='TrackVis Executable Path:') ), resizable=True ) #### EOF ######################################################################
LTS5/connectomeviewer
c47231af3cd622d555b3fb831aaab5b8d8c2adb8
Small fix in code oracle
diff --git a/cviewer/plugins/codeoracle/scripts.py b/cviewer/plugins/codeoracle/scripts.py index 8321738..3318fc9 100644 --- a/cviewer/plugins/codeoracle/scripts.py +++ b/cviewer/plugins/codeoracle/scripts.py @@ -159,868 +159,868 @@ def showfibfos(fibarr, colarr, percentage = 100): cu = InteractiveCurves(curves = fibarr2.tolist(), colors = colarr2) w=World() w.add(cu) wi = Window(caption="Multi-Modal 1", width = 800, height = 800) wi.attach(w) def preparecolorarray(clustering, number_of_fibers): colors=np.zeros((number_of_fibers,4)) for c in clustering: color=np.random.rand(1,4) for i in clustering[c]['indices']: colors[i]=color colors[:,3] = 1.0 # need alpha channel return colors def angle(x,y): return np.rad2deg(np.arccos(np.dot(x,y)/np.sqrt(np.dot(x,x))/np.sqrt(np.dot(y,y)))) def compute_angle_array(tracksobj, downsampling = 3): n = tracksobj.shape[0] fiberangles = np.zeros( (n, 1) ) if downsampling == 3: for i in xrange(n): x=tracksobj[i][0]-tracksobj[i][1] y=tracksobj[i][2]-tracksobj[i][1] fiberangles[i] = angle(x,y) return fiberangles # start script # Compute the distance array dist = compute_start_end_distances(endpoints) # Inspect histogram to find xcenterline # hist(endpoints[:,0,0],200) # -> e.g. found x coordinate 103 # compute distance mean distmean = np.mean(endpoints[:,:,0],axis=1) # noccidx = filterfibersidx(distmean, 70, 104) # good to have cc and few corticospinal noccidx = filterfibersidxcomplement(distmean, 70, 104) # good to have cc and few corticospinal # change hemi parameter to switch hemisphere onlyleftidx = filterhemisphere(distmean, 84, hemi = 1) noccidx = np.intersect1d(noccidx , onlyleftidx) # 4. filter out corpous callosum fibers # noccidx = compfilterccidx(endpoints, 84, False) noccfibers = fibers[noccidx] # 5. show fibers without cc #showfibfvtk(noccfibers,randcolarr(noccfibers), 1000) # 6. look at distance histogram #hist(dist,100) # 7. compute new distance histogram for fibers without cc distnocc = compute_start_end_distances(endpoints[noccidx,:,:]) meancuvnocc = meancurv[noccidx] #hist(distnocc,100) #hist(meancuvnocc,100) # 8. find short fibers and show them #shortfibers = noccfibers[filterfibersidx(distnocc, 0, 30)] #showfibfvtk(shortfibers,randcolarr(shortfibers), 100) # using meancurvature shortfibers = noccfibers[filterfibersidx2(distnocc, 10, 30, meancuvnocc, 0.05)] #showfibfvtk(shortfibers,randcolarr(shortfibers), 10) #shortfibers = noccfibers[filterfibersidx(dist, 8, 40)] # 120-180: long range # around 85: some projection, cortico spinal, temporal association # 8-40: enough U fibers # 9. fiber clustering fiblist = shortfibers.tolist() print("Downsampling...") tracks=[tm.downsample(t,3) for t in fiblist] # calculate the angle of downsampled fibers tracksobj=np.array(tracks, dtype=np.object) fiberangles = compute_angle_array(tracksobj) # filter fibers fiberangleidx = filterfibersidx(fiberangles, 20, 80) # create new short fiber set shortfibersnew = shortfibers[fiberangleidx] tracksobjnew = tracksobj[fiberangleidx] print("Clustering....") now=time.clock() C=td.local_skeleton_clustering(tracksobjnew.tolist(),d_thr=10) print('Done in %.2f s' % (time.clock()-now,)) # 10. prepare color array and show mycols = preparecolorarray(C, len(shortfibersnew)) #showfibfvtk(shortfibersnew,mycols, 10) #mycols = preparecolorarray(C, len(shortfibers)) #mycols = randcolarr(shortfibers) #showfibfvtk(shortfibers,mycols, 50) # only show left hemisphere # show number of fibers in each bundle histogram a=np.array([(id,v['N']) for id, v in C.items()]) idx=np.where(a[:,1] < 100)[0] allidx = np.arange(tracksobjnew.shape[0]) for i in idx: idxremove = C[i]['indices'] allidx = np.lib.arraysetops.setdiff1d(allidx, C[i]['indices']) #del C[i] shortfibersnew2 = shortfibersnew[allidx] tracksobjnew2 = tracksobjnew[allidx] C2=td.local_skeleton_clustering(tracksobjnew2.tolist(),d_thr=9) mycols2 = preparecolorarray(C2, len(shortfibersnew2)) # show with fos showfibfvtk(shortfibersnew2,mycols2, 10) #showfibfos(shortfibersnew2,mycols2, 50) #hist(a,100) # use fos to show with bigger sized tubes """ percentage=1 fibarr2 = shortfibersnew2[::percentage] colarr2 = mycols2[::percentage].astype('f4') cu = InteractiveCurves(curves = fibarr2.tolist(), colors = colarr2, line_width = 6.0) w=World() w.add(cu) wi = Window(caption="Multi-Modal 1", width = 1200, height = 900, bgcolor = (1,1,1,0)) wi.attach(w) # w.delete(cu) """ ''' threedviz2 = """ # Modified from NetworkX drawing # https://networkx.lanl.gov/trac/browser/networkx/examples/drawing/mayavi2_spring.py import networkx as nx import numpy as np from enthought.mayavi import mlab # Retrieve NetworkX graph G = cfile.obj.get_by_name("connectome_freesurferaparc").data # Key value on the nodes to transform to scalar value for node coloring node_scalar_key = "dn_correspondence_id" # Network Layouting: 2d circular layout pos=nx.circular_layout(G,dim=2,scale=1) # numpy array of x,y,z positions in sorted node order xyz=np.array([pos[v] for v in sorted(G)]) # adding zero z coordinate xyz = np.hstack( (xyz, np.zeros( (len(xyz), 1) ) ) ) # Network Layouting: 3d spring layout #pos=nx.spring_layout(G,dim=3) # numpy array of x,y,z positions in sorted node order #xyz=np.array([pos[v] for v in sorted(G)]) # If you do not want to apply a layouting algorithm # You can create the xyz array from your node positions # as displayed in Code Oracle "3D Network" # scalar colors scalars = np.zeros( (len(G.nodes()),) ) for i,data in enumerate(G.nodes(data=True)): scalars[i] = float(data[1][node_scalar_key]) mlab.figure(1, bgcolor=(0, 0, 0)) mlab.clf() pts = mlab.points3d(xyz[:,0], xyz[:,1], xyz[:,2], scalars, scale_factor=0.05, scale_mode='none', colormap='Blues', resolution=20) # Defines only the connectivity # You can combine this script with the "3D Network" Code Oracle pts.mlab_source.dataset.lines = np.array(G.edges()) tube = mlab.pipeline.tube(pts, tube_radius=0.008) mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8)) # You can store the resulting figure programmatically # mlab.savefig('mynetwork.png') """ nipypebet = """ # Prerequisite: # 1. You need to have Nipype installed on your system. You can check this by entering # import nipype # In the IPython console. If it gives an error, you might want to install it from NeuroDebian. # See http://neuro.debian.net/ - Documentation is on http://nipy.sourceforge.net/nipype/ # 2. For this simple brain extraction script, you need to have FSL installed. # Goal: # This script shows how to extract the brain using BET through the Nipype interface. # It is derived from http://nipy.sourceforge.net/nipype/users/dartmouth_workshop_2010.html # As an input, you need a T1-weighted image that as an input to the Nipype node. rawimage = cfile.obj.get_by_name('MYRAWT1IMAGE') # Let's check if the metadata agrees with what is expected (it should say "T1-weighted") print rawimage.dtype # We do not necessarily need to load the connectome object - if the connectome file is extracted # locally. We just need to retrieve the absolute file path rawimage_pwd = rawimage.get_abs_path() # We need the Nipype FSL interface import nipype.interfaces.fsl as fsl # We set the FSL default output type to compressed Nifti-1 fsl.FSLCommand.set_default_output_type('NIFTI_GZ') # We want to store the processed file in the temporary folder for now. fname_out = '/tmp/only_brain.nii.gz' # Now, we run the Nipype BET node, providing the correct input result = fsl.BET(in_file=rawimage_pwd, out_file = fname_out ).run() # We can print the result print result.outputs # To add the processed data file to the currently loaded connectome file, ... #cvol = cf.CVolume(name="BETed brain", src=fname_out, fileformat='Nifti1GZ', dtype='T1-weighted') #cfile.obj.add_connectome_volume(cvol) # Make sure that you save the connectome file if you want to keep the processed file. """ pushpull = """ # Prerequisite: # 1. For this script to run, you need to have PyXNAT installed # on your PYTHONPATH system. You can get it from http://packages.python.org/pyxnat/ # 2. You need to have access to an XNAT server and a project # You can create a login and project here: # http://central.xnat.org/ # http://sandbox.xnat.org/ # Goal: # 1. We want to push a connectome file to an XNAT server # 2. We want to pull a connectome file from an XNAT server # Hint: # If you plan to retrieve or upload big datasets, it is recommended to run this # script in an external Python shell, as long script executions block the IPython # shell within the Connectome Viewer. # We assume that a connectome file is currently loaded. For testing purposes, # it is beneficial if the files are not too big. # We need to load cfflib import cfflib as cf # Retrieve the currently loaded connectome object to push to the XNAT Server a = cfile.obj # You need to setup the XNAT connection cf.set_xnat_connection({'server': 'http://sandbox.xnat.org', 'user':'YOURUSERNAME', 'password':'YOURPASSWORD'}) # You need to have write access on the XNAT Server given. You will need the projectid to push # data to the server. In addition, you need to provide a subjectid and an experimentid. If overwrite # is set to True, remote files are overwritten by the local files. # Then, you can push the connectome file to XNAT cf.xnat_push( connectome_obj = a, projectid = "YOURPROJECTID", subjectid = "SUBJECTID", experimentid = "EXPID", overwrite = False) # NB: On the remote server, unique identifier for the subject and experiment id are generated, using the project id. # The push operation may take some time. # Similarly as you pushed a connectome file to XNAT, you can pull it again from the server. # You need the same identifiers to retrieve the data again. In addition, you need to provide a storage # path for the retrieved files. #cf.xnat_pull( projectid = "YOURPROJECTID", subjectid = "SUBJECTID", experimentid = "EXPID", '/YOUR/FILE/STORAGE/PATH') # In case you want to load the pulled connectome object, you can load it using cfflib #import cfflib as cf; mynewcon = cf.load( '/YOUR/FILE/STORAGE/PATH/meta.cml' ) """ surfscript = """ # Importing Mayavi mlab interface from enthought.mayavi import mlab # Retrieving the data # ------------------- # surface data from connectome file surface_file_vertices = cfile.obj.get_by_name("%s") vertices = surface_file_vertices.data.darrays[%s].data surface_file_faces = cfile.obj.get_by_name("%s") faces = surface_file_faces.data.darrays[%s].data labelname = "%s" surface_file_labels = cfile.obj.get_by_name(labelname) # Sanity check # ------------ # ensure that (triangluar) faces have dimension (N,3) if len(faces.shape) == 1: faces = faces.reshape( (len(faces) / 3, 3) ) # check for labels if labelname == "None": labels = None else: labels = surface_file_labels.data.darrays[%s].data # Ensure correct dimension (1-D) for labels labels = labels.ravel() # Ensure that each vertices has a corresponding label assert vertices.shape[0] == len(labels) # Perform task # ------------ # Create triangular surface mesh x, y, z = vertices[:,0], vertices[:,1], vertices[:,2] mlab.triangular_mesh(x, y, z, faces, scalars = labels) """ conmatrix = """ # Importing NetworkX import networkx as nx # Import the Connectome Matrix Viewer from cviewer.visualization.matrix.con_matrix_viewer import ConnectionMatrixViewer # Retrieving the data # ------------------- # retrieve the graph g = cfile.obj.get_by_name("%s").data # set the node key to use the labels nodelabelkey = "%s" # Defining some helper functions # ------------------------------ def relabel_to_int(graph): " Relabel string node ids to integer " def intmap(x): return int(x) return nx.relabel_nodes(graph,intmap) def get_nodelabels(graph, nodekey = 'dn_label'): " Retrieve a list of node labels " g = relabel_to_int(graph) a = [] return [v[nodekey] for n,v in g.nodes_iter(data=True)] def get_edge_values(graph): " Retrieve valid edge keys " if len(graph.edges()) == 0: return edi = graph.edges_iter(data=True) u,v,ed = edi.next() ret = [] for k,v in ed.items(): if isinstance(v, float) or isinstance(v, int): ret.append(k) return ret def get_matdict(graph): matdict = {} g = relabel_to_int(graph) # grab keys from the first edge, discarding id dl = get_edge_values(g) # create numpy matrix for each key using recarray matrec = nx.to_numpy_recarray(g, dtype=zip(dl, [float]*len(dl)) ) for k in dl: matdict[k] = matrec[k] return matdict def invoke_matrix_viewer(graph, nodelabelkey = 'dn_label'): " Invoke the Connectome Matrix Viewer " cmatrix_viewer = ConnectionMatrixViewer(get_nodelabels(graph, nodekey = nodelabelkey), get_matdict(graph)) cmatrix_viewer.edit_traits() # Perform task # ------------ invoke_matrix_viewer(g, nodelabelkey) """ conmatrixpyplot = """ # Importing NetworkX import networkx as nx # Import Pylab from pylab import imshow, show, cm # Import Numpy import numpy as np # Retrieving the data # ------------------- # retrieve the graph g = cfile.obj.get_by_name("%s").data # define the edge key to plot edgekey = "%s" # binarize matrix binarize = False # Defining some helper functions # ------------------------------ def show_matrix(a, edge, binarize = False): for u,v,d in a.edges_iter(data=True): a.edge[u][v]['weight'] = a.edge[u][v][edge] bb=nx.to_numpy_matrix(a) if binarize: c=np.zeros(bb.shape) c[bb>0] = 1 b = c else: b = bb imshow(b, interpolation='nearest', cmap=cm.jet, vmin = b.min(), vmax=b.max()) show() # Perform task # ------------ show_matrix(g, edgekey, binarize) """ ctrackedge = """ # Importing Numpy import numpy as np # Import Dipy Visualization import dipy.viz.fvtk as fvtk # Retrieving the data and set parameters # -------------------------------------- a = cfile.obj.get_by_name("Final Tractography (freesurferaparc)").get_fibers_as_numpy() fiberlabels = cfile.obj.get_by_name("Final fiber labels (freesurferaparc)").data fromid = 8 toid = 10 # Defining some helper functions # ------------------------------ def sidx(arr, fromval, toval): " Returns the indices that are equal to a given value " return np.where( (arr[:,0] == fromval) & (arr[:,1] == toval) )[0] def randcolarr(arr): " Returns a random color for each row in arr " return np.random.rand(1,3).repeat(len(arr),axis=0) def showfibfvtk(fibarr, colarr, percentage = 100): fibarr2 = fibarr[::percentage] colarr2 = colarr[::percentage] fibarr2list = fibarr2.tolist() r=fvtk.ren() #fvtk.add(r,fvtk.axes()) r.SetBackground(1, 1, 1) [fvtk.add(r,fvtk.line(ele, colarr2[i,:])) for i, ele in enumerate(fibarr2list)]; fvtk.show(r, title = "Fibers", size = (500,500)) # Perform task # ------------ idx = sidx(fiberlabels, fromid, toid) showfibfvtk(a[idx], randcolarr(a[idx]), 100) """ netscript = """ # Importing NumPy import numpy as np # Importing Mayavi mlab and tvtk packages from enthought.mayavi import mlab from enthought.tvtk.api import tvtk # Retrieving the data and set parameters # -------------------------------------- # load graph data g = cfile.obj.get_by_name("%s").data position_key = "%s" edge_key = "%s" node_label_key = "%s" # Node ids you want to create labels for create_label = [] # Assume node id's are integers nr_nodes = len(g.nodes()) position_array = np.zeros( (nr_nodes, 3) ) for i,nodeid in enumerate(g.nodes()): pos = g.node[nodeid][position_key] # apply a conversion procedure if the position # is a tuple store as string # we need a numpy array in the end - if type(pos) is str: + if type(pos) is str or unicode: pos = tuple(float(s) for s in pos[1:-1].split(',')) pos = np.array(pos) position_array[i,:] = pos x, y, z = position_array[:,0], position_array[:,1], position_array[:,2] # Retrieve the edges and create a Numpy array edges = np.array(g.edges()) nr_edges = len(edges) # Retrieve edge values ev = np.zeros( (nr_edges, 1) ) for i,d in enumerate(g.edges_iter(data=True)): ev[i] = d[2][edge_key] # ensure that we are setting the correct edge assert d[0] == edges[i,0] and d[1] == edges[i,1] # Need to subtract one because the array index starts at zero edges = edges - 1 # Create vectors which will become edges start_positions = position_array[edges[:, 0], :].T end_positions = position_array[edges[:, 1], :].T vectors = end_positions - start_positions # Perform task # ------------ # create a new figure mlab.figure() nodesource = mlab.pipeline.scalar_scatter(x, y, z, name = 'Node Source') nodes = mlab.pipeline.glyph(nodesource, scale_factor=3.0, scale_mode='none',\ name = 'Nodes', mode='cube') nodes.glyph.color_mode = 'color_by_scalar' vectorsrc = mlab.pipeline.vector_scatter(start_positions[0], start_positions[1], start_positions[2], vectors[0], vectors[1], vectors[2], name = 'Connectivity Source') # add scalar array da = tvtk.DoubleArray(name=edge_key) da.from_array(ev) vectorsrc.mlab_source.dataset.point_data.add_array(da) vectorsrc.mlab_source.dataset.point_data.scalars = da.to_array() vectorsrc.mlab_source.dataset.point_data.scalars.name = edge_key # need to update the boundaries vectorsrc.outputs[0].update() # Add a thresholding filter to threshold the edges thres = mlab.pipeline.threshold(vectorsrc, name="Thresholding") myvectors = mlab.pipeline.vectors(thres,colormap='OrRd', #mode='cylinder', name='Connections', #scale_factor=1, #resolution=20, # make the opacity of the actor depend on the scalar. #transparent=True, scale_mode = 'vector') myvectors.glyph.glyph_source.glyph_source.glyph_type = 'dash' # vectors.glyph.glyph_source.glyph_source.radius = 0.01 myvectors.glyph.color_mode = 'color_by_scalar' myvectors.glyph.glyph.clamping = False # create labels for la in create_label: row_index = la - 1 label = g.node[la][node_label_key] mlab.text3d(position_array[row_index,0], position_array[row_index,1], position_array[row_index,2], ' ' + label, name = 'Node ' + label) """ nbsscript = """ # Import Numpy import numpy as np # Import pylab for plotting from pylab import imshow, show, title # Import NetworkX import networkx as nx # Import Network based statistic import cviewer.libs.pyconto.groupstatistics.nbs as nbs # For documentation of Network-based statistic parameters # do in IPython: nbs.compute_nbs? # https://github.com/LTS5/connectomeviewer/blob/master/cviewer/libs/pyconto/groupstatistics/nbs/_nbs.py # Retrieving the data and set parameters # -------------------------------------- # Define the two groups of networks you want to compare, # setting the connectome network name. These objects need # to exist in the loaded connectome file. first = ['FirstNetwork_control', 'SecondNetwork_control'] # The same for the second group: second = ['FirstNetwork_patient', 'SecondNetwork_patient'] # Select the edge value to use for the first group first_edge_value = 'number_of_fibers' # Select the edge value to use for the second group second_edge_value = 'number_of_fibers' # More parameters for threshold (THRESH) # andd the number of # permutations (K) THRESH=3 K=10 # Can be one of 'left', 'equal', 'right' TAIL='left' SHOW_MATRIX = True # Perform task # ------------ # Get the connectome objects for the given connectome network names firstgroup = [cfile.obj.get_by_name(n) for n in first] secondgroup = [cfile.obj.get_by_name(n) for n in second] # Make sure that all networks are loaded in memory for net in firstgroup: net.load() for net in secondgroup: net.load() # Convert your network data for each group into numpy arrays nr1_networks = len(firstgroup) nr1_nrnodes = len(firstgroup[0].data.nodes()) nr2_networks = len(secondgroup) nr2_nrnodes = len(secondgroup[0].data.nodes()) X = np.zeros( (nr1_nrnodes, nr1_nrnodes, nr1_networks) ) Y = np.zeros( (nr2_nrnodes, nr2_nrnodes, nr2_networks) ) # Fill in the data from the networks for i, sub in enumerate(firstgroup): graph=sub.data # Setting the edge requested edge value as weight value for u,v,d in graph.edges(data=True): graph[u][v]['weight']=d[first_edge_value] # Retrieve the matrix X[:,:,i] = nx.to_numpy_matrix(graph) for i, sub in enumerate(secondgroup): graph=sub.data # Setting the edge requested edge value as weight value for u,v,d in graph.edges(data=True): graph[u][v]['weight']=d[second_edge_value] # Retrieve the matrix Y[:,:,i] = nx.to_numpy_matrix(graph) # Perform task # ------------ # Compute NBS, this might take a long time # and might better be done in a seperate script PVAL, ADJ, NULL = nbs.compute_nbs(X,Y,THRESH,K,TAIL) # We can now look at the connectivity matrix identified with matplotlib if SHOW_MATRIX: imshow(ADJ, interpolation='nearest') title('Edges identified by the NBS') show() # we create a networkx graph again from the adjacency matrix nbsgraph = nx.from_numpy_matrix(ADJ) # relabel nodes because the should not start at zero for our convention nbsgraph=nx.relabel_nodes(nbsgraph, lambda x: x + 1) # populate node dictionaries with attributes from first network of the first group # it must include some location information to display it for nid, ndata in firstgroup[0].data.nodes_iter(data=True): nbsgraph.node[nid] = ndata # Find a date import datetime as dt a=dt.datetime.now() ostr = '%s:%s:%s' % (a.hour, a.minute, a.second) # You can now add now the results to the connectome file # Make sure that the name is not existing yet in the connectome file cfile.obj.add_connectome_network_from_nxgraph('NBS result at %s' % ostr, nbsgraph, dtype='NBSResult') cfile.update_children() """ volrendering = """ from enthought.mayavi import mlab import numpy as np data=np.random.random( (10,10,10)) min = data.min() max = data.max() source=mlab.pipeline.scalar_field(data) vol = mlab.pipeline.volume(source, vmin=min+0.65*(max-min), vmax=min+0.9*(max-min)) """ volslice = """ # Import Mayavi mlab interface from enthought.mayavi import mlab # Import NumPy import numpy as np # Retrieving the data and set parameters # -------------------------------------- # the CVolume name volname="%s" # Retrieve volume data (as Nibabel Image) voldat = cfile.obj.get_by_name(volname).data # Retrieve the image data data = voldat.get_data() # Retrieve the affine affine = voldat.get_affine() center = np.r_[0, 0, 0, 1] # Perform task # ------------ # create A ScalarField with spacing and origin from the affine data_src = mlab.pipeline.scalar_field(data) data_src.spacing = np.diag(affine)[:3] data_src.origin = np.dot(affine, center)[:3] # Create an outline mlab.pipeline.outline(data_src) # Create a simple x-aligned image plane widget image_plane_widget = mlab.pipeline.image_plane_widget(data_src, name=volname) image_plane_widget.ipw.plane_orientation = 'x_axes' image_plane_widget.ipw.reslice_interpolate = 'nearest_neighbour' """ reportlab = """ # Credits # http://www.protocolostomy.com/2008/10/22/generating-reports-with-charts-using-python-reportlab/ from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import networkx as nx import numpy as np import datetime import tempfile import os.path PAGE_HEIGHT=defaultPageSize[1] styles = getSampleStyleSheet() Title = "Connectome Report for " Elements=[] HeaderStyle = styles["Heading1"] ParaStyle = styles["Normal"] PreStyle = styles["Code"] today = datetime.date.today() tmpdir = tempfile.gettempdir() # Retrieving the data # ------------------- # the network for the reporting net = cfile.obj.get_by_name('connectome_freesurferaparc') net.load() # the edge key de_key = 'number_of_fibers' # output file name fname = os.path.join(tmpdir, 'out.pdf') date = today.strftime('Reported on %dth, %h %Y') netw = net.data def header(txt, style=HeaderStyle, klass=Paragraph, sep=0.3): s = Spacer(0.2*inch, sep*inch) para = klass(txt, style) sect = [s, para] result = KeepTogether(sect) return result def p(txt): return header(txt, style=ParaStyle, sep=0.1) def pre(txt): s = Spacer(0.1*inch, 0.1*inch) p = Preformatted(txt, PreStyle) precomps = [s,p] result = KeepTogether(precomps) return result def go(fname): doc = SimpleDocTemplate(fname) doc.build(Elements) mytitle = header(Title + '"' + cfile.obj.get_connectome_meta().get_title() + '"') mydate = header(date, sep=0.1, style=ParaStyle) mytitlenet = header(net.get_name() + " (CNetwork)") for u,v,d in netw.edges_iter(data=True): edgval = netw.edge[u][v][de_key] if edgval > 0: netw.edge[u][v]['weight'] = 1 else: netw.edge[u][v]['weight'] = 1 b=nx.to_numpy_matrix(netw) fig = plt.figure() fig.suptitle("Binary Connection matrix") aa= plt.imshow(b, interpolation='nearest', cmap=plt.cm.Greys, vmin = b.min(), vmax=b.max()) fig.savefig(os.path.join(tmpdir, 'matrix.png')) fig.clear() fig.suptitle("Degree distribution") plt.hist(netw.degree().values(),30) fig.savefig(os.path.join(tmpdir,'distri.png')) # measures if nx.is_connected(netw): isit = "Yes" else: isit = "No" me1 = p("Number of Nodes: " + str(netw.number_of_nodes())) me2 = p("Number of Edges: " + str(netw.number_of_edges())) me3 = p("Is network connected: " + isit) me4 = p("Number of connected components: " + str(nx.number_connected_components(netw))) me44 = p("Average node degree: %.2f" % np.mean(netw.degree().values())) me5 = p("Average unweighted shortest path length: %.2f" % nx.average_shortest_path_length(netw, weighted = False)) me6 = p("Average clustering coefficient: %.2f" % nx.average_clustering(netw)) logo = os.path.join(tmpdir, "matrix.png") im1 = Image(logo, 300,225) logo = os.path.join(tmpdir, "distri.png") im2 = Image(logo, 250,188) codesection = [mytitle, mydate, mytitlenet, me1, me2, me3, me4,me44, me5, me6, im1, im2] src = KeepTogether(codesection) Elements.append(src) go(fname) """
LTS5/connectomeviewer
289af0b9a5823adcf8d6a01d9a692919fe982664
Traits should be 4.0.0
diff --git a/cviewer/info.py b/cviewer/info.py index 336db10..83a1cc8 100644 --- a/cviewer/info.py +++ b/cviewer/info.py @@ -1,83 +1,83 @@ ''' Release data for Connectome Viewer This script should do no imports. It only defines variables. ''' version = '2.0.0' is_release = False long_description = \ """ Connectome Viewer - A Framework for the Visualization and Analysis of Multi-Modal Multi-Scale Connectome Data in Python The aim of Connectome Viewer is to produce a platform-independent Python framework for the analysis and visualization of Connectome data using an open development model. The Connectome Viewer is a extensible, scriptable, pythonic software tool for visualization and analysis in neuroimaging research on many spatial scales. Employing the Connectome File Format, diverse data such as networks, surfaces, volumes, tracks and metadata are handled and integrated. Specifically, we aim to: 1. Provide an open source, mixed language scientific programming framework for rapid development and quantitative analysis 2. Provide a visualization platform to readily visualize multi-modal data for interactive data exploration 3. Allow for enhanced brain connectivity analysis and plotting 4. Provide the Connectome File Format to store a wide range of data types: metadata, networks, surfaces, volumes, fiber tracks, time series 5. Create and maintain a wide base of developers to contribute plugins to this framework. 6. To integrate this framework with software packages in neuroimaging and provide an easily installable bundle. """ # these have to be done per install_requires envisagecore_min_version = '3.1.2' traitsbackendwx_min_version = '3.2.1' envisageplugins_min_version = '3.1.2' enthoughtbase_min_version = '3.0.4' traitsgui_min_version = '3.1.1' chaco_min_version = '3.2.1' lxml_min_version = '2.2.6' pymysql_min_version = '0.2' # these can be done safely traits_min_version = '3.2.0' networkx_min_version = '1.4' mayavi_min_version = '3.3.2' h5py_min_version = '1.2.0' scipy_min_version = '0.5' # for ubuntu 10.04 ### envisagecore_min_version = '3.1.1' # python-envisagecore envisageplugins_min_version = '3.1.1' # python-envisageplugins traitsbackendwx_min_version = '3.2.0' # python-traitsbackendwx traitsbackendqt_min_version = '3.2.0' # python-traitsbackendqt traitsgui_min_version = '3.1.0' # python-traitsgui -traits_min_version = '3.2.0' # python-traits +traits_min_version = '4.0.0' # python-traits python_enthought_traits_ui = '3.1.0' # python-enthought-traits-ui enthoughtbase_min_version = '3.0.3' # python-enthoughtbase chaco_min_version = '3.2.0' # python-chaco lxml_min_version = '2.2.4' # python-lxml scipy_min_version = '0.5' # python-scipy (0.7.0) numpy_min_version = '1.3.0' # python-numpy h5py_min_version = '1.2.1' # python-h5py mayavi_min_version = '3.3.0' # mayavi2 # python-apptools (3.3.0), python-enthought-traits (3.1.0), python-numpy (1.3.0) # outdated or not available pymysql_min_version = '0.2' # not available networkx_min_version = '1.4' # python-network (0.99)
LTS5/connectomeviewer
8e4cc74e9f2b52a97dc5ecb68b971708c65c8edf
BF: Networks attribute could already be tuple
diff --git a/cviewer/plugins/codeoracle/scripts.py b/cviewer/plugins/codeoracle/scripts.py index bd51233..8321738 100644 --- a/cviewer/plugins/codeoracle/scripts.py +++ b/cviewer/plugins/codeoracle/scripts.py @@ -159,867 +159,868 @@ def showfibfos(fibarr, colarr, percentage = 100): cu = InteractiveCurves(curves = fibarr2.tolist(), colors = colarr2) w=World() w.add(cu) wi = Window(caption="Multi-Modal 1", width = 800, height = 800) wi.attach(w) def preparecolorarray(clustering, number_of_fibers): colors=np.zeros((number_of_fibers,4)) for c in clustering: color=np.random.rand(1,4) for i in clustering[c]['indices']: colors[i]=color colors[:,3] = 1.0 # need alpha channel return colors def angle(x,y): return np.rad2deg(np.arccos(np.dot(x,y)/np.sqrt(np.dot(x,x))/np.sqrt(np.dot(y,y)))) def compute_angle_array(tracksobj, downsampling = 3): n = tracksobj.shape[0] fiberangles = np.zeros( (n, 1) ) if downsampling == 3: for i in xrange(n): x=tracksobj[i][0]-tracksobj[i][1] y=tracksobj[i][2]-tracksobj[i][1] fiberangles[i] = angle(x,y) return fiberangles # start script # Compute the distance array dist = compute_start_end_distances(endpoints) # Inspect histogram to find xcenterline # hist(endpoints[:,0,0],200) # -> e.g. found x coordinate 103 # compute distance mean distmean = np.mean(endpoints[:,:,0],axis=1) # noccidx = filterfibersidx(distmean, 70, 104) # good to have cc and few corticospinal noccidx = filterfibersidxcomplement(distmean, 70, 104) # good to have cc and few corticospinal # change hemi parameter to switch hemisphere onlyleftidx = filterhemisphere(distmean, 84, hemi = 1) noccidx = np.intersect1d(noccidx , onlyleftidx) # 4. filter out corpous callosum fibers # noccidx = compfilterccidx(endpoints, 84, False) noccfibers = fibers[noccidx] # 5. show fibers without cc #showfibfvtk(noccfibers,randcolarr(noccfibers), 1000) # 6. look at distance histogram #hist(dist,100) # 7. compute new distance histogram for fibers without cc distnocc = compute_start_end_distances(endpoints[noccidx,:,:]) meancuvnocc = meancurv[noccidx] #hist(distnocc,100) #hist(meancuvnocc,100) # 8. find short fibers and show them #shortfibers = noccfibers[filterfibersidx(distnocc, 0, 30)] #showfibfvtk(shortfibers,randcolarr(shortfibers), 100) # using meancurvature shortfibers = noccfibers[filterfibersidx2(distnocc, 10, 30, meancuvnocc, 0.05)] #showfibfvtk(shortfibers,randcolarr(shortfibers), 10) #shortfibers = noccfibers[filterfibersidx(dist, 8, 40)] # 120-180: long range # around 85: some projection, cortico spinal, temporal association # 8-40: enough U fibers # 9. fiber clustering fiblist = shortfibers.tolist() print("Downsampling...") tracks=[tm.downsample(t,3) for t in fiblist] # calculate the angle of downsampled fibers tracksobj=np.array(tracks, dtype=np.object) fiberangles = compute_angle_array(tracksobj) # filter fibers fiberangleidx = filterfibersidx(fiberangles, 20, 80) # create new short fiber set shortfibersnew = shortfibers[fiberangleidx] tracksobjnew = tracksobj[fiberangleidx] print("Clustering....") now=time.clock() C=td.local_skeleton_clustering(tracksobjnew.tolist(),d_thr=10) print('Done in %.2f s' % (time.clock()-now,)) # 10. prepare color array and show mycols = preparecolorarray(C, len(shortfibersnew)) #showfibfvtk(shortfibersnew,mycols, 10) #mycols = preparecolorarray(C, len(shortfibers)) #mycols = randcolarr(shortfibers) #showfibfvtk(shortfibers,mycols, 50) # only show left hemisphere # show number of fibers in each bundle histogram a=np.array([(id,v['N']) for id, v in C.items()]) idx=np.where(a[:,1] < 100)[0] allidx = np.arange(tracksobjnew.shape[0]) for i in idx: idxremove = C[i]['indices'] allidx = np.lib.arraysetops.setdiff1d(allidx, C[i]['indices']) #del C[i] shortfibersnew2 = shortfibersnew[allidx] tracksobjnew2 = tracksobjnew[allidx] C2=td.local_skeleton_clustering(tracksobjnew2.tolist(),d_thr=9) mycols2 = preparecolorarray(C2, len(shortfibersnew2)) # show with fos showfibfvtk(shortfibersnew2,mycols2, 10) #showfibfos(shortfibersnew2,mycols2, 50) #hist(a,100) # use fos to show with bigger sized tubes """ percentage=1 fibarr2 = shortfibersnew2[::percentage] colarr2 = mycols2[::percentage].astype('f4') cu = InteractiveCurves(curves = fibarr2.tolist(), colors = colarr2, line_width = 6.0) w=World() w.add(cu) wi = Window(caption="Multi-Modal 1", width = 1200, height = 900, bgcolor = (1,1,1,0)) wi.attach(w) # w.delete(cu) """ ''' threedviz2 = """ # Modified from NetworkX drawing # https://networkx.lanl.gov/trac/browser/networkx/examples/drawing/mayavi2_spring.py import networkx as nx import numpy as np from enthought.mayavi import mlab # Retrieve NetworkX graph G = cfile.obj.get_by_name("connectome_freesurferaparc").data # Key value on the nodes to transform to scalar value for node coloring node_scalar_key = "dn_correspondence_id" # Network Layouting: 2d circular layout pos=nx.circular_layout(G,dim=2,scale=1) # numpy array of x,y,z positions in sorted node order xyz=np.array([pos[v] for v in sorted(G)]) # adding zero z coordinate xyz = np.hstack( (xyz, np.zeros( (len(xyz), 1) ) ) ) # Network Layouting: 3d spring layout #pos=nx.spring_layout(G,dim=3) # numpy array of x,y,z positions in sorted node order #xyz=np.array([pos[v] for v in sorted(G)]) # If you do not want to apply a layouting algorithm # You can create the xyz array from your node positions # as displayed in Code Oracle "3D Network" # scalar colors scalars = np.zeros( (len(G.nodes()),) ) for i,data in enumerate(G.nodes(data=True)): scalars[i] = float(data[1][node_scalar_key]) mlab.figure(1, bgcolor=(0, 0, 0)) mlab.clf() pts = mlab.points3d(xyz[:,0], xyz[:,1], xyz[:,2], scalars, scale_factor=0.05, scale_mode='none', colormap='Blues', resolution=20) # Defines only the connectivity # You can combine this script with the "3D Network" Code Oracle pts.mlab_source.dataset.lines = np.array(G.edges()) tube = mlab.pipeline.tube(pts, tube_radius=0.008) mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8)) # You can store the resulting figure programmatically # mlab.savefig('mynetwork.png') """ nipypebet = """ # Prerequisite: # 1. You need to have Nipype installed on your system. You can check this by entering # import nipype # In the IPython console. If it gives an error, you might want to install it from NeuroDebian. # See http://neuro.debian.net/ - Documentation is on http://nipy.sourceforge.net/nipype/ # 2. For this simple brain extraction script, you need to have FSL installed. # Goal: # This script shows how to extract the brain using BET through the Nipype interface. # It is derived from http://nipy.sourceforge.net/nipype/users/dartmouth_workshop_2010.html # As an input, you need a T1-weighted image that as an input to the Nipype node. rawimage = cfile.obj.get_by_name('MYRAWT1IMAGE') # Let's check if the metadata agrees with what is expected (it should say "T1-weighted") print rawimage.dtype # We do not necessarily need to load the connectome object - if the connectome file is extracted # locally. We just need to retrieve the absolute file path rawimage_pwd = rawimage.get_abs_path() # We need the Nipype FSL interface import nipype.interfaces.fsl as fsl # We set the FSL default output type to compressed Nifti-1 fsl.FSLCommand.set_default_output_type('NIFTI_GZ') # We want to store the processed file in the temporary folder for now. fname_out = '/tmp/only_brain.nii.gz' # Now, we run the Nipype BET node, providing the correct input result = fsl.BET(in_file=rawimage_pwd, out_file = fname_out ).run() # We can print the result print result.outputs # To add the processed data file to the currently loaded connectome file, ... #cvol = cf.CVolume(name="BETed brain", src=fname_out, fileformat='Nifti1GZ', dtype='T1-weighted') #cfile.obj.add_connectome_volume(cvol) # Make sure that you save the connectome file if you want to keep the processed file. """ pushpull = """ # Prerequisite: # 1. For this script to run, you need to have PyXNAT installed # on your PYTHONPATH system. You can get it from http://packages.python.org/pyxnat/ # 2. You need to have access to an XNAT server and a project # You can create a login and project here: # http://central.xnat.org/ # http://sandbox.xnat.org/ # Goal: # 1. We want to push a connectome file to an XNAT server # 2. We want to pull a connectome file from an XNAT server # Hint: # If you plan to retrieve or upload big datasets, it is recommended to run this # script in an external Python shell, as long script executions block the IPython # shell within the Connectome Viewer. # We assume that a connectome file is currently loaded. For testing purposes, # it is beneficial if the files are not too big. # We need to load cfflib import cfflib as cf # Retrieve the currently loaded connectome object to push to the XNAT Server a = cfile.obj # You need to setup the XNAT connection cf.set_xnat_connection({'server': 'http://sandbox.xnat.org', 'user':'YOURUSERNAME', 'password':'YOURPASSWORD'}) # You need to have write access on the XNAT Server given. You will need the projectid to push # data to the server. In addition, you need to provide a subjectid and an experimentid. If overwrite # is set to True, remote files are overwritten by the local files. # Then, you can push the connectome file to XNAT cf.xnat_push( connectome_obj = a, projectid = "YOURPROJECTID", subjectid = "SUBJECTID", experimentid = "EXPID", overwrite = False) # NB: On the remote server, unique identifier for the subject and experiment id are generated, using the project id. # The push operation may take some time. # Similarly as you pushed a connectome file to XNAT, you can pull it again from the server. # You need the same identifiers to retrieve the data again. In addition, you need to provide a storage # path for the retrieved files. #cf.xnat_pull( projectid = "YOURPROJECTID", subjectid = "SUBJECTID", experimentid = "EXPID", '/YOUR/FILE/STORAGE/PATH') # In case you want to load the pulled connectome object, you can load it using cfflib #import cfflib as cf; mynewcon = cf.load( '/YOUR/FILE/STORAGE/PATH/meta.cml' ) """ surfscript = """ # Importing Mayavi mlab interface from enthought.mayavi import mlab # Retrieving the data # ------------------- # surface data from connectome file surface_file_vertices = cfile.obj.get_by_name("%s") vertices = surface_file_vertices.data.darrays[%s].data surface_file_faces = cfile.obj.get_by_name("%s") faces = surface_file_faces.data.darrays[%s].data labelname = "%s" surface_file_labels = cfile.obj.get_by_name(labelname) # Sanity check # ------------ # ensure that (triangluar) faces have dimension (N,3) if len(faces.shape) == 1: faces = faces.reshape( (len(faces) / 3, 3) ) # check for labels if labelname == "None": labels = None else: labels = surface_file_labels.data.darrays[%s].data # Ensure correct dimension (1-D) for labels labels = labels.ravel() # Ensure that each vertices has a corresponding label assert vertices.shape[0] == len(labels) # Perform task # ------------ # Create triangular surface mesh x, y, z = vertices[:,0], vertices[:,1], vertices[:,2] mlab.triangular_mesh(x, y, z, faces, scalars = labels) """ conmatrix = """ # Importing NetworkX import networkx as nx # Import the Connectome Matrix Viewer from cviewer.visualization.matrix.con_matrix_viewer import ConnectionMatrixViewer # Retrieving the data # ------------------- # retrieve the graph g = cfile.obj.get_by_name("%s").data # set the node key to use the labels nodelabelkey = "%s" # Defining some helper functions # ------------------------------ def relabel_to_int(graph): " Relabel string node ids to integer " def intmap(x): return int(x) return nx.relabel_nodes(graph,intmap) def get_nodelabels(graph, nodekey = 'dn_label'): " Retrieve a list of node labels " g = relabel_to_int(graph) a = [] return [v[nodekey] for n,v in g.nodes_iter(data=True)] def get_edge_values(graph): " Retrieve valid edge keys " if len(graph.edges()) == 0: return edi = graph.edges_iter(data=True) u,v,ed = edi.next() ret = [] for k,v in ed.items(): if isinstance(v, float) or isinstance(v, int): ret.append(k) return ret def get_matdict(graph): matdict = {} g = relabel_to_int(graph) # grab keys from the first edge, discarding id dl = get_edge_values(g) # create numpy matrix for each key using recarray matrec = nx.to_numpy_recarray(g, dtype=zip(dl, [float]*len(dl)) ) for k in dl: matdict[k] = matrec[k] return matdict def invoke_matrix_viewer(graph, nodelabelkey = 'dn_label'): " Invoke the Connectome Matrix Viewer " cmatrix_viewer = ConnectionMatrixViewer(get_nodelabels(graph, nodekey = nodelabelkey), get_matdict(graph)) cmatrix_viewer.edit_traits() # Perform task # ------------ invoke_matrix_viewer(g, nodelabelkey) """ conmatrixpyplot = """ # Importing NetworkX import networkx as nx # Import Pylab from pylab import imshow, show, cm # Import Numpy import numpy as np # Retrieving the data # ------------------- # retrieve the graph g = cfile.obj.get_by_name("%s").data # define the edge key to plot edgekey = "%s" # binarize matrix binarize = False # Defining some helper functions # ------------------------------ def show_matrix(a, edge, binarize = False): for u,v,d in a.edges_iter(data=True): a.edge[u][v]['weight'] = a.edge[u][v][edge] bb=nx.to_numpy_matrix(a) if binarize: c=np.zeros(bb.shape) c[bb>0] = 1 b = c else: b = bb imshow(b, interpolation='nearest', cmap=cm.jet, vmin = b.min(), vmax=b.max()) show() # Perform task # ------------ show_matrix(g, edgekey, binarize) """ ctrackedge = """ # Importing Numpy import numpy as np # Import Dipy Visualization import dipy.viz.fvtk as fvtk # Retrieving the data and set parameters # -------------------------------------- a = cfile.obj.get_by_name("Final Tractography (freesurferaparc)").get_fibers_as_numpy() fiberlabels = cfile.obj.get_by_name("Final fiber labels (freesurferaparc)").data fromid = 8 toid = 10 # Defining some helper functions # ------------------------------ def sidx(arr, fromval, toval): " Returns the indices that are equal to a given value " return np.where( (arr[:,0] == fromval) & (arr[:,1] == toval) )[0] def randcolarr(arr): " Returns a random color for each row in arr " return np.random.rand(1,3).repeat(len(arr),axis=0) def showfibfvtk(fibarr, colarr, percentage = 100): fibarr2 = fibarr[::percentage] colarr2 = colarr[::percentage] fibarr2list = fibarr2.tolist() r=fvtk.ren() #fvtk.add(r,fvtk.axes()) r.SetBackground(1, 1, 1) [fvtk.add(r,fvtk.line(ele, colarr2[i,:])) for i, ele in enumerate(fibarr2list)]; fvtk.show(r, title = "Fibers", size = (500,500)) # Perform task # ------------ idx = sidx(fiberlabels, fromid, toid) showfibfvtk(a[idx], randcolarr(a[idx]), 100) """ netscript = """ # Importing NumPy import numpy as np # Importing Mayavi mlab and tvtk packages from enthought.mayavi import mlab from enthought.tvtk.api import tvtk # Retrieving the data and set parameters # -------------------------------------- # load graph data g = cfile.obj.get_by_name("%s").data position_key = "%s" edge_key = "%s" node_label_key = "%s" # Node ids you want to create labels for create_label = [] # Assume node id's are integers nr_nodes = len(g.nodes()) position_array = np.zeros( (nr_nodes, 3) ) for i,nodeid in enumerate(g.nodes()): pos = g.node[nodeid][position_key] # apply a conversion procedure if the position # is a tuple store as string # we need a numpy array in the end - pos = tuple(float(s) for s in pos[1:-1].split(',')) + if type(pos) is str: + pos = tuple(float(s) for s in pos[1:-1].split(',')) pos = np.array(pos) position_array[i,:] = pos x, y, z = position_array[:,0], position_array[:,1], position_array[:,2] # Retrieve the edges and create a Numpy array edges = np.array(g.edges()) nr_edges = len(edges) # Retrieve edge values ev = np.zeros( (nr_edges, 1) ) for i,d in enumerate(g.edges_iter(data=True)): ev[i] = d[2][edge_key] # ensure that we are setting the correct edge assert d[0] == edges[i,0] and d[1] == edges[i,1] # Need to subtract one because the array index starts at zero edges = edges - 1 # Create vectors which will become edges start_positions = position_array[edges[:, 0], :].T end_positions = position_array[edges[:, 1], :].T vectors = end_positions - start_positions # Perform task # ------------ # create a new figure mlab.figure() nodesource = mlab.pipeline.scalar_scatter(x, y, z, name = 'Node Source') nodes = mlab.pipeline.glyph(nodesource, scale_factor=3.0, scale_mode='none',\ name = 'Nodes', mode='cube') nodes.glyph.color_mode = 'color_by_scalar' vectorsrc = mlab.pipeline.vector_scatter(start_positions[0], start_positions[1], start_positions[2], vectors[0], vectors[1], vectors[2], name = 'Connectivity Source') # add scalar array da = tvtk.DoubleArray(name=edge_key) da.from_array(ev) vectorsrc.mlab_source.dataset.point_data.add_array(da) vectorsrc.mlab_source.dataset.point_data.scalars = da.to_array() vectorsrc.mlab_source.dataset.point_data.scalars.name = edge_key # need to update the boundaries vectorsrc.outputs[0].update() # Add a thresholding filter to threshold the edges thres = mlab.pipeline.threshold(vectorsrc, name="Thresholding") myvectors = mlab.pipeline.vectors(thres,colormap='OrRd', #mode='cylinder', name='Connections', #scale_factor=1, #resolution=20, # make the opacity of the actor depend on the scalar. #transparent=True, scale_mode = 'vector') myvectors.glyph.glyph_source.glyph_source.glyph_type = 'dash' # vectors.glyph.glyph_source.glyph_source.radius = 0.01 myvectors.glyph.color_mode = 'color_by_scalar' myvectors.glyph.glyph.clamping = False # create labels for la in create_label: row_index = la - 1 label = g.node[la][node_label_key] mlab.text3d(position_array[row_index,0], position_array[row_index,1], position_array[row_index,2], ' ' + label, name = 'Node ' + label) """ nbsscript = """ # Import Numpy import numpy as np # Import pylab for plotting from pylab import imshow, show, title # Import NetworkX import networkx as nx # Import Network based statistic import cviewer.libs.pyconto.groupstatistics.nbs as nbs # For documentation of Network-based statistic parameters # do in IPython: nbs.compute_nbs? # https://github.com/LTS5/connectomeviewer/blob/master/cviewer/libs/pyconto/groupstatistics/nbs/_nbs.py # Retrieving the data and set parameters # -------------------------------------- # Define the two groups of networks you want to compare, # setting the connectome network name. These objects need # to exist in the loaded connectome file. first = ['FirstNetwork_control', 'SecondNetwork_control'] # The same for the second group: second = ['FirstNetwork_patient', 'SecondNetwork_patient'] # Select the edge value to use for the first group first_edge_value = 'number_of_fibers' # Select the edge value to use for the second group second_edge_value = 'number_of_fibers' # More parameters for threshold (THRESH) # andd the number of # permutations (K) THRESH=3 K=10 # Can be one of 'left', 'equal', 'right' TAIL='left' SHOW_MATRIX = True # Perform task # ------------ # Get the connectome objects for the given connectome network names firstgroup = [cfile.obj.get_by_name(n) for n in first] secondgroup = [cfile.obj.get_by_name(n) for n in second] # Make sure that all networks are loaded in memory for net in firstgroup: net.load() for net in secondgroup: net.load() # Convert your network data for each group into numpy arrays nr1_networks = len(firstgroup) nr1_nrnodes = len(firstgroup[0].data.nodes()) nr2_networks = len(secondgroup) nr2_nrnodes = len(secondgroup[0].data.nodes()) X = np.zeros( (nr1_nrnodes, nr1_nrnodes, nr1_networks) ) Y = np.zeros( (nr2_nrnodes, nr2_nrnodes, nr2_networks) ) # Fill in the data from the networks for i, sub in enumerate(firstgroup): graph=sub.data # Setting the edge requested edge value as weight value for u,v,d in graph.edges(data=True): graph[u][v]['weight']=d[first_edge_value] # Retrieve the matrix X[:,:,i] = nx.to_numpy_matrix(graph) for i, sub in enumerate(secondgroup): graph=sub.data # Setting the edge requested edge value as weight value for u,v,d in graph.edges(data=True): graph[u][v]['weight']=d[second_edge_value] # Retrieve the matrix Y[:,:,i] = nx.to_numpy_matrix(graph) # Perform task # ------------ # Compute NBS, this might take a long time # and might better be done in a seperate script PVAL, ADJ, NULL = nbs.compute_nbs(X,Y,THRESH,K,TAIL) # We can now look at the connectivity matrix identified with matplotlib if SHOW_MATRIX: imshow(ADJ, interpolation='nearest') title('Edges identified by the NBS') show() # we create a networkx graph again from the adjacency matrix nbsgraph = nx.from_numpy_matrix(ADJ) # relabel nodes because the should not start at zero for our convention nbsgraph=nx.relabel_nodes(nbsgraph, lambda x: x + 1) # populate node dictionaries with attributes from first network of the first group # it must include some location information to display it for nid, ndata in firstgroup[0].data.nodes_iter(data=True): nbsgraph.node[nid] = ndata # Find a date import datetime as dt a=dt.datetime.now() ostr = '%s:%s:%s' % (a.hour, a.minute, a.second) # You can now add now the results to the connectome file # Make sure that the name is not existing yet in the connectome file cfile.obj.add_connectome_network_from_nxgraph('NBS result at %s' % ostr, nbsgraph, dtype='NBSResult') cfile.update_children() """ volrendering = """ from enthought.mayavi import mlab import numpy as np data=np.random.random( (10,10,10)) min = data.min() max = data.max() source=mlab.pipeline.scalar_field(data) vol = mlab.pipeline.volume(source, vmin=min+0.65*(max-min), vmax=min+0.9*(max-min)) """ volslice = """ # Import Mayavi mlab interface from enthought.mayavi import mlab # Import NumPy import numpy as np # Retrieving the data and set parameters # -------------------------------------- # the CVolume name volname="%s" # Retrieve volume data (as Nibabel Image) voldat = cfile.obj.get_by_name(volname).data # Retrieve the image data data = voldat.get_data() # Retrieve the affine affine = voldat.get_affine() center = np.r_[0, 0, 0, 1] # Perform task # ------------ # create A ScalarField with spacing and origin from the affine data_src = mlab.pipeline.scalar_field(data) data_src.spacing = np.diag(affine)[:3] data_src.origin = np.dot(affine, center)[:3] # Create an outline mlab.pipeline.outline(data_src) # Create a simple x-aligned image plane widget image_plane_widget = mlab.pipeline.image_plane_widget(data_src, name=volname) image_plane_widget.ipw.plane_orientation = 'x_axes' image_plane_widget.ipw.reslice_interpolate = 'nearest_neighbour' """ reportlab = """ # Credits # http://www.protocolostomy.com/2008/10/22/generating-reports-with-charts-using-python-reportlab/ from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import networkx as nx import numpy as np import datetime import tempfile import os.path PAGE_HEIGHT=defaultPageSize[1] styles = getSampleStyleSheet() Title = "Connectome Report for " Elements=[] HeaderStyle = styles["Heading1"] ParaStyle = styles["Normal"] PreStyle = styles["Code"] today = datetime.date.today() tmpdir = tempfile.gettempdir() # Retrieving the data # ------------------- # the network for the reporting net = cfile.obj.get_by_name('connectome_freesurferaparc') net.load() # the edge key de_key = 'number_of_fibers' # output file name fname = os.path.join(tmpdir, 'out.pdf') date = today.strftime('Reported on %dth, %h %Y') netw = net.data def header(txt, style=HeaderStyle, klass=Paragraph, sep=0.3): s = Spacer(0.2*inch, sep*inch) para = klass(txt, style) sect = [s, para] result = KeepTogether(sect) return result def p(txt): return header(txt, style=ParaStyle, sep=0.1) def pre(txt): s = Spacer(0.1*inch, 0.1*inch) p = Preformatted(txt, PreStyle) precomps = [s,p] result = KeepTogether(precomps) return result def go(fname): doc = SimpleDocTemplate(fname) doc.build(Elements) mytitle = header(Title + '"' + cfile.obj.get_connectome_meta().get_title() + '"') mydate = header(date, sep=0.1, style=ParaStyle) mytitlenet = header(net.get_name() + " (CNetwork)") for u,v,d in netw.edges_iter(data=True): edgval = netw.edge[u][v][de_key] if edgval > 0: netw.edge[u][v]['weight'] = 1 else: netw.edge[u][v]['weight'] = 1 b=nx.to_numpy_matrix(netw) fig = plt.figure() fig.suptitle("Binary Connection matrix") aa= plt.imshow(b, interpolation='nearest', cmap=plt.cm.Greys, vmin = b.min(), vmax=b.max()) fig.savefig(os.path.join(tmpdir, 'matrix.png')) fig.clear() fig.suptitle("Degree distribution") plt.hist(netw.degree().values(),30) fig.savefig(os.path.join(tmpdir,'distri.png')) # measures if nx.is_connected(netw): isit = "Yes" else: isit = "No" me1 = p("Number of Nodes: " + str(netw.number_of_nodes())) me2 = p("Number of Edges: " + str(netw.number_of_edges())) me3 = p("Is network connected: " + isit) me4 = p("Number of connected components: " + str(nx.number_connected_components(netw))) me44 = p("Average node degree: %.2f" % np.mean(netw.degree().values())) me5 = p("Average unweighted shortest path length: %.2f" % nx.average_shortest_path_length(netw, weighted = False)) me6 = p("Average clustering coefficient: %.2f" % nx.average_clustering(netw)) logo = os.path.join(tmpdir, "matrix.png") im1 = Image(logo, 300,225) logo = os.path.join(tmpdir, "distri.png") im2 = Image(logo, 250,188) codesection = [mytitle, mydate, mytitlenet, me1, me2, me3, me4,me44, me5, me6, im1, im2] src = KeepTogether(codesection) Elements.append(src) go(fname) """
LTS5/connectomeviewer
842a1166e62f87c1cc450bb62e247db7dfc1bd86
Remove welcome perspective import
diff --git a/cviewer/plugins/ui/cviewer_ui_plugin.py b/cviewer/plugins/ui/cviewer_ui_plugin.py index 926b547..1fd408e 100644 --- a/cviewer/plugins/ui/cviewer_ui_plugin.py +++ b/cviewer/plugins/ui/cviewer_ui_plugin.py @@ -1,236 +1,234 @@ """ The ConntecomeViewer UI Plugin """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Partly modified version; mayavi_ui_plugin.py # Author: Prabhu Ramachandran <prabhu [at] aero . iitb . ac . in> # Copyright (c) 2008, Enthought, Inc. # License: BSD Style. # Enthought library imports from enthought.envisage.api import Plugin from enthought.traits.api import List, on_trait_change from enthought.pyface.workbench.api import Perspective, PerspectiveItem from enthought.etsconfig.api import ETSConfig # View IDs ENGINE_VIEW = 'enthought.mayavi.core.ui.engine_view.EngineView' CURRENT_SELECTION_VIEW = 'enthought.mayavi.core.engine.Engine.current_selection' SHELL_VIEW = 'enthought.plugins.python_shell_view' LOGGER_VIEW = 'enthought.logger.plugin.view.logger_view.LoggerView' ID = 'connectome.cviewer.ui' CFFVIEW = 'cviewer.plugins.cff2.ui.cff_view.CFFView' # This module's package. PKG = '.'.join(__name__.split('.')[:-1]) -from welcome.perspective import WelcomePerspective - # Logging imports import logging logger = logging.getLogger('root.'+__name__) ############################################################################### # ViewerPerspective ############################################################################### class ViewerPerspective(Perspective): """ The default perspective for the ConnectomeViewer """ # the unique ID id = "cviewer.perspective.viewer_perspective" # The perspective's name. name = 'ViewerPerspective' # Should this perspective be enabled or not? enabled = True # Should the editor area be shown in this perspective? show_editor_area = True # The contents of the perspective. contents = List() def _contents_default(self): # The contents of the perspective. Add the views here with position contents = [ PerspectiveItem(id=CFFVIEW, position='left', width=0.6), PerspectiveItem(id=ENGINE_VIEW, position='bottom', relative_to=CFFVIEW), PerspectiveItem(id=SHELL_VIEW, position='bottom', height=0.2), # XXX: deactivate mayavi views per default as not to confuse end-users too much #PerspectiveItem(id=CURRENT_SELECTION_VIEW, position='bottom', # relative_to=ENGINE_VIEW), ] return contents ############################################################################### # `CViewerUIPlugin` class. ############################################################################### class CViewerUIPlugin(Plugin): """ A Connectome Viewer user interface plugins. This plugin contributes the actions, menues, preference pages etc. """ # extension points this plugin contributes to PERSPECTIVES = 'enthought.envisage.ui.workbench.perspectives' PREFERENCES = 'enthought.envisage.preferences' PREFERENCES_PAGES = 'enthought.envisage.ui.workbench.preferences_pages' #BANNER = 'enthought.plugins.ipython_shell.banner' ACTION_SETS = 'enthought.envisage.ui.workbench.action_sets' #COMMANDS = 'enthought.plugins.python_shell.commands' VIEWS = "enthought.envisage.ui.workbench.views" # The plugin's unique identifier. id = ID # The plugin's name (suitable for displaying to the user). name = 'ConnectomeViewer UI' # Contributions to the views extension point made by this plug-in. views = List(contributes_to=VIEWS) # Perspectives. perspectives = List(contributes_to=PERSPECTIVES) # actions action_sets = List(contributes_to=ACTION_SETS) # Preferences preferences = List(contributes_to=PREFERENCES) # Preference pages preferences_pages = List(contributes_to=PREFERENCES_PAGES) # Ipython banner #banner = List(contributes_to=BANNER) # more imports needed #commands = List(contributes_to=COMMANDS) ##################################################################### # Private methods. def _views_default(self): """ Trait initialiser. """ return [self._engine_view_factory, self._current_selection_view_factory,] def _perspectives_default(self): """ Trait initializer. """ return [ViewerPerspective] def _action_sets_default(self): """ Trait initializer. """ from cviewer_ui_action_set import CViewerUIActionSet return [CViewerUIActionSet] def _preferences_default(self): """ Trait initializer. """ return ['pkgfile://%s/preferences.ini' % PKG] def _preferences_pages_default(self): """ Trait initializer. """ from cviewer_ui_preferences_page import CViewerUIPreferencesPage return [CViewerUIPreferencesPage] ###################################################################### # Private methods. (imported from MayaviUI plugin) def _engine_view_factory(self, window, **traits): """ Factory method for engine views. """ from enthought.pyface.workbench.traits_ui_view import \ TraitsUIView from enthought.mayavi.core.ui.engine_view import \ EngineView engine_view = EngineView(engine=self._get_engine(window)) tui_engine_view = TraitsUIView(obj=engine_view, id=ENGINE_VIEW, name='MayaVi Visualization Tree', window=window, position='left', **traits ) return tui_engine_view def _current_selection_view_factory(self, window, **traits): """ Factory method for the current selection of the engine. """ from enthought.pyface.workbench.traits_ui_view import \ TraitsUIView engine = self._get_engine(window) tui_engine_view = TraitsUIView(obj=engine, view='current_selection_view', id=CURRENT_SELECTION_VIEW, name='Visualization Object Editor', window=window, position='bottom', relative_to=ENGINE_VIEW, **traits ) return tui_engine_view def _get_engine(self, window): """Return the Mayavi engine of the particular window.""" from enthought.mayavi.core.engine import Engine return window.get_service(Engine) def _get_script(self, window): """Return the `enthought.mayavi.plugins.script.Script` instance of the window.""" from enthought.mayavi.plugins.script import Script return window.get_service(Script) ###################################################################### # Trait handlers. @on_trait_change('application.gui:started') def _on_application_gui_started(self, obj, trait_name, old, new): """This is called when the application's GUI is started. The method binds the `Script` and `Engine` instance on the interpreter. """ # This is called when the application trait is set but we don't # want to do anything at that point. if trait_name != 'started' or not new: return # Get the script service. app = self.application window = app.workbench.active_window script = self._get_script(window) # Get a hold of the Python shell view. id = SHELL_VIEW py = window.get_view_by_id(id) if py is None: logger.warn('*'*10) logger.warn("Can't find the Python shell view to bind variables") return # Bind the script and engine instances to names on the # interpreter. try: py.bind('mayavi', script) py.bind('engine', script.engine) from enthought.naming.ui.api import explore py.bind('explore', explore) except AttributeError, msg: # This can happen when the shell is not visible. # FIXME: fix this when the shell plugin is improved. logger.warn(msg) logger.warn("Can't find the Python shell to bind variables")
LTS5/connectomeviewer
bb6bc9635d95a7a7bbc1e97abb0fbaa57e70ddd0
Do check for the presence of numpy of the required version for any action
diff --git a/setup.py b/setup.py index 4b906ad..eedb6d9 100755 --- a/setup.py +++ b/setup.py @@ -1,88 +1,88 @@ #!/usr/bin/env python import sys from glob import glob from distutils import log from distutils.cmd import Command import numpy as np # monkey-patch numpy distutils to use Cython instead of Pyrex from build_helpers import package_check, INFO_VARS def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('cviewer') return config ################################################################################ # Dependency check ################################################################################ def _mayavi_version(pkg_name): from enthought.mayavi import version return version.version def _traits_version(pkg_name): from enthought.traits import version return version.__version__ +# Check for core dependencies +package_check('numpy', INFO_VARS['numpy_min_version']) ################################################################################ ################################################################################ # For some commands, use setuptools - if len(set(('develop', 'bdist_egg', 'bdist_rpm', 'bdist', 'bdist_dumb', 'bdist_wininst', 'install_egg_info', 'egg_info', 'easy_install', )).intersection(sys.argv)) > 0: from setup_egg import extra_setuptools_args package_check('networkx', INFO_VARS['networkx_min_version']) - package_check('numpy', INFO_VARS['numpy_min_version']) package_check('enthought.mayavi', INFO_VARS['mayavi_min_version'],version_getter=_mayavi_version) package_check('enthought.traits', INFO_VARS['traits_min_version'],version_getter=_traits_version) # extra_setuptools_args can be defined from the line above, but it can # also be defined here because setup.py has been exec'ed from # setup_egg.py. if not 'extra_setuptools_args' in globals(): extra_setuptools_args = dict() def main(**extra_args): from numpy.distutils.core import setup setup( name = 'Connectome Viewer', version = INFO_VARS['version'], author = "Stephan Gerhard", author_email = "[email protected]", classifiers = [c.strip() for c in """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: Science/Research Operating System :: OS Independent Operating System :: POSIX Operating System :: POSIX :: Linux Operating System :: Unix Programming Language :: Python Topic :: Scientific/Engineering Topic :: Software Development """.splitlines() if len(c.split()) > 0], description = "Multi-Modal MR Connectomics Framework for Analysis and Visualization", license = "Modified BSD License", long_description = INFO_VARS['long_description'], maintainer = 'Stephan Gerhard', maintainer_email = '[email protected]', platforms = ["Linux", "Unix"], url = 'http://www.connectomeviewer.org/', scripts = glob('scripts/*'), configuration = configuration, **extra_args ) if __name__ == "__main__": main()
LTS5/connectomeviewer
852a19771818458320d725de15468aa4777ca683
Remove build in setup.py
diff --git a/setup.py b/setup.py index 6006383..4b906ad 100755 --- a/setup.py +++ b/setup.py @@ -1,88 +1,88 @@ #!/usr/bin/env python import sys from glob import glob from distutils import log from distutils.cmd import Command import numpy as np # monkey-patch numpy distutils to use Cython instead of Pyrex from build_helpers import package_check, INFO_VARS def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('cviewer') return config ################################################################################ # Dependency check ################################################################################ def _mayavi_version(pkg_name): from enthought.mayavi import version return version.version def _traits_version(pkg_name): from enthought.traits import version return version.__version__ ################################################################################ ################################################################################ # For some commands, use setuptools -if len(set(('build', 'develop', 'bdist_egg', 'bdist_rpm', 'bdist', 'bdist_dumb', +if len(set(('develop', 'bdist_egg', 'bdist_rpm', 'bdist', 'bdist_dumb', 'bdist_wininst', 'install_egg_info', 'egg_info', 'easy_install', )).intersection(sys.argv)) > 0: from setup_egg import extra_setuptools_args package_check('networkx', INFO_VARS['networkx_min_version']) package_check('numpy', INFO_VARS['numpy_min_version']) package_check('enthought.mayavi', INFO_VARS['mayavi_min_version'],version_getter=_mayavi_version) package_check('enthought.traits', INFO_VARS['traits_min_version'],version_getter=_traits_version) # extra_setuptools_args can be defined from the line above, but it can # also be defined here because setup.py has been exec'ed from # setup_egg.py. if not 'extra_setuptools_args' in globals(): extra_setuptools_args = dict() def main(**extra_args): from numpy.distutils.core import setup setup( name = 'Connectome Viewer', version = INFO_VARS['version'], author = "Stephan Gerhard", author_email = "[email protected]", classifiers = [c.strip() for c in """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: Science/Research Operating System :: OS Independent Operating System :: POSIX Operating System :: POSIX :: Linux Operating System :: Unix Programming Language :: Python Topic :: Scientific/Engineering Topic :: Software Development """.splitlines() if len(c.split()) > 0], description = "Multi-Modal MR Connectomics Framework for Analysis and Visualization", license = "Modified BSD License", long_description = INFO_VARS['long_description'], maintainer = 'Stephan Gerhard', maintainer_email = '[email protected]', platforms = ["Linux", "Unix"], url = 'http://www.connectomeviewer.org/', scripts = glob('scripts/*'), configuration = configuration, **extra_args ) if __name__ == "__main__": main()
LTS5/connectomeviewer
a8c4dfe82d323ee1e0e4f0b69ef2c1c9c922f7b0
File rights change
diff --git a/scratch/split_fibers.py b/scratch/split_fibers.py old mode 100755 new mode 100644
LTS5/connectomeviewer
ac28df10ebe3dd888424b4024c21b8c54423e73b
Correct version for --version option
diff --git a/cviewer/run.py b/cviewer/run.py index 65ce1ae..d81b11e 100644 --- a/cviewer/run.py +++ b/cviewer/run.py @@ -1,88 +1,89 @@ """ Startup script for the Connectome Viewer application """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library imports import sys import logging +from __version__ import __version__ # First, and before importing any Enthought packages, set the ETS_TOOLKIT # environment variable to qt4, to tell Traits that we will use Qt. #import os #os.environ['ETS_TOOLKIT'] = 'qt4' # ConnectomeViewer imports from cviewer.app import CViewer # Testing for corrext wxversion # Try forcing the use of wx 2.8 before any other import. import sys if not 'wx' in sys.modules: try: from enthought.etsconfig.api import ETSConfig if ETSConfig.toolkit in ('wx', ''): import wxversion wxversion.ensureMinimal('2.8') except ImportError: """ wxversion not installed or not 2.8 or higher""" ########################################################################## # `CViewerApp` class ########################################################################## class CViewerApp(CViewer): def parse_command_line(self, argv): """Parse command line options. """ # This is a overwritten method # Parse and store command line options to process # once app has started in `run`. from optparse import OptionParser usage = "usage: %prog [options]" - parser = OptionParser(usage, version="%prog 0.1.0") + parser = OptionParser(usage, version="%prog " + __version__ ) #parser.add_option("--load-cff", # type="string", dest="cfile", default='', # help="Open the given .cff file directly.") parser.add_option("-v", "--verbose", dest="verbose", default=False, action="store_true", help="Print out debug information.") (options, args) = parser.parse_args(argv) self.cmd_line_opts = (options, args) if options.verbose: self.log_mode = logging.DEBUG else: self.log_mode = logging.ERROR def run(self): """Process the command line options and setup cviewer as per the users needs. """ options, args = self.cmd_line_opts # Process the options. def main(): """ Startup of the Connectome Viewer """ global cviewer # allowing imports like cviewer.plugins. if '' not in sys.path: sys.path.insert(0, '') # to prevent a bug (?) on 64 bit machines # we need to import the gifti libraries before the main loop #import cviewer.io.gifti.gifti as gifti cviewer = CViewerApp() cviewer.main(sys.argv[1:])
LTS5/connectomeviewer
d7b01b41b5171dbec2489dd286c8c83450e2cd28
Conditioned package_check
diff --git a/setup.py b/setup.py index 0533a9a..6006383 100755 --- a/setup.py +++ b/setup.py @@ -1,88 +1,88 @@ #!/usr/bin/env python import sys from glob import glob from distutils import log from distutils.cmd import Command import numpy as np # monkey-patch numpy distutils to use Cython instead of Pyrex from build_helpers import package_check, INFO_VARS def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('cviewer') return config ################################################################################ # Dependency check ################################################################################ def _mayavi_version(pkg_name): from enthought.mayavi import version return version.version def _traits_version(pkg_name): from enthought.traits import version return version.__version__ -package_check('networkx', INFO_VARS['networkx_min_version']) -package_check('numpy', INFO_VARS['numpy_min_version']) -package_check('enthought.mayavi', INFO_VARS['mayavi_min_version'],version_getter=_mayavi_version) -package_check('enthought.traits', INFO_VARS['traits_min_version'],version_getter=_traits_version) ################################################################################ ################################################################################ # For some commands, use setuptools -if len(set(('develop', 'bdist_egg', 'bdist_rpm', 'bdist', 'bdist_dumb', +if len(set(('build', 'develop', 'bdist_egg', 'bdist_rpm', 'bdist', 'bdist_dumb', 'bdist_wininst', 'install_egg_info', 'egg_info', 'easy_install', )).intersection(sys.argv)) > 0: from setup_egg import extra_setuptools_args + package_check('networkx', INFO_VARS['networkx_min_version']) + package_check('numpy', INFO_VARS['numpy_min_version']) + package_check('enthought.mayavi', INFO_VARS['mayavi_min_version'],version_getter=_mayavi_version) + package_check('enthought.traits', INFO_VARS['traits_min_version'],version_getter=_traits_version) # extra_setuptools_args can be defined from the line above, but it can # also be defined here because setup.py has been exec'ed from # setup_egg.py. if not 'extra_setuptools_args' in globals(): extra_setuptools_args = dict() def main(**extra_args): from numpy.distutils.core import setup setup( name = 'Connectome Viewer', version = INFO_VARS['version'], author = "Stephan Gerhard", author_email = "[email protected]", classifiers = [c.strip() for c in """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: Science/Research Operating System :: OS Independent Operating System :: POSIX Operating System :: POSIX :: Linux Operating System :: Unix Programming Language :: Python Topic :: Scientific/Engineering Topic :: Software Development """.splitlines() if len(c.split()) > 0], description = "Multi-Modal MR Connectomics Framework for Analysis and Visualization", license = "Modified BSD License", long_description = INFO_VARS['long_description'], maintainer = 'Stephan Gerhard', maintainer_email = '[email protected]', platforms = ["Linux", "Unix"], url = 'http://www.connectomeviewer.org/', scripts = glob('scripts/*'), configuration = configuration, **extra_args ) if __name__ == "__main__": main()
LTS5/connectomeviewer
7c2a5c3180570c82acab86097e79bb0900e68b68
Remove welcome from setup.py
diff --git a/cviewer/plugins/ui/setup.py b/cviewer/plugins/ui/setup.py index 50d4852..ff86b2b 100644 --- a/cviewer/plugins/ui/setup.py +++ b/cviewer/plugins/ui/setup.py @@ -1,13 +1,11 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('ui', parent_package, top_path) - - config.add_subpackage('welcome') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) \ No newline at end of file
LTS5/connectomeviewer
8f6b5287a7a4ac758d4cab8fc17457b7f8696573
Thanks goes to Yarik
diff --git a/README.rst b/README.rst index d8b4de7..6b184d8 100644 --- a/README.rst +++ b/README.rst @@ -1,51 +1,51 @@ ================= Connectome Viewer ================= The Connectome Viewer - Interactive Analysis and Visualization for MR Connectomics The Connectome Viewer is a extensible, scriptable, pythonic software tool for visualization and analysis in neuroimaging research. Employing the Connectome File Format, diverse data types such as networks, surfaces, volumes, tracks and metadata are handled and integrated. The Connectome Viewer is part of the MR Connectome Toolkit. Copyright (C) 2009-2011, Ecole Polytechnique Fédérale de Lausanne (EPFL) and Hospital Center and University of Lausanne (UNIL-CHUV), Switzerland ======= Credits ======= ------ Author ------ Stephan Gerhard ------ Thanks ------ +* Yaroslav Halchenko * Patric Hagmann * Leila Cammoun * Jean-Philippe Thiran * Xavier Gigandet * Reto Meuli * Benjamin Thyreau * Alessandro Daducci * Alia Lemkaddem * Marie-Christine Ottet * Djalel Meskaldji * Francesca Pizzorni * Christophe Chenes * Alessandra Griffa --------------------- Plugins/External code --------------------- See plugin section in documentation for copyright and license of contributions. * Enthought Evisage. Application Framework. Enthought. * Mayavi2. Partly modified files. Prabhu Ramachandran and Gael Varoquaux * Andrew Zalesky (Network-Based Statistics) -
LTS5/connectomeviewer
fbf3017554d06a4d91f349ffefe2b1a0c737c032
Add gitattributes to not export scratch folder in archive
diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dcfa68a --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +/scratch export-ignore
LTS5/connectomeviewer
7855e164f1383c2df2ae0dc2e1bff98ae0352bb3
Release 2.0.0
diff --git a/cviewer/app.py b/cviewer/app.py index d71df52..1c0659a 100644 --- a/cviewer/app.py +++ b/cviewer/app.py @@ -1,340 +1,340 @@ """ The Connectome Viewer Envisage application with Plugins """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Modified version. Adapted from the MayaVi2 application # Standard library imports import sys import os.path import os # Enthought library imports from enthought.traits.api import (HasTraits, Instance, Int, on_trait_change) from enthought.etsconfig.api import ETSConfig from enthought.logger.api import LogFileHandler, FORMATTER # ConnectomeViewer imports from cviewer.cviewer_workbench_application import CViewerWorkbenchApplication from cviewer.plugins.ui.preference_manager import preference_manager from cviewer.info import version as ver # Logger imports import logging, logging.handlers logger = logging.getLogger('root') logger_envisage = logging.getLogger('enthought.envisage.plugin') logger_ipython = logging.getLogger('enthought.plugins.ipython_shell.view.ipython_shell_view') logger_pyface = logging.getLogger('enthought.pyface.ui.wx.workbench.editor_set_structure_handler') logger_pyfaceview = logging.getLogger('enthought.pyface.workbench.i_view') def setup_logger(logger, fname, stream=True, mode=logging.ERROR): """Setup a log file and the logger. Parameters ---------- fname : string File name the logger should use. stream : bool Add a stream handler. mode : logging type The logging mode of the stream handler. """ if not os.path.isabs(fname): path = os.path.join(ETSConfig.application_data, fname) else: path = fname create_file_handler = True # check if path exists dirname = os.path.dirname(path) if not(os.path.exists(dirname)): try: os.makedirs(dirname) except OSError: #logger.error('Can not create path to store the log file.') create_file_handler = False # check if path is writable if not os.access(dirname, os.W_OK): print "===========================================" print "The application data path is not writable: ", dirname print "Please remove it with:" print "sudo rm -rf " + dirname print "and re-run the Connectome Viewer with:" print "connectomeviewer -v" print "===========================================" raise Exception("PermissionError") # check if files exists, if not open it if not(os.path.exists(path)): # XXX add try catch file = open(path, 'w') file.close() # setting the logging level logger.setLevel(mode) # create formatter formatter = logging.Formatter("%(levelname)s - %(name)s - %(message)s") # old: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" if stream: # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(mode) # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) if create_file_handler: filehandler = logging.handlers.RotatingFileHandler(path, maxBytes=1000000, backupCount=4) filehandler.setLevel(mode) filehandler.setFormatter(formatter) logger.addHandler(filehandler) logger_envisage.addHandler(filehandler) # does this fix the # no handlers could be found for logger "enthought.envisage.plugin" logger_ipython.addHandler(filehandler) logger_pyface.addHandler(filehandler) logger_pyfaceview.addHandler(filehandler) import datetime import sys import platform dt = datetime.datetime.now() outdate = dt.strftime("%A, %d. %B %Y %I:%M%p") logger.info("*"*5) if create_file_handler: logger.info("logfile: %s" % os.path.abspath(path)) logger.info("cviewer version: %s " % ver) # logger.info("cviewer executable: %s " % str(__main__)) logger.info("python executable: %s" % sys.executable) logger.info("python version: %s" % sys.version.replace('\n', '')) logger.info("uname: %s" % ' '.join(platform.uname())) logger.info("distribution: %s" % ' '.join(platform.linux_distribution())) logger.info("execution date and time: %s" % outdate) logger.info("*"*5) def get_non_gui_plugin_classes(): """Get list of basic mayavi plugin classes that do not add any views or actions.""" from enthought.envisage.core_plugin import CorePlugin from enthought.envisage.ui.workbench.workbench_plugin import WorkbenchPlugin from enthought.tvtk.plugins.scene.scene_plugin import ScenePlugin from enthought.mayavi.plugins.mayavi_plugin import MayaviPlugin plugins = [CorePlugin, WorkbenchPlugin, MayaviPlugin, ScenePlugin, ] return plugins def get_non_gui_plugins(): """Get list of basic mayavi plugins that do not add any views or actions.""" return [cls() for cls in get_non_gui_plugin_classes()] def get_plugin_classes(): """Get list of default plugin classes to use for Connectome Viewer.""" # Force the selection of a toolkit: from enthought.traits.ui.api import toolkit toolkit() from enthought.etsconfig.api import ETSConfig try_use_ipython = preference_manager.cviewerui.useipython use_ipython = False if ETSConfig.toolkit == 'wx' and try_use_ipython: try: # If the right versions of IPython, EnvisagePlugins and # Pyface are not installed, this import will fail. from enthought.plugins.ipython_shell.view.ipython_shell_view \ import IPythonShellView use_ipython = True except: pass if use_ipython: from enthought.plugins.ipython_shell.ipython_shell_plugin import \ IPythonShellPlugin PythonShellPlugin = IPythonShellPlugin else: from enthought.plugins.python_shell.python_shell_plugin import PythonShellPlugin from enthought.tvtk.plugins.scene.ui.scene_ui_plugin import SceneUIPlugin from cviewer.plugins.text_editor.text_editor_plugin import TextEditorPlugin plugins = get_non_gui_plugin_classes() plugins.extend([ SceneUIPlugin, TextEditorPlugin, PythonShellPlugin, ]) return plugins def get_plugins(): """Get list of default plugins to use for Mayavi.""" return [cls() for cls in get_plugin_classes()] def get_cviewer_plugins(): """ Get list of Connectome Viewer plugins """ plugins = [] logger.info('Plugins') logger.info('*******') # from cviewer.plugins.cff.cff_plugin import ConnectomeFilePlugin # # add ConnectomeFile plugin # plugins.insert(0, ConnectomeFilePlugin()) # logger.info('Added ConnectomeFilePlugin') from cviewer.plugins.cff2.cff_plugin import ConnectomeFile2Plugin # add ConnectomeFile plugin plugins.insert(0, ConnectomeFile2Plugin()) logger.info('Added ConnectomeFile2Plugin') #from cviewer.plugins.analysis.analysis_ui_plugin import AnalysisUIPlugin # add ConnectomeAnalysis UI plugin #plugins.insert(0, AnalysisUIPlugin()) #logger.info('Added AnalysisUIPlugin') from cviewer.plugins.ui.cviewer_ui_plugin import CViewerUIPlugin # add ConnectomeViewerUserInterface plugin plugins.insert(0, CViewerUIPlugin()) logger.info('Added CViewerUIPlugin') # add Bindings plugin from cviewer.plugins.bindings.bindings_plugin import BindingsPlugin plugins.append(BindingsPlugin()) logger.info('Added BindingsPlugin') # add sLORETA Converter plugin from cviewer.plugins.codeoracle.oracle_plugin import OraclePlugin plugins.append(OraclePlugin()) logger.info('Added Oracle Plugin') # add NBS plugin from cviewer.plugins.nbs.nbs_plugin import NBSPlugin plugins.append(NBSPlugin()) logger.info('Added Network Based Statistics (NBS) Plugin') # add cmp #try: # cmp_works = True # from cviewer.plugins.cmp.cmp_plugin import CMPPlugin # except ImportError: # cmp_works = False # if cmp_works: # plugins.append(CMPPlugin()) # logger.info('Added Connectome Mapper Plugin') return plugins ########################################################################### # `CViewer` class. ########################################################################### class CViewer(HasTraits): """The Connectome Viewer application class. """ # The main envisage application. application = Instance('enthought.envisage.ui.workbench.api.WorkbenchApplication') # The MayaVi Script instance. script = Instance('enthought.mayavi.plugins.script.Script') # The logging mode. log_mode = Int(logging.ERROR, desc='the logging mode to use') def main(self, argv=None): """The main application is created and launched here. Parameters ---------- argv : list of strings The list of command line arguments. The default is `None` where no command line arguments are parsed. To support command line arguments you can pass `sys.argv[1:]`. log_mode : The logging mode to use. """ # parse any cmd line args. if argv is None: argv = [] self.parse_command_line(argv) # setup logging self.setup_logger() # add all default plugins plugins = get_plugins() # add ConnectomeViewer plugins plugins = get_cviewer_plugins() + plugins # create the application prefs = preference_manager.preferences # create the application object self.application = CViewerWorkbenchApplication(plugins=plugins, preferences=prefs) # start the application. self.application.run() - logger.info('We hope you enjoyed using the ConnectomeViewer!') + logger.info('We hope you enjoyed using the Connectome Viewer!') def setup_logger(self): """ Setting up the root logger """ from enthought.etsconfig.api import ETSConfig path = os.path.join(ETSConfig.application_data, 'ch.connectome.viewer', 'cviewer.log') path = os.path.abspath(path) setup_logger(logger, path, mode=self.log_mode) def parse_command_line(self, argv): """Parse command line options. Parameters ---------- - argv : `list` of `strings` The list of command line arguments. """ from optparse import OptionParser usage = "usage: %prog [options]" parser = OptionParser(usage) (options, args) = parser.parse_args(argv) def run(self): """This function is called after the GUI has started. """ pass def main(argv=None): - """ Helper to start up the ConnectomeViewer application. """ + """ Helper to start up the Connectome Viewer application. """ m = CViewer() m.main(argv) return m diff --git a/cviewer/info.py b/cviewer/info.py index 9329f7c..336db10 100644 --- a/cviewer/info.py +++ b/cviewer/info.py @@ -1,83 +1,83 @@ ''' Release data for Connectome Viewer This script should do no imports. It only defines variables. ''' -version = '2.0.0-RC3' +version = '2.0.0' is_release = False long_description = \ """ Connectome Viewer - A Framework for the Visualization and Analysis of Multi-Modal Multi-Scale Connectome Data in Python The aim of Connectome Viewer is to produce a platform-independent Python framework for the analysis and visualization of Connectome data using an open development model. The Connectome Viewer is a extensible, scriptable, pythonic software tool for visualization and analysis in neuroimaging research on many spatial scales. Employing the Connectome File Format, diverse data such as networks, surfaces, volumes, tracks and metadata are handled and integrated. Specifically, we aim to: 1. Provide an open source, mixed language scientific programming framework for rapid development and quantitative analysis 2. Provide a visualization platform to readily visualize multi-modal data for interactive data exploration 3. Allow for enhanced brain connectivity analysis and plotting 4. Provide the Connectome File Format to store a wide range of data types: metadata, networks, surfaces, volumes, fiber tracks, time series 5. Create and maintain a wide base of developers to contribute plugins to this framework. 6. To integrate this framework with software packages in neuroimaging and provide an easily installable bundle. """ # these have to be done per install_requires envisagecore_min_version = '3.1.2' traitsbackendwx_min_version = '3.2.1' envisageplugins_min_version = '3.1.2' enthoughtbase_min_version = '3.0.4' traitsgui_min_version = '3.1.1' chaco_min_version = '3.2.1' lxml_min_version = '2.2.6' pymysql_min_version = '0.2' # these can be done safely traits_min_version = '3.2.0' networkx_min_version = '1.4' mayavi_min_version = '3.3.2' h5py_min_version = '1.2.0' scipy_min_version = '0.5' # for ubuntu 10.04 ### envisagecore_min_version = '3.1.1' # python-envisagecore envisageplugins_min_version = '3.1.1' # python-envisageplugins traitsbackendwx_min_version = '3.2.0' # python-traitsbackendwx traitsbackendqt_min_version = '3.2.0' # python-traitsbackendqt traitsgui_min_version = '3.1.0' # python-traitsgui traits_min_version = '3.2.0' # python-traits python_enthought_traits_ui = '3.1.0' # python-enthought-traits-ui enthoughtbase_min_version = '3.0.3' # python-enthoughtbase chaco_min_version = '3.2.0' # python-chaco lxml_min_version = '2.2.4' # python-lxml scipy_min_version = '0.5' # python-scipy (0.7.0) numpy_min_version = '1.3.0' # python-numpy h5py_min_version = '1.2.1' # python-h5py mayavi_min_version = '3.3.0' # mayavi2 # python-apptools (3.3.0), python-enthought-traits (3.1.0), python-numpy (1.3.0) # outdated or not available pymysql_min_version = '0.2' # not available networkx_min_version = '1.4' # python-network (0.99) diff --git a/doc/source/conf.py b/doc/source/conf.py index 450ea00..340d6bb 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -1,214 +1,214 @@ # -*- coding: utf-8 -*- # # sampledoc documentation build configuration file, created by # sphinx-quickstart on Tue Jun 3 12:40:24 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import sys, os # If your extensions are in another directory, add it here. If the directory # is relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. sys.path.append(os.path.abspath('sphinxext')) # Import support for ipython console session syntax highlighting (lives # in the sphinxext directory defined above) import ipython_console_highlighting # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'ipython_console_highlighting', 'inheritance_diagram', 'numpydoc', 'autosummary'] # Matplotlib sphinx extensions # ---------------------------- # Currently we depend on some matplotlib extentions that are only in # the trunk, so we've added copies of these files to fall back on, # since most people install releases. Once theses extensions have # been released for a while we should remove this hack. I'm assuming # any modifications to these extensions will be done upstream in # matplotlib! The matplotlib trunk will have more bug fixes and # feature updates so we'll try to use that one first. try: import matplotlib.sphinxext extensions.append('matplotlib.sphinxext.mathmpl') extensions.append('matplotlib.sphinxext.only_directives') extensions.append('matplotlib.sphinxext.plot_directive') except ImportError: extensions.append('mathmpl') extensions.append('only_directives') extensions.append('plot_directive') # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General substitutions. project = 'Connectome Viewer' copyright = '2010, EPFL & UNIL-CHUV. Author: Stephan Gerhard' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. -version = '2.0.0 RC4' +version = '2.0.0' # The full version, including alpha/beta/rc tags. -release = '2.0.0 RC4' +release = '2.0.0' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. unused_docs = [] # List of directories, relative to source directories, that shouldn't # be searched for source files. exclude_trees = ['www'] # what to put into API doc (just class doc, just init, or both) autoclass_content = 'class' # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. #html_style = 'nipy.css' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". html_title = 'ConnectomeViewer Documentation' # The name of an image file (within the static path) to place at the top of # the sidebar. #html_logo = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Content template for the index page. html_index = 'www/index.html' # Custom sidebar templates, maps document names to template names. html_sidebars = {'index': 'indexsidebar.html'} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If true, the reST sources are included in the HTML build as _sources/<name>. html_copy_source = False # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' html_theme = 'sphinxdoc' # Output file base name for HTML help builder. htmlhelp_basename = project # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class # [howto/manual]). latex_documents = [ ('contents', 'cviewer.tex', 'ConnectomeViewer Documentation', ur'Multi-Modal, Multi-Level pythonic Network Visualization and Analysis','manual'), ## ('devel/index', 'nipy_devel.tex', ## 'Neuroimaging in Python Developer Documentation', ## ur'The Neuroimaging in Python documentation team.','manual'), ## ('api/index', 'nipy_ref.tex', ## 'Neuroimaging in Python Reference Guide', ## ur'The Neuroimaging in Python documentation team.','manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. latex_use_parts = True # Additional stuff for the LaTeX preamble. latex_preamble = """ \usepackage{amsmath} \usepackage{amssymb} % Uncomment these two if needed %\usepackage{amsfonts} %\usepackage{txfonts} """ # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. latex_use_modindex = True diff --git a/setup.py b/setup.py index 8085e57..0533a9a 100755 --- a/setup.py +++ b/setup.py @@ -1,89 +1,88 @@ #!/usr/bin/env python import sys from glob import glob from distutils import log from distutils.cmd import Command import numpy as np # monkey-patch numpy distutils to use Cython instead of Pyrex from build_helpers import package_check, INFO_VARS def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('cviewer') return config ################################################################################ # Dependency check ################################################################################ def _mayavi_version(pkg_name): from enthought.mayavi import version return version.version def _traits_version(pkg_name): from enthought.traits import version return version.__version__ -package_check('scipy', INFO_VARS['scipy_min_version']) package_check('networkx', INFO_VARS['networkx_min_version']) package_check('numpy', INFO_VARS['numpy_min_version']) package_check('enthought.mayavi', INFO_VARS['mayavi_min_version'],version_getter=_mayavi_version) package_check('enthought.traits', INFO_VARS['traits_min_version'],version_getter=_traits_version) ################################################################################ ################################################################################ # For some commands, use setuptools if len(set(('develop', 'bdist_egg', 'bdist_rpm', 'bdist', 'bdist_dumb', 'bdist_wininst', 'install_egg_info', 'egg_info', 'easy_install', )).intersection(sys.argv)) > 0: from setup_egg import extra_setuptools_args # extra_setuptools_args can be defined from the line above, but it can # also be defined here because setup.py has been exec'ed from # setup_egg.py. if not 'extra_setuptools_args' in globals(): extra_setuptools_args = dict() def main(**extra_args): from numpy.distutils.core import setup setup( name = 'Connectome Viewer', version = INFO_VARS['version'], author = "Stephan Gerhard", author_email = "[email protected]", classifiers = [c.strip() for c in """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: Science/Research Operating System :: OS Independent Operating System :: POSIX Operating System :: POSIX :: Linux Operating System :: Unix Programming Language :: Python Topic :: Scientific/Engineering Topic :: Software Development """.splitlines() if len(c.split()) > 0], description = "Multi-Modal MR Connectomics Framework for Analysis and Visualization", license = "Modified BSD License", long_description = INFO_VARS['long_description'], maintainer = 'Stephan Gerhard', maintainer_email = '[email protected]', platforms = ["Linux", "Unix"], url = 'http://www.connectomeviewer.org/', scripts = glob('scripts/*'), configuration = configuration, **extra_args ) if __name__ == "__main__": main()
LTS5/connectomeviewer
6e64542ae31d90e2708fc2582de08fb6a99f0de9
Connectome Viewer Toolkit publication accepted
diff --git a/doc/source/publications.rst b/doc/source/publications.rst index 3d5f498..884b1fa 100644 --- a/doc/source/publications.rst +++ b/doc/source/publications.rst @@ -1,15 +1,15 @@ .. _publications: ============ Publications ============ How to cite the Connectome Viewer and Connectome File Format? ````````````````````````````````````````````````````````````` -* Gerhard S et al. "The Connectome Viewer Toolkit: an open source framework to manage, analyze and visualize connectomes", Frontiers in Neuroinformatics (Submitted) +* Gerhard S et al. "The Connectome Viewer Toolkit: an open source framework to manage, analyze and visualize connectomes", Frontiers in Neuroinformatics, May 2011 (Accepted) Related publications ```````````````````` * Hagmann P, Cammoun L, Gigandet X, Meuli R, Honey CJ, et al. 2008 `Mapping the Structural Core of Human Cerebral Cortex. <http://www.plosbiology.org/article/info:doi/10.1371/journal.pbio.0060159>`_ PLoS Biol 6(7): e159. * Sporns O, Tononi G, Kötter R (2005). `The Human Connectome: A Structural Description of the Human Brain. <http://dx.doi.org/10.1371/journal.pcbi.0010042>`_ PLoS Comput Biol 1(4): e42.
LTS5/connectomeviewer
03e505255af9da5fc881ec22006961f32ca9d462
Write GEXF in Code Oracle
diff --git a/cviewer/plugins/codeoracle/actions.py b/cviewer/plugins/codeoracle/actions.py index 21bde65..71120eb 100644 --- a/cviewer/plugins/codeoracle/actions.py +++ b/cviewer/plugins/codeoracle/actions.py @@ -1,341 +1,359 @@ import logging from enthought.io.api import File from enthought.pyface.api import FileDialog, OK from enthought.pyface.action.api import Action from enthought.traits.api import Any from cviewer.plugins.text_editor.editor.text_editor import TextEditor from cviewer.plugins.ui.preference_manager import preference_manager # Logging imports import logging logger = logging.getLogger('root.'+__name__) class NetworkVizTubes(Action): tooltip = "Show 3D Network with Tubes" description = "Show 3D Network with Tubes and colorcoded Nodes" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from scripts import threedviz2 import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(threedviz2) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class NetworkReport(Action): tooltip = "Network Report" description = "Network Report" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from scripts import reportlab import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(reportlab) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) +class WriteGEXF(Action): + tooltip = "Write Gephi GEXF file" + description = "Write Gephi GEXF file" + + # The WorkbenchWindow the action is attached to. + window = Any() + + def perform(self, event=None): + + from scripts import writegexf + + import tempfile + myf = tempfile.mktemp(suffix='.py', prefix='my') + f=open(myf, 'w') + f.write(writegexf) + f.close() + + self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class CorticoCortico(Action): tooltip = "Extract cortico-cortico fibers" description = "Extract cortico-cortico fibers" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from scripts import corticocortico import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(corticocortico) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class NipypeBet(Action): tooltip = "Brain extraction using BET" description = "Brain extraction using BET" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from scripts import nipypebet import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(nipypebet) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class ShowTracks(Action): tooltip = "Show tracks between two regions" description = "Show tracks between two regions" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from scripts import ctrackedge import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(ctrackedge) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class XNATPushPull(Action): tooltip = "Push and pull files from and to XNAT Server" description = "Push and pull files from and to XNAT Server" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from scripts import pushpull import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(pushpull) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class ComputeNBS(Action): tooltip = "Compute NBS" description = "Compute NBS" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): # from cnetwork_nbs_action import NBSNetworkParameter, NBSMoreParameter from scripts import nbsscript # cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') # # no = NBSNetworkParameter(cfile) # no.edit_traits(kind='livemodal') # # if (len(no.selected1) == 0 or len(no.selected2) == 0): # return # # mo = NBSMoreParameter(cfile, no.selected1[0], no.selected2[0]) # mo.edit_traits(kind='livemodal') # # import datetime as dt # a=dt.datetime.now() # ostr = '%s%s%s' % (a.hour, a.minute, a.second) # if not (len(no.selected1) == 0 or len(no.selected2) == 0): # # if cancel, not create surface # # create a temporary file # import tempfile # myf = tempfile.mktemp(suffix='.py', prefix='my') # f=open(myf, 'w') # f.write(nbsscript % (str(no.selected1), # mo.first_edge_value, # str(no.selected2), # mo.second_edge_value, # mo.THRES, # mo.K, # mo.TAIL, # ostr)) # f.close() # # self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(nbsscript) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class ShowNetworks(Action): tooltip = "Create a 3D Network" description = "Create a 3D Network" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from cnetwork_action import NetworkParameter from scripts import netscript cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') no = NetworkParameter(cfile) no.edit_traits(kind='livemodal') if not no.netw[no.graph]['name'] == "None": # if cancel, not create surface # create a temporary file import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(netscript % (no.netw[no.graph]['name'], no.node_position, no.edge_value, no.node_label)) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class ConnectionMatrix(Action): tooltip = "Show connection matrix" description = "Show connection matrix" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from cnetwork_action import MatrixNetworkParameter from scripts import conmatrix cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') no = MatrixNetworkParameter(cfile) no.edit_traits(kind='livemodal') if not no.netw[no.graph]['name'] == "None": # if cancel, not create surface # create a temporary file import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(conmatrix % (no.netw[no.graph]['name'], no.node_label)) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class SimpleConnectionMatrix(Action): tooltip = "Show simple connection matrix" description = "Show simple connection matrix" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from cnetwork_action import MatrixEdgeNetworkParameter from scripts import conmatrixpyplot cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') no = MatrixEdgeNetworkParameter(cfile) no.edit_traits(kind='livemodal') if not no.netw[no.graph]['name'] == "None": # if cancel, not create surface # create a temporary file import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(conmatrixpyplot % (no.netw[no.graph]['name'], no.edge_label)) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class ShowSurfaces(Action): """ Open a new file in the text editor """ tooltip = "Create a surface" description = "Create a surface" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from csurface_action import SurfaceParameter from scripts import surfscript cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') so = SurfaceParameter(cfile) so.edit_traits(kind='livemodal') if not so.pointset_da[so.pointset]['name'] == "None": # if cancel, not create surface # create a temporary file import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') if so.labels_da[so.labels].has_key('da_idx'): labels = so.labels_da[so.labels]['da_idx'] else: labels = 0 f.write(surfscript % (so.pointset_da[so.pointset]['name'], so.pointset_da[so.pointset]['da_idx'], so.faces_da[so.faces]['name'], so.faces_da[so.faces]['da_idx'], so.labels_da[so.labels]['name'], labels)) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) class ShowVolumes(Action): """ Open a new file in the text editor """ tooltip = "Create a volume" description = "Create a volume" # The WorkbenchWindow the action is attached to. window = Any() def perform(self, event=None): from cvolume_action import VolumeParameter from scripts import volslice cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile') so = VolumeParameter(cfile) so.edit_traits(kind='livemodal') if True: #not so.pointset_da[so.pointset]['name'] == "None": # if cancel, not create surface # create a temporary file import tempfile myf = tempfile.mktemp(suffix='.py', prefix='my') f=open(myf, 'w') f.write(volslice % so.volumes[so.myvolume]['name']) f.close() self.window.workbench.edit(File(myf), kind=TextEditor,use_existing=False) diff --git a/cviewer/plugins/codeoracle/oracle_action_set.py b/cviewer/plugins/codeoracle/oracle_action_set.py index adf5635..77e4c32 100644 --- a/cviewer/plugins/codeoracle/oracle_action_set.py +++ b/cviewer/plugins/codeoracle/oracle_action_set.py @@ -1,119 +1,127 @@ """ Action set for the Oracl plugin """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Enthought library imports from enthought.envisage.ui.action.api import Action, Group, Menu, ToolBar from enthought.envisage.ui.workbench.api import WorkbenchActionSet networkrepo = Action( id = "OracleCNetworkReport", class_name = "cviewer.plugins.codeoracle.actions.NetworkReport", name = "Network Report", path = "MenuBar/Code Oracle/Connectome/CNetwork/Analysis" ) xnat_pushpull = Action( id = "OracleXNATPushPull", class_name = "cviewer.plugins.codeoracle.actions.XNATPushPull", name = "XNAT Push and Pull", path = "MenuBar/Code Oracle/Other/XNAT" ) show_surface = Action( id = "OracleCSurface", class_name = "cviewer.plugins.codeoracle.actions.ShowSurfaces", name = "Show Surface", path = "MenuBar/Code Oracle/Connectome/CSurface/Visualization" ) show_volumecre = Action( id = "OracleCVolumeCre", class_name = "cviewer.plugins.codeoracle.actions.ShowVolumes", name = "Volume Creation", path = "MenuBar/Code Oracle/Connectome/CVolume/Visualization" ) show_network = Action( id = "OracleCNetwork3D", class_name = "cviewer.plugins.codeoracle.actions.ShowNetworks", name = "3D Network", path = "MenuBar/Code Oracle/Connectome/CNetwork/Visualization" ) show_network2 = Action( id = "OracleCNetwork3D2", class_name = "cviewer.plugins.codeoracle.actions.NetworkVizTubes", name = "3D Network (with tubes and node color)", path = "MenuBar/Code Oracle/Connectome/CNetwork/Visualization" ) connection_matrix = Action( id = "OracleCNetworkMat", class_name = "cviewer.plugins.codeoracle.actions.ConnectionMatrix", name = "Connection Matrix", path = "MenuBar/Code Oracle/Connectome/CNetwork/Visualization" ) simple_connection_matrix = Action( id = "OracleCNetworkSimpleMat", class_name = "cviewer.plugins.codeoracle.actions.SimpleConnectionMatrix", name = "Simple Connection Matrix", path = "MenuBar/Code Oracle/Connectome/CNetwork/Visualization" ) +writegexf = Action( + id = "OracleCNetworkWriteGEXF", + class_name = "cviewer.plugins.codeoracle.actions.WriteGEXF", + name = "Write Gephi GEXF", + path = "MenuBar/Code Oracle/Connectome/CNetwork/Analysis" +) + compute_nbs = Action( id = "OracleNBS", class_name = "cviewer.plugins.codeoracle.actions.ComputeNBS", name = "Network-based statistic (NBS)", path = "MenuBar/Code Oracle/Statistics" ) show_tracks = Action( id = "OracleShowTracks", class_name = "cviewer.plugins.codeoracle.actions.ShowTracks", name = "Tracks between regions", path = "MenuBar/Code Oracle/Connectome/CTrack/Visualization" ) cortico_cortico = Action( id = "OracleCorticoCorticoTracks", class_name = "cviewer.plugins.codeoracle.actions.CorticoCortico", name = "Extract cortico-cortico fiber tracks", path = "MenuBar/Code Oracle/Connectome/CTrack/Analysis" ) nipype_bet = Action( id = "OracleNipypeBet", class_name = "cviewer.plugins.codeoracle.actions.NipypeBet", name = "Brain extraction using BET", path = "MenuBar/Code Oracle/Other/Nipype" ) class OracleActionSet(WorkbenchActionSet): """ The actionset for the Oracle plugin """ id = "cviewer.plugins.codeoracle.action_set" actions = [ show_surface, show_network, show_network2, compute_nbs, show_volumecre, connection_matrix, simple_connection_matrix, show_tracks, cortico_cortico, xnat_pushpull, nipype_bet, - networkrepo + networkrepo, + writegexf ] diff --git a/cviewer/plugins/codeoracle/scripts.py b/cviewer/plugins/codeoracle/scripts.py index 87bdf0e..bd51233 100644 --- a/cviewer/plugins/codeoracle/scripts.py +++ b/cviewer/plugins/codeoracle/scripts.py @@ -1,512 +1,538 @@ +writegexf = ''' +""" Convert a connectome network to the GEXF format +readable by Gephi for further analysis and visualization """ + +import networkx as nx +import numpy as np + +cnet = cfile.obj.get_by_name('connectome_freesurferaparc') +cnet.load() +outpath = 'out.gexf' + +def fix_float_for_gexf(network): + for u,v,d in network.edges_iter(data=True): + for k,v in d.items(): + if isinstance(d[k], np.float64): + d[k] = float( d[k] ) + for u,d in network.nodes_iter(data=True): + for k,v in d.items(): + if isinstance(d[k], np.float64): + d[k] = float( d[k] ) + return network + +G = fix_float_for_gexf(cnet.data) +nx.write_gexf(cnet.data, outpath) +''' + corticocortico =''' """ Extract cortio-cortico fibers from tractography outputs of CMTK, apply clustering and visualize them. The basic idea is to remove sets of fibers such as the corpus callosum first, and then inspect various histograms of start-endpoint-distances, mean curvature etc. and downsample to incrementally filter out fibers until only cortico-cortico fibers remain. The remaining fibers are then clustered to yield bundles of cortico-cortical fibers. This script shows the outcome of the power of interactively working with scientific datasets for exploration and parameter estimation. Stephan Gerhard, May 2011 """ import numpy as np import nibabel as ni from os.path import join as j import os.path as op import time from nibabel import trackvis import cfflib as cf from dipy.tracking import metrics as tm from dipy.tracking import distances as td from dipy.io import pickles as pkl from dipy.tracking.metrics import length, mean_curvature import dipy.viz.fvtk as fvtk from fos import World, Window from fos.actor.curve import InteractiveCurves # Load the relevant data files # load connectome file object con = cfile.obj # alternatively when loading from Ipython directly with cfflib # con = cf.load('meta.cml') def load_data(con): fibobj = con.get_by_name('Final Tractography (freesurferaparc)') fibobj.load() fibers = fibobj.get_fibers_as_numpy() fibershdr = fibers.data[1] epmmobj = con.get_by_name('Fiber mean curvature') eleobj = con.get_by_name('Final fiber lengths (freesurferaparc)') eleobj.load() lenghts = eleobj.data emobj = con.get_by_name('Fiber mean curvature') emobj.load() meancurv = emobj.data print "Compute endpoints [mm] array" endpoints = np.zeros( (len(fibers), 2, 3), dtype = np.float32 ) for i in xrange(len(fibers)): endpoints[i,0,:] = fibers[i][0,:] endpoints[i,1,:] = fibers[i][-1,:] return fibers, fibershdr, lenghts, meancurv, endpoints # load stuff, can uncomment for rerunning the script in ipython with # run -i script.py fibers, fibershdr, lenghts, meancurv, endpoints = load_data(con) # Helper functions def compute_start_end_distances(endpoints): n = endpoints.shape[0] di = np.zeros( (n, 1) ) for i in xrange(n): d = np.abs(endpoints[i,0,:]-endpoints[i,1,:]) di[i,0] = np.sqrt(np.dot(d,d)) return di def sidx(arr, value): """ Returns the indices that are smaller or equal to the given array """ return np.where( arr <= value)[0] def randcolarr(arr): """ Returns a random color for each row in arr """ return np.random.rand(1,3).repeat(len(arr),axis=0) def filterfibers(fibarr, filtarr, lower, upper): return fibarr[ np.where((filtarr>lower) & (filtarr<upper))[0] ] def filterfibersidx(filtarr, lower, upper): return np.where((filtarr>lower) & (filtarr<upper))[0] def filterfibersidxcomplement(filtarr, lower, upper): return np.where((filtarr<=lower) | (filtarr>=upper))[0] def filterhemisphere(endpointsmean, xcut, hemi = 0): if hemi == 1: return np.where( (endpointsmean < xcut) )[0] elif hemi == 2: return np.where( (endpointsmean > xcut) )[0] def filterfibersidx2(filtarr, lower, upper, curvarr, value): return np.where((filtarr>lower) & (filtarr<upper) & (curvarr >value) )[0] def filterccidx(endpoints, xcenterline): """ Returns the index of all fibers where the start or endpoint of each fiber is opposite the x centerline """ return np.where((endpoints[:,0,0]>xcenterline) & (endpoints[:,1,0]<xcenterline))[0] def compfilterccidx(endpoints, xcenterline, onlyleft = True): """ Returns the index of all fibers where the start or endpoint of each fiber is opposite the x centerline """ if onlyleft: return np.where( (((endpoints[:,0,0]>xcenterline) & (endpoints[:,1,0]>xcenterline)) | ((endpoints[:,0,0]<xcenterline) & (endpoints[:,1,0]<xcenterline))) & ((endpoints[:,0,0]<xcenterline) & (endpoints[:,1,0]<xcenterline)) )[0] else: return np.where( ((endpoints[:,0,0]>xcenterline) & (endpoints[:,1,0]>xcenterline)) | ((endpoints[:,0,0]<xcenterline) & (endpoints[:,1,0]<xcenterline)) )[0] def showfibfvtk(fibarr, colarr, percentage = 100): fibarr2 = fibarr[::percentage] colarr2 = colarr[::percentage] fibarr2list = fibarr2.tolist() r=fvtk.ren(); #fvtk.add(r,fvtk.axes()) r.SetBackground(1, 1, 1) [fvtk.add(r,fvtk.line(ele, colarr2[i,:])) for i, ele in enumerate(fibarr2list)]; fvtk.show(r, title = "Fibers", size = (500,500)) def showfibfos(fibarr, colarr, percentage = 100): fibarr2 = fibarr[::percentage] colarr2 = colarr[::percentage].astype('f4') cu = InteractiveCurves(curves = fibarr2.tolist(), colors = colarr2) w=World() w.add(cu) wi = Window(caption="Multi-Modal 1", width = 800, height = 800) wi.attach(w) def preparecolorarray(clustering, number_of_fibers): colors=np.zeros((number_of_fibers,4)) for c in clustering: color=np.random.rand(1,4) for i in clustering[c]['indices']: colors[i]=color colors[:,3] = 1.0 # need alpha channel return colors def angle(x,y): return np.rad2deg(np.arccos(np.dot(x,y)/np.sqrt(np.dot(x,x))/np.sqrt(np.dot(y,y)))) def compute_angle_array(tracksobj, downsampling = 3): n = tracksobj.shape[0] fiberangles = np.zeros( (n, 1) ) if downsampling == 3: for i in xrange(n): x=tracksobj[i][0]-tracksobj[i][1] y=tracksobj[i][2]-tracksobj[i][1] fiberangles[i] = angle(x,y) return fiberangles # start script # Compute the distance array dist = compute_start_end_distances(endpoints) # Inspect histogram to find xcenterline # hist(endpoints[:,0,0],200) # -> e.g. found x coordinate 103 # compute distance mean distmean = np.mean(endpoints[:,:,0],axis=1) # noccidx = filterfibersidx(distmean, 70, 104) # good to have cc and few corticospinal noccidx = filterfibersidxcomplement(distmean, 70, 104) # good to have cc and few corticospinal # change hemi parameter to switch hemisphere onlyleftidx = filterhemisphere(distmean, 84, hemi = 1) noccidx = np.intersect1d(noccidx , onlyleftidx) # 4. filter out corpous callosum fibers # noccidx = compfilterccidx(endpoints, 84, False) noccfibers = fibers[noccidx] # 5. show fibers without cc #showfibfvtk(noccfibers,randcolarr(noccfibers), 1000) # 6. look at distance histogram #hist(dist,100) # 7. compute new distance histogram for fibers without cc distnocc = compute_start_end_distances(endpoints[noccidx,:,:]) meancuvnocc = meancurv[noccidx] #hist(distnocc,100) #hist(meancuvnocc,100) # 8. find short fibers and show them #shortfibers = noccfibers[filterfibersidx(distnocc, 0, 30)] #showfibfvtk(shortfibers,randcolarr(shortfibers), 100) # using meancurvature shortfibers = noccfibers[filterfibersidx2(distnocc, 10, 30, meancuvnocc, 0.05)] #showfibfvtk(shortfibers,randcolarr(shortfibers), 10) #shortfibers = noccfibers[filterfibersidx(dist, 8, 40)] # 120-180: long range # around 85: some projection, cortico spinal, temporal association # 8-40: enough U fibers # 9. fiber clustering fiblist = shortfibers.tolist() print("Downsampling...") tracks=[tm.downsample(t,3) for t in fiblist] # calculate the angle of downsampled fibers tracksobj=np.array(tracks, dtype=np.object) fiberangles = compute_angle_array(tracksobj) # filter fibers fiberangleidx = filterfibersidx(fiberangles, 20, 80) # create new short fiber set shortfibersnew = shortfibers[fiberangleidx] tracksobjnew = tracksobj[fiberangleidx] print("Clustering....") now=time.clock() C=td.local_skeleton_clustering(tracksobjnew.tolist(),d_thr=10) print('Done in %.2f s' % (time.clock()-now,)) # 10. prepare color array and show mycols = preparecolorarray(C, len(shortfibersnew)) #showfibfvtk(shortfibersnew,mycols, 10) #mycols = preparecolorarray(C, len(shortfibers)) #mycols = randcolarr(shortfibers) #showfibfvtk(shortfibers,mycols, 50) # only show left hemisphere # show number of fibers in each bundle histogram a=np.array([(id,v['N']) for id, v in C.items()]) idx=np.where(a[:,1] < 100)[0] allidx = np.arange(tracksobjnew.shape[0]) for i in idx: idxremove = C[i]['indices'] allidx = np.lib.arraysetops.setdiff1d(allidx, C[i]['indices']) #del C[i] shortfibersnew2 = shortfibersnew[allidx] tracksobjnew2 = tracksobjnew[allidx] C2=td.local_skeleton_clustering(tracksobjnew2.tolist(),d_thr=9) mycols2 = preparecolorarray(C2, len(shortfibersnew2)) # show with fos showfibfvtk(shortfibersnew2,mycols2, 10) #showfibfos(shortfibersnew2,mycols2, 50) #hist(a,100) # use fos to show with bigger sized tubes """ percentage=1 fibarr2 = shortfibersnew2[::percentage] colarr2 = mycols2[::percentage].astype('f4') cu = InteractiveCurves(curves = fibarr2.tolist(), colors = colarr2, line_width = 6.0) w=World() w.add(cu) wi = Window(caption="Multi-Modal 1", width = 1200, height = 900, bgcolor = (1,1,1,0)) wi.attach(w) # w.delete(cu) """ ''' threedviz2 = """ # Modified from NetworkX drawing # https://networkx.lanl.gov/trac/browser/networkx/examples/drawing/mayavi2_spring.py import networkx as nx import numpy as np from enthought.mayavi import mlab # Retrieve NetworkX graph G = cfile.obj.get_by_name("connectome_freesurferaparc").data # Key value on the nodes to transform to scalar value for node coloring node_scalar_key = "dn_correspondence_id" # Network Layouting: 2d circular layout pos=nx.circular_layout(G,dim=2,scale=1) # numpy array of x,y,z positions in sorted node order xyz=np.array([pos[v] for v in sorted(G)]) # adding zero z coordinate xyz = np.hstack( (xyz, np.zeros( (len(xyz), 1) ) ) ) # Network Layouting: 3d spring layout #pos=nx.spring_layout(G,dim=3) # numpy array of x,y,z positions in sorted node order #xyz=np.array([pos[v] for v in sorted(G)]) # If you do not want to apply a layouting algorithm # You can create the xyz array from your node positions # as displayed in Code Oracle "3D Network" # scalar colors scalars = np.zeros( (len(G.nodes()),) ) for i,data in enumerate(G.nodes(data=True)): scalars[i] = float(data[1][node_scalar_key]) mlab.figure(1, bgcolor=(0, 0, 0)) mlab.clf() pts = mlab.points3d(xyz[:,0], xyz[:,1], xyz[:,2], scalars, scale_factor=0.05, scale_mode='none', colormap='Blues', resolution=20) # Defines only the connectivity # You can combine this script with the "3D Network" Code Oracle pts.mlab_source.dataset.lines = np.array(G.edges()) tube = mlab.pipeline.tube(pts, tube_radius=0.008) mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8)) # You can store the resulting figure programmatically # mlab.savefig('mynetwork.png') """ nipypebet = """ # Prerequisite: # 1. You need to have Nipype installed on your system. You can check this by entering # import nipype # In the IPython console. If it gives an error, you might want to install it from NeuroDebian. # See http://neuro.debian.net/ - Documentation is on http://nipy.sourceforge.net/nipype/ # 2. For this simple brain extraction script, you need to have FSL installed. # Goal: # This script shows how to extract the brain using BET through the Nipype interface. # It is derived from http://nipy.sourceforge.net/nipype/users/dartmouth_workshop_2010.html # As an input, you need a T1-weighted image that as an input to the Nipype node. rawimage = cfile.obj.get_by_name('MYRAWT1IMAGE') # Let's check if the metadata agrees with what is expected (it should say "T1-weighted") print rawimage.dtype # We do not necessarily need to load the connectome object - if the connectome file is extracted # locally. We just need to retrieve the absolute file path rawimage_pwd = rawimage.get_abs_path() # We need the Nipype FSL interface import nipype.interfaces.fsl as fsl # We set the FSL default output type to compressed Nifti-1 fsl.FSLCommand.set_default_output_type('NIFTI_GZ') # We want to store the processed file in the temporary folder for now. fname_out = '/tmp/only_brain.nii.gz' # Now, we run the Nipype BET node, providing the correct input result = fsl.BET(in_file=rawimage_pwd, out_file = fname_out ).run() # We can print the result print result.outputs # To add the processed data file to the currently loaded connectome file, ... #cvol = cf.CVolume(name="BETed brain", src=fname_out, fileformat='Nifti1GZ', dtype='T1-weighted') #cfile.obj.add_connectome_volume(cvol) # Make sure that you save the connectome file if you want to keep the processed file. """ pushpull = """ # Prerequisite: # 1. For this script to run, you need to have PyXNAT installed # on your PYTHONPATH system. You can get it from http://packages.python.org/pyxnat/ # 2. You need to have access to an XNAT server and a project # You can create a login and project here: # http://central.xnat.org/ # http://sandbox.xnat.org/ # Goal: # 1. We want to push a connectome file to an XNAT server # 2. We want to pull a connectome file from an XNAT server # Hint: # If you plan to retrieve or upload big datasets, it is recommended to run this # script in an external Python shell, as long script executions block the IPython # shell within the Connectome Viewer. # We assume that a connectome file is currently loaded. For testing purposes, # it is beneficial if the files are not too big. # We need to load cfflib import cfflib as cf # Retrieve the currently loaded connectome object to push to the XNAT Server a = cfile.obj # You need to setup the XNAT connection cf.set_xnat_connection({'server': 'http://sandbox.xnat.org', 'user':'YOURUSERNAME', 'password':'YOURPASSWORD'}) # You need to have write access on the XNAT Server given. You will need the projectid to push # data to the server. In addition, you need to provide a subjectid and an experimentid. If overwrite # is set to True, remote files are overwritten by the local files. # Then, you can push the connectome file to XNAT cf.xnat_push( connectome_obj = a, projectid = "YOURPROJECTID", subjectid = "SUBJECTID", experimentid = "EXPID", overwrite = False) # NB: On the remote server, unique identifier for the subject and experiment id are generated, using the project id. # The push operation may take some time. # Similarly as you pushed a connectome file to XNAT, you can pull it again from the server. # You need the same identifiers to retrieve the data again. In addition, you need to provide a storage # path for the retrieved files. #cf.xnat_pull( projectid = "YOURPROJECTID", subjectid = "SUBJECTID", experimentid = "EXPID", '/YOUR/FILE/STORAGE/PATH') # In case you want to load the pulled connectome object, you can load it using cfflib #import cfflib as cf; mynewcon = cf.load( '/YOUR/FILE/STORAGE/PATH/meta.cml' ) """ surfscript = """ # Importing Mayavi mlab interface from enthought.mayavi import mlab # Retrieving the data # ------------------- # surface data from connectome file surface_file_vertices = cfile.obj.get_by_name("%s") vertices = surface_file_vertices.data.darrays[%s].data surface_file_faces = cfile.obj.get_by_name("%s") faces = surface_file_faces.data.darrays[%s].data labelname = "%s" surface_file_labels = cfile.obj.get_by_name(labelname) # Sanity check # ------------ # ensure that (triangluar) faces have dimension (N,3) if len(faces.shape) == 1: faces = faces.reshape( (len(faces) / 3, 3) ) # check for labels if labelname == "None": labels = None else: labels = surface_file_labels.data.darrays[%s].data # Ensure correct dimension (1-D) for labels labels = labels.ravel() # Ensure that each vertices has a corresponding label assert vertices.shape[0] == len(labels) # Perform task # ------------ # Create triangular surface mesh x, y, z = vertices[:,0], vertices[:,1], vertices[:,2] mlab.triangular_mesh(x, y, z, faces, scalars = labels) """ conmatrix = """ # Importing NetworkX import networkx as nx # Import the Connectome Matrix Viewer from cviewer.visualization.matrix.con_matrix_viewer import ConnectionMatrixViewer # Retrieving the data # ------------------- # retrieve the graph g = cfile.obj.get_by_name("%s").data # set the node key to use the labels nodelabelkey = "%s" # Defining some helper functions # ------------------------------ def relabel_to_int(graph): " Relabel string node ids to integer " def intmap(x): return int(x) return nx.relabel_nodes(graph,intmap) def get_nodelabels(graph, nodekey = 'dn_label'): " Retrieve a list of node labels " g = relabel_to_int(graph) a = [] return [v[nodekey] for n,v in g.nodes_iter(data=True)] def get_edge_values(graph): " Retrieve valid edge keys " if len(graph.edges()) == 0: return edi = graph.edges_iter(data=True) u,v,ed = edi.next() ret = [] for k,v in ed.items(): if isinstance(v, float) or isinstance(v, int): ret.append(k) return ret def get_matdict(graph): matdict = {} g = relabel_to_int(graph) # grab keys from the first edge, discarding id dl = get_edge_values(g)