This commit is contained in:
Ritchie Martori
2011-11-21 22:59:22 -08:00
parent 256d9ab91b
commit 345f31cf32
10 changed files with 3510 additions and 1 deletions

View File

@@ -0,0 +1,62 @@
body {background: #000;}
.container {color: #DFFFBD; font-size: 14px; font-family: monaco}
.terminal .clipboard {
position: absolute;
bottom: 0;
left: 0;
opacity: 0.01;
filter: alpha(opacity = 0.01);
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.01);
width: 2px;
}
.cmd > .clipboard {
position: fixed;
}
.terminal {
padding: 10px;
position: relative;
overflow: hidden;
}
.cmd {
padding: 0;
margin: 0;
height: 1.3em;
}
.terminal .terminal-output div {
display: block;
}
.terminal, .terminal .terminal-output, .terminal .terminal-output div,
.terminal .terminal-output div div, .cmd, .terminal .cmd span, .terminal .cmd div {
font-family: monospace;
color: #aaa;
background-color: #000;
font-size: 12px;
}
.terminal .cmd span {
float: left;
}
.terminal .cmd span.inverted {
background-color: #aaa;
color: #000;
}
.terminal div::-moz-selection, .terminal span::-moz-selection {
background-color: #aaa;
color: #000;
}
.terminal div::selection, .terminal span::selection {
background-color: #aaa;
color: #000;
}
.terminal .terminal-output div.error, .terminal .terminal-output div.error div {
color: red;
}
.tilda {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 1100;
}
.clear {
clear: both;
}

View File

@@ -35,12 +35,14 @@
<div id="menu" class="three columns">
<div class="panel">
<h5>App Config</h5>
<hr />
<hr />
<h5>Plugins</h5>
<div class="links">
<em>No Plugins Loaded</em>
</div>
<hr />
<a href="console.htm">Console</a>
<hr />
<p>Browse the <a href="">plugin library</a> for useful add-ons or use our plugin generator to quickly build your own.</p>
<a href="" class="small radius nice blue button">Create New Plugin</a>
</div>

View File

@@ -0,0 +1,78 @@
body {background: #000;}
.terminal .clipboard {
position: absolute;
bottom: 0;
left: 0;
opacity: 0.01;
filter: alpha(opacity = 0.01);
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.01);
width: 2px;
}
.cmd > .clipboard {
position: fixed;
}
.terminal {
padding: 10px;
position: relative;
overflow: hidden;
}
.cmd {
padding: 0;
margin: 0;
height: 1.3em;
}
.terminal .terminal-output div {
display: block;
}
.terminal, .terminal .terminal-output, .terminal .terminal-output div,
.terminal .terminal-output div div, .cmd, .terminal .cmd span, .terminal .cmd div {
font-family: Monaco, monospace;
color: #DEFFAD;
background-color: #000;
font-weight: bold;
font-size: 14px;
}
.terminal .cmd span {
float: left;
}
.terminal .cmd span.inverted {
background-color: #DEFFAD;
color: #000;
}
.terminal div::-moz-selection, .terminal span::-moz-selection {
background-color: #DEFFAD;
color: #000;
}
.terminal div::selection, .terminal span::selection {
background-color: #DEFFAD;
color: #000;
}
.terminal .terminal-output div.error, .terminal .terminal-output div.error div {
color: red;
}
.tilda {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 1100;
}
.clear {
clear: both;
}
/* json */
.key {
color: #A6FFC8;
}
.string {
color: #EEFFC9;
}
.boolean {
color: #FFFCA6;
}

71
public/terminal/index.html Executable file
View File

@@ -0,0 +1,71 @@
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>JSON-RPC Demo for JQuery Terminal Emulator</title>
<meta name="author" content="Jakub Jankiewicz - jcubic&#64;onet.pl"/>
<meta name="Description" content="Demonstration for JQuery Terminal Emulator using call automaticly JSON-RPC service (in php) with authentication."/>
<link rel="sitemap" type="application/xml" title="Sitemap" href=""/>
<link rel="shortcut icon" href="favicon.ico"/>
<script src="../deployd.js"></script>
<script src="js/jquery-1.5.min.js"></script>
<script src="js/jquery.terminal-0.4.3.min.js"></script>
<script src="js/prettyprint.js"></script>
<link href="css/jquery.terminal.css" rel="stylesheet"/>
</head>
<body>
<div id="terminal"></div>
<script>
jQuery(document).ready(function($) {
function scroll(argument) {
$('body, html').scrollTop($('html').height())
}
var terminal = $('#terminal').terminal(function(command, term) {
switch(command) {
case 'settings':
d('/settings');
break;
default:
eval(command);
break;
}
}, {
greetings: 'Deployd REPL',
prompt: 'deployd >'
});
jQuery.ajaxSetup({
complete: function(res) {
try {
var result = JSON.parse(res.responseText);
var print = JSON.stringify(result, null, 2);
print = print.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
$('.terminal-output').append('<pre>' + print + '</pre>');
} catch(e) {
terminal.error(res.responseText);
}
scroll();
}
})
});
</script>
</body>

63
public/terminal/js/dterm.js Executable file
View File

@@ -0,0 +1,63 @@
/*!
* Example plugin using JQuery Terminal Emulator
* Copyright (C) 2010 Jakub Jankiewicz <http://jcubic.pl>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function($) {
$.extend_if_has = function(desc, source, array) {
for (var i=array.length;i--;) {
if (typeof source[array[i]] != 'undefined') {
desc[array[i]] = source[array[i]];
}
}
return desc;
};
$.fn.dterm = function(eval, options) {
var op = $.extend_if_has({}, options,
['greetings', 'prompt', 'onInit',
'onExit', 'clear',
'login', 'name', 'exit']);
op.enabled = false;
var terminal = this.terminal(eval, op).css('overflow', 'hidden');
if (!options.title) {
options.title = 'JQuery Terminal Emulator';
}
if (options.logoutOnClose) {
options.close = function(e, ui) {
terminal.logout();
terminal.clear();
};
} else {
options.close = function(e, ui) {
terminal.disable();
};
}
var self = this;
var dialog = this.dialog($.extend(options, {
resizeStop: function(e, ui) {
var content = self.find('.ui-dialog-content');
terminal.resize(content.width(), content.height());
},
open: function(e, ui) {
terminal.focus();
terminal.resize();
},
show: 'fade',
closeOnEscape: false
}));
self.terminal = terminal;
return self;
};
})(jQuery);

16
public/terminal/js/jquery-1.5.min.js vendored Executable file

File diff suppressed because one or more lines are too long

14
public/terminal/js/jquery.mousewheel-min.js vendored Executable file
View File

@@ -0,0 +1,14 @@
/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
*
* $LastChangedDate: 2007-12-20 09:02:08 -0600 (Thu, 20 Dec 2007) $
* $Rev: 4265 $
*
* Version: 3.0
*
* Requires: $ 1.2.2+
*/
(function(a){a.event.special.mousewheel={setup:function(){var b=a.event.special.mousewheel.handler;if(a.browser.mozilla){a(this).bind("mousemove.mousewheel",function(c){a.data(this,"mwcursorposdata",{pageX:c.pageX,pageY:c.pageY,clientX:c.clientX,clientY:c.clientY})})}if(this.addEventListener){this.addEventListener((a.browser.mozilla?"DOMMouseScroll":"mousewheel"),b,false)}else{this.onmousewheel=b}},teardown:function(){var b=a.event.special.mousewheel.handler;a(this).unbind("mousemove.mousewheel");if(this.removeEventListener){this.removeEventListener((a.browser.mozilla?"DOMMouseScroll":"mousewheel"),b,false)}else{this.onmousewheel=function(){}}a.removeData(this,"mwcursorposdata")},handler:function(d){var b=Array.prototype.slice.call(arguments,1);d=a.event.fix(d||window.event);a.extend(d,a.data(this,"mwcursorposdata")||{});var e=0,c=true;if(d.wheelDelta){e=d.wheelDelta/120}if(d.detail){e=-d.detail/3}d.data=d.data||{};d.type="mousewheel";b.unshift(e);b.unshift(d);return a.event.handle.apply(this,b)}};a.fn.extend({mousewheel:function(b){return b?this.bind("mousewheel",b):this.trigger("mousewheel")},unmousewheel:function(b){return this.unbind("mousewheel",b)}})})(jQuery);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,77 @@
/*
| __ _____ ________ __
| / // _ /__ __ _____ ___ __ _/__ ___/__ ___ ______ __ __ __ ___ / /
| __ / // // // // // _ // _// // / / // _ // _// // // \/ // _ \/ /
| / / // // // // // ___// / / // / / // ___// / / / / // // /\ // // / /__
| \___//____ \\___//____//_/ _\_ / /_//____//_/ /_/ /_//_//_/ /_/ \__\_\___/
| \/ /____/ version 0.4.3
http://terminal.jcubic.pl
Licensed under GNU LGPL Version 3 license
Copyright (c) 2011 Jakub Jankiewicz <http://jcubic.pl>
Includes:
Storage plugin Distributed under the MIT License
Copyright (c) 2010 Dave Schindler
LiveQuery plugin Dual MIT and GPL
Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
jQuery Timers licenced with the WTFPL
<http://jquery.offput.ca/every/>
Date: Thu, 20 Oct 2011 14:31:02 +0000
*/
Array.prototype.has=function(g){for(var z=this.length;z--;)if(this[z]==g)return true;return false};function get_stack(g){return g?[g.toString().match(/.*\n.*\n/)].concat(get_stack(g.caller)):[]}
(function(g,z){function Y(b,d){var f;if(typeof b==="string"&&typeof d==="string"){localStorage[b]=d;return true}else if(typeof b==="object"&&typeof d==="undefined"){for(f in b)if(b.hasOwnProperty(f))localStorage[f]=b[f];return true}return false}function V(b,d){var f,e;f=new Date;f.setTime(f.getTime()+31536E6);f="; expires="+f.toGMTString();if(typeof b==="string"&&typeof d==="string"){document.cookie=b+"="+d+f+"; path=/";return true}else if(typeof b==="object"&&typeof d==="undefined"){for(e in b)if(b.hasOwnProperty(e))document.cookie=
e+"="+b[e]+f+"; path=/";return true}return false}function Z(b){return localStorage[b]}function $(b){var d,f,e;b+="=";d=document.cookie.split(";");for(f=0;f<d.length;f++){for(e=d[f];e.charAt(0)===" ";)e=e.substring(1,e.length);if(e.indexOf(b)===0)return e.substring(b.length,e.length)}return null}function aa(b){return delete localStorage[b]}function ba(b){return V(b,"",-1)}function U(b,d){var f=[],e=b.length;if(e<d)return[b];for(var j=0;j<e;j+=d)f.push(b.substring(j,j+d));return f}function E(b){if(typeof b==
"string"){b=b.replace(/&(?!#[0-9]*;)/g,"&amp;");b=b.replace(/</g,"&lt;").replace(/>/g,"&gt;");b=b.replace(/\n/g,"<br/>");b=b.replace(/ /g,"&nbsp;");b=b.replace(/\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;");var d=b.split(ca);if(d.length>1)b=g.map(d,function(f){return f===""?f:f[0]=="["?f.replace(da,function(e,j,q,y,F){if(F==="")return"<span>&nbsp;</span>";e="";if(j.indexOf("b")!=-1)e+="font-weight:bold;";if(j.indexOf("u")!=-1)e+="text-decoration:underline;";if(j.indexOf("i")!=-1)e+="font-style:italic; ";if(q.match(W))e+=
"color:"+q+";";if(y.match(W))e+="background-color:"+y;return b='<span style="'+e+'">'+F+"</span>"}):"<span>"+f+"</span>"}).join("");return b}else return""}function X(b){var d=b instanceof Array?b:b?[b]:[],f=0;g.extend(this,{left:function(){if(f===0)f=d.length-1;else--f;return d[f]},right:function(){if(f==d.length-1)f=0;else++f;return d[f]},current:function(){return d[f]},data:function(){return d},length:function(){return d.length},reset:function(){f=0},append:function(e){d.push(e);this.reset()}})}
function ea(b){var d=b?[b]:[];g.extend(this,{size:function(){return d.length},pop:function(){if(d.length===0)return null;else{var f=d[d.length-1];d=d.slice(0,d.length-1);return f}},push:function(f){d=d.concat([f]);return f},top:function(){return d.length>0?d[d.length-1]:null}})}function fa(b){var d=true;if(typeof b==="string"&&b!=="")b+="_";var f=g.Storage.get(b+"commands"),e=new X(f?eval("("+f+")"):[""]);g.extend(this,{append:function(j){if(d&&e.current()!=j){e.append(j);g.Storage.set(b+"commands",
g.json_stringify(e.data()))}},data:function(){return e.data()},next:function(){return e.right()},last:function(){e.reset()},previous:function(){return e.left()},clear:function(){e=new X;g.Storage.remove(b+"commands")},enable:function(){d=true},disable:function(){d=false}})}g.extend(g.fn,{livequery:function(b,d,f){var e=this,j;if(g.isFunction(b)){f=d;d=b;b=z}g.each(g.livequery.queries,function(q,y){if(e.selector==y.selector&&e.context==y.context&&b==y.type&&(!d||d.$lqguid==y.fn.$lqguid)&&(!f||f.$lqguid==
y.fn2.$lqguid))return(j=y)&&false});j=j||new g.livequery(this.selector,this.context,b,d,f);j.stopped=false;j.run();return this},expire:function(b,d,f){var e=this;if(g.isFunction(b)){f=d;d=b;b=z}g.each(g.livequery.queries,function(j,q){if(e.selector==q.selector&&e.context==q.context&&(!b||b==q.type)&&(!d||d.$lqguid==q.fn.$lqguid)&&(!f||f.$lqguid==q.fn2.$lqguid)&&!this.stopped)g.livequery.stop(q.id)});return this}});g.livequery=function(b,d,f,e,j){this.selector=b;this.context=d||document;this.type=
f;this.fn=e;this.fn2=j;this.elements=[];this.stopped=false;this.id=g.livequery.queries.push(this)-1;e.$lqguid=e.$lqguid||g.livequery.guid++;if(j)j.$lqguid=j.$lqguid||g.livequery.guid++;return this};g.livequery.prototype={stop:function(){var b=this;if(this.type)this.elements.unbind(this.type,this.fn);else this.fn2&&this.elements.each(function(d,f){b.fn2.apply(f)});this.elements=[];this.stopped=true},run:function(){if(!this.stopped){var b=this,d=this.elements,f=g(this.selector,this.context),e=f.not(d);
this.elements=f;if(this.type){e.bind(this.type,this.fn);d.length>0&&g.each(d,function(j,q){g.inArray(q,f)<0&&g.event.remove(q,b.type,b.fn)})}else{e.each(function(){b.fn.apply(this)});this.fn2&&d.length>0&&g.each(d,function(j,q){g.inArray(q,f)<0&&b.fn2.apply(q)})}}}};g.extend(g.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if(g.livequery.running&&g.livequery.queue.length)for(var b=g.livequery.queue.length;b--;)g.livequery.queries[g.livequery.queue.shift()].run()},
pause:function(){g.livequery.running=false},play:function(){g.livequery.running=true;g.livequery.run()},registerPlugin:function(){g.each(arguments,function(b,d){if(g.fn[d]){var f=g.fn[d];g.fn[d]=function(){var e=f.apply(this,arguments);g.livequery.run();return e}}})},run:function(b){if(b!=z)g.inArray(b,g.livequery.queue)<0&&g.livequery.queue.push(b);else g.each(g.livequery.queries,function(d){g.inArray(d,g.livequery.queue)<0&&g.livequery.queue.push(d)});g.livequery.timeout&&clearTimeout(g.livequery.timeout);
g.livequery.timeout=setTimeout(g.livequery.checkQueue,20)},stop:function(b){b!=z?g.livequery.queries[b].stop():g.each(g.livequery.queries,function(d){g.livequery.queries[d].stop()})}});g.livequery.registerPlugin("append","prepend","after","before","wrap","attr","removeAttr","addClass","removeClass","toggleClass","empty","remove");g(function(){g.livequery.play()});var ga=g.prototype.init;g.prototype.init=function(b,d){var f=ga.apply(this,arguments);if(b&&b.selector){f.context=b.context;f.selector=
b.selector}if(typeof b=="string"){f.context=d||document;f.selector=b}return f};g.prototype.init.prototype=g.prototype;var Q=typeof window.localStorage!=="undefined";g.extend({Storage:{set:Q?Y:V,get:Q?Z:$,remove:Q?aa:ba}});jQuery.fn.extend({everyTime:function(b,d,f,e,j){return this.each(function(){jQuery.timer.add(this,b,d,f,e,j)})},oneTime:function(b,d,f){return this.each(function(){jQuery.timer.add(this,b,d,f,1)})},stopTime:function(b,d){return this.each(function(){jQuery.timer.remove(this,b,d)})}});
jQuery.extend({timer:{guid:1,global:{},regex:/^([0-9]+)\s*(.*s)?$/,powers:{ms:1,cs:10,ds:100,s:1E3,das:1E4,hs:1E5,ks:1E6},timeParse:function(b){if(b==z||b===null)return null;var d=this.regex.exec(jQuery.trim(b.toString()));return d[2]?parseInt(d[1],10)*(this.powers[d[2]]||1):b},add:function(b,d,f,e,j,q){var y=0;if(jQuery.isFunction(f)){j||(j=e);e=f;f=d}d=jQuery.timer.timeParse(d);if(!(typeof d!="number"||isNaN(d)||d<=0)){if(j&&j.constructor!=Number){q=!!j;j=0}j=j||0;q=q||false;if(!b.$timers)b.$timers=
{};b.$timers[f]||(b.$timers[f]={});e.$timerID=e.$timerID||this.guid++;var F=function(){if(!(q&&this.inProgress)){this.inProgress=true;if(++y>j&&j!==0||e.call(b,y)===false)jQuery.timer.remove(b,f,e);this.inProgress=false}};F.$timerID=e.$timerID;b.$timers[f][e.$timerID]||(b.$timers[f][e.$timerID]=window.setInterval(F,d));this.global[f]||(this.global[f]=[]);this.global[f].push(b)}},remove:function(b,d,f){var e=b.$timers,j;if(e){if(d){if(e[d]){if(f){if(f.$timerID){window.clearInterval(e[d][f.$timerID]);
delete e[d][f.$timerID]}}else for(f in e[d]){window.clearInterval(e[d][f]);delete e[d][f]}for(j in e[d])break;if(!j){j=null;delete e[d]}}}else for(d in e)this.remove(b,d,f);for(j in e)break;if(!j)b.$timers=null}}}});if(jQuery.browser.msie)jQuery(window).one("unload",function(){var b=jQuery.timer.global,d;for(d in b)for(var f=b[d],e=f.length;--e;)jQuery.timer.remove(f[e],d)});var ca=/(\[\[[biu]*;[^;]*;[^\]]*\][^\]\[]*\])/g,da=/\[\[([biu]*);([^;]*);([^\]]*)\]([^\]\[]*)\]/g,W=/#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})/;
g.json_stringify=function(b,d){var f="",e;d=d===z?1:d;switch(typeof b){case "function":f+=b;break;case "boolean":f+=b?"true":"false";break;case "object":if(b===null)f+="null";else if(b instanceof Array){f+="[";var j=b.length;for(e=0;e<j-1;++e)f+=g.json_stringify(b[e],d+1);f+=g.json_stringify(b[j-1],d+1)+"]"}else{f+="{";for(j in b)if(b.hasOwnProperty(j))f+='"'+j+'":'+g.json_stringify(b[j],d+1);f+="}"}break;case "string":j=b;var q={"\\\\":"\\\\",'"':'\\"',"/":"\\/","\\n":"\\n","\\r":"\\r","\\t":"\\t"};
for(e in q)if(q.hasOwnProperty(e))j=j.replace(RegExp(e,"g"),q[e]);f+='"'+j+'"';break;case "number":f+=String(b)}f+=d>1?",":"";if(d==1)f=f.replace(/,([\]}])/g,"$1");return f.replace(/([\[{]),/g,"$1")};g.fn.cmd=function(b){function d(){L.toggleClass("inverted")}function f(){j.focus();e.oneTime(1,function(){e.insert(j.val());j.blur();j.val("")})}var e=this;e.addClass("cmd");e.append('<span class="prompt"></span><span></span><span class="cursor">&nbsp;</span><span></span>');var j=g("<textarea/>").addClass("clipboard").appendTo(e);
b.width&&e.width(b.width);var q,y,F=b.mask||false,o="",p=0,I,J=b.enabled,R,G,L=e.find(".cursor"),c=function(h){function u(t,v){if(v==t.length){B.html(E(t));L.html("&nbsp;");H.html("")}else if(v===0){B.html("");L.html(E(t.slice(0,1)));H.html(E(t.slice(1)))}else{var k=E(t.slice(0,v));B.html(k);k=t.slice(v,v+1);L.html(k==" "?"&nbsp;":E(k));v==t.lenght-1?H.html(""):H.html(E(t.slice(v+1)))}}function K(t){return"<div>"+E(t)+"</div>"}function P(t){var v=H;g.each(t,function(k,l){v=g(K(l)).insertAfter(v).addClass("clear")})}
function n(t){g.each(t,function(v,k){B.before(K(k))})}var B=L.prev(),H=L.next();return function(){var t=F?o.replace(/./g,"*"):o,v;h.find("div").remove();B.html("");if(t.length>q-y-1||t.match(/\n/)){var k;if(t.match(/\n/)){var l=t.split("\n"),a=q-y-1;for(v=0;v<l.length-1;++v)l[v]+=" ";if(l[0].length>a){k=[l[0].substring(0,a)];k=k.concat(U(l[0].substring(a),q))}else k=[l[0]];for(v=1;v<l.length;++v)if(l[v].length>q)k=k.concat(U(l[v],q));else k.push(l[v])}else{k=t.substring(0,q-y-1);a=t.substring(q-y-
1);k=[k].concat(U(a,q))}a=k[0].length;if(p<a){u(k[0],p);P(k.slice(1))}else if(p==a){B.before(K(k[0]));u(k[1],0);P(k.slice(2))}else{v=k.length;if(p<a){u(k[0],p);P(k.slice(1))}else if(p==a){B.before(K(k[0]));u(k[1],0);P(k.slice(2))}else{l=k.slice(-1)[0];var i=t.length-p;t=0;if(i<=l.length){n(k.slice(0,-1));t=l.length==i?0:l.length-i;u(l,t)}else if(v==3){B.before("<div>"+E(k[0])+"</div>");u(k[1],p-a-1);H.after('<div class="clear">'+E(k[2])+"</div>")}else{t=p;for(v=0;v<k.length;++v)if(t>k[v].length)t-=
k[v].length;else break;a=k[v];if(t==a.length){t=0;a=k[++v]}u(a,t);n(k.slice(0,v));P(k.slice(v+1))}}}}else if(t===""){B.html("");L.html("&nbsp;");H.html("")}else u(t,p)}}(e),M=function(){var h=e.find(".prompt");return function(){if(typeof I=="string"){y=I.length;h.html(E(I)+"&nbsp;")}else I(function(u){y=u.length;h.html(E(u)+"&nbsp;")})}}();g.extend(e,{name:function(h){if(h!==z){R=h;G=new fa(h)}else return R},history:function(){return G},set:function(h,u){if(h!==z){o=h;if(!u)p=o.length;c()}},insert:function(h,
u){if(p==o.length)o+=h;else o=p===0?h+o:o.slice(0,p)+h+o.slice(p);u||(p+=h.length);c()},get:function(){return o},commands:function(h){if(h)b.commands=h;else return h},destroy:function(){g(document.documentElement).unbind(".commandline");e.find(".prompt").remove()},prompt:function(h){if(h===z)return I;else{if(typeof h=="string"||typeof h=="function")I=h;else throw"prompt must be a function or string";M()}},position:function(h){if(typeof h=="number"){p=h<0?0:h>o.length?o.length:h;c()}else return p},
resize:function(h){if(h)q=h;else{h=e.width();var u=L.innerWidth();q=Math.floor(h/u)}c()},enable:function(){if(!J){e.everyTime(500,"blink",d);J=true}},isenabled:function(){return J},disable:function(){if(J){e.stopTime("blink",d);e.find(".cursor").removeClass("inverted");J=false}},mask:function(h){if(typeof h=="boolean"){F=h;c()}else return F}});e.name(b.name||"");I=b.prompt||">";M();if(b.enabled===z||b.enabled===true)e.enable();g(document.documentElement).keypress(function(h){var u;if(h.ctrlKey&&h.which==
99)return true;if(b.keypress)u=b.keypress(h);if(u===z||u){if(J)if([38,32,13,0,8].has(h.which)&&h.keyCode!=123&&!(h.which==38&&h.shiftKey))return false;else if(!h.ctrlKey&&!(h.altKey&&h.which==100)){e.insert(String.fromCharCode(h.which));return false}}else return u}).keydown(function(h){if(J){if(b.keydown&&b.keydown(h)===false)return false;var u;if(h.keyCode==13){G&&o&&G.append(o);G.last();h=o;e.set("");typeof I=="function"&&M();b.commands&&b.commands(h)}else if(h.which==32)e.insert(" ");else if(h.which==
8){if(o!==""&&p>0){o=o.slice(0,p-1)+o.slice(p,o.length);--p;c()}}else if(h.which==9&&!(h.ctrlKey||h.altKey))e.insert("\t");else if(h.which==46){if(o!==""&&p<o.length){o=o.slice(0,p)+o.slice(p+1,o.length);c()}return true}else if(G&&h.which==38||h.which==80&&h.ctrlKey)e.set(G.previous());else if(G&&h.which==40||h.which==78&&h.ctrlKey)e.set(G.next());else if(h.which==37||h.which==66&&h.ctrlKey)if(h.ctrlKey&&h.which!=66){u=p-1;h=0;for(o[u]==" "&&--u;u>0;--u)if(o[u]==" "&&o[u+1]!=" "){h=u+1;break}else if(o[u]==
"\n"&&o[u+1]!="\n"){h=u;break}e.position(h)}else{if(p>0){--p;c()}}else if(h.which==39||h.which==70&&h.ctrlKey)if(h.ctrlKey&&h.which!=70){o[p]==" "&&++p;h=o.slice(p).match(/\S[\n\s]{2,}|[\n\s]+\S?/);if(!h||h[0].match(/^\s+$/))p=o.length;else if(h[0][0]!=" ")p+=h.index+1;else{p+=h.index+h[0].length-1;h[0][h[0].length-1]!=" "&&--p}c()}else{if(p<o.length){++p;c()}}else if(h.which==123)return true;else if(h.which==36)e.position(0);else if(h.which==35)e.position(o.length);else if(h.ctrlKey||h.metaKey)if(h.shiftKey){if(h.which==
84)return true}else if(h.which==65)e.position(0);else if(h.which==69)e.position(o.length);else if(h.which==88||h.which==67||h.which==87||h.which==84)return true;else if(h.which==86){f();return true}else if(h.which==75)if(p===0)e.set("");else p!=o.length&&e.set(o.slice(0,p));else if(h.which==85)e.set("");else{if(h.which==17)return true}else if(h.altKey)h.which==68&&e.set(o.slice(0,p)+o.slice(p).replace(/[^ ]+ |[^ ]+$/,""),true);else return true;return false}});return e};g.jrpc=function(b,d,f,e,j,q){d=
g.json_stringify({jsonrpc:"2.0",method:f,params:e,id:d});return g.ajax({url:b,data:d,success:j,error:q,contentType:"application/json",dataType:"json",async:true,cache:false,type:"POST"})};Q=/ {13}$/;var ha=[["jQuery Terminal","(c) 2011 jcubic"],["JQuery Terminal Emulator v. 0.4.3","Copyright (c) 2011 Jakub Jankiewicz <http://jcubic.pl>".replace(/ *<.*>/,"")],["JQuery Terminal Emulator version version 0.4.3","Copyright (c) 2011 Jakub Jankiewicz <http://jcubic.pl>"],[" _______ ________ __",
" / / _ /_ ____________ _/__ ___/______________ _____ / /"," __ / / // / // / _ / _/ // / / / _ / _/ / / \\/ / _ \\/ /","/ / / // / // / ___/ // // / / / ___/ // / / / / /\\ / // / /__","\\___/____ \\\\__/____/_/ \\__ / /_/____/_//_/ /_/ /_/ \\/\\__\\_\\___/"," \\/ /____/ ".replace(Q,"")+"version 0.4.3","Copyright (c) 2011 Jakub Jankiewicz <http://jcubic.pl>"],[" __ _____ ________ __",
" / // _ /__ __ _____ ___ __ _/__ ___/__ ___ ______ __ __ __ ___ / /"," __ / // // // // // _ // _// // / / // _ // _// // // \\/ // _ \\/ /","/ / // // // // // ___// / / // / / // ___// / / / / // // /\\ // // / /__","\\___//____ \\\\___//____//_/ _\\_ / /_//____//_/ /_/ /_//_//_/ /_/ \\__\\_\\___/"," \\/ /____/ ".replace(Q,"")+"version 0.4.3","Copyright (c) 2011 Jakub Jankiewicz <http://jcubic.pl>"]],ia=[],N=new function(b){var d=
b?[b]:[],f=0;g.extend(this,{rotate:function(){if(d.length==1)return d[0];else{if(f==d.length-1)f=0;else++f;return d[f]}},length:function(){return d.length},set:function(e){for(var j=d.length;j--;)if(d[j]===e){f=j;return}this.append(e)},front:function(){return d[f]},append:function(e){d.push(e)}})};g.fn.terminal=function(b,d){function f(){var a=g("<span>x</span>").appendTo(c),i=Math.floor(c.width()/a.width());a.remove();return i}function e(a,i){c.error("&#91;"+i+"&#93;: "+(typeof a=="string"?a:a.fileName+
": "+a.message));c.pause();typeof a.fileName=="string"&&g.get(a.fileName,function(m){c.resume();var w=a.lineNumber-1;(m=m.split("\n")[w])&&c.error("&#91;"+a.lineNumber+"&#93;: "+m)})}function j(a,i){try{if(typeof i=="function")i(function(){});else if(typeof i!="string")throw a+" must be string or function";}catch(m){e(m,a.toUpperCase());return false}return true}function q(){var a=c.prop?c.prop("scrollHeight"):c.attr("scrollHeight");c.scrollTop(a)}function y(a){a=typeof a=="string"?a:String(a);var i,
m,w;if(a.length>K){i=K;var r=[];m=/(\[\[[biu]*;[^;]*;\][^\]\[]*\]?)/g;w=/(\[\[[biu]*;[^;]*;\])/;a=a.split(/\n/g);for(var x="",s=0,C=a.length;s<C;++s){if(x!=="")if(a[s]===""){r.push(x+"]");continue}else{a[s]=x+a[s];x=""}for(var A=0,T=a[s].length;A<T;A+=i){var D=a[s].substring(A,A+i);if(x!=="")D=x+D;var O=D.match(m);if(O&&O.length>0){var S=0;D=0;for(var ja=O.length;D<ja;++D){S+=O[D].match(w)[1].length;if(O[D][O[D].length-1]=="]")S+=1}if(x!=="")S-=x.length;D=x+a[s].substring(A,A+i+S);O=D.match(m);x=
O[O.length-1];A+=S;if(x[x.length-1]!="]"){D+="]";x=x.match(w)[1]}else x=""}else x="";r.push(D)}}i=g("<div></div>");m=0;for(w=r.length;m<w;++m)r[m]===""||r[m]=="\r"?i.append("<div>&nbsp;</div>"):g("<div/>").html(E(r[m])).appendTo(i)}else i=g("<div/>").html(E(a));h.append(i);i.width("100%");q();return i}function F(a,i){var m=1,w=function(r,x){i.pause();g.jrpc(a,m++,r,x,function(s){if(s.error)i.error("&#91;RPC&#93; "+s.error.message);else if(typeof s.result=="string")i.echo(s.result);else if(s.result instanceof
Array)i.echo(s.result.join(" "));else if(typeof s.result=="object"){var C="",A;for(A in s.result)if(s.result.hasOwnProperty(A))C+=A+": "+s.result[A]+"\n";i.echo(C)}i.resume()},function(s,C){i.error("&#91;AJAX&#93; "+C+" - Server reponse is: \n"+s.responseText);i.resume()})};return function(r,x){if(r!==""){var s,C;if(r.match(/[^ ]* /)){r=r.split(/ +/);s=r[0];C=r.slice(1)}else{s=r;C=[]}if(!n.login||s=="help")w(s,C);else{var A=x.token();A?w(s,[A].concat(C)):x.error("&#91;AUTH&#93; Access denied (no token)")}}}}
function o(a){var i=l.prompt();if(l.mask())a=a.replace(/./g,"*");typeof i=="function"?i(function(m){c.echo(m+" "+a)}):c.echo(i+" "+a)}function p(a){try{var i=k.top();if(a=="exit"&&n.exit)if(k.size()==1)n.login?J():c.echo("You can exit from main interpeter");else c.pop("exit");else{o(a);if(a=="clear"&&n.clear)c.clear();else if(a.match(/\|/)){var m=a.split(/\s*\|\s*/),w=[],r=c.echo;c.echo=function(D){w.push(D)};i.eval(m[0],c);a=1;for(var x=m.length;a<x-1;++a)for(var s=0,C=w.length;s<C;++s){var A=m[a]+
" "+w[s];i.eval(A,c)}c.echo=r;s=0;for(C=w.length;s<C;++s){A=m[x-1]+" "+w[s];i.eval(A,c)}}else i.eval(a,c)}}catch(T){e(T,"USER");c.resume();throw T;}}function I(){var a=null;l.prompt("login:");n.history&&l.history().disable();l.commands(function(i){try{o(i);if(a){l.mask(false);c.pause();if(typeof n.login!="function")throw"Value of login property must be a function";n.login(a,i,function(w){if(w){var r=n.name;r=r?"_"+r:"";g.Storage.set("token"+r,w);g.Storage.set("login"+r,a);l.commands(p);G()}else{c.error("Wrong password try again");
l.prompt("login:");a=null}c.resume();n.history&&l.history().enable()})}else{a=i;l.prompt("password:");l.mask(true)}}catch(m){e(m,"LOGIN",c);throw m;}})}function J(){var a=n.name;a=a?"_"+a:"";g.Storage.remove("token"+a,null);g.Storage.remove("login"+a,null);n.history&&l.history().disable();I()}function R(){var a=k.top(),i="";if(a.name!==z&&a.name!=="")i+=a.name+"_";i+=u;l.name(i);l.prompt(a.prompt);n.history&&l.history().enable();l.set("");if(typeof a.onStart=="function")a.onStart(c)}function G(){R();
if(d.greetings===z)c.echo(c.signature);else d.greetings&&c.echo(d.greetings);if(typeof n.onInit=="function")n.onInit(c)}function L(a){if(!c.paused()){if(n.keydown&&n.keydown(a,c)===false)return false;if(a.which!=9)H=0;if(a.which==68&&a.ctrlKey){if(n.exit)if(l.get()==="")if(k.size()>1||n.login!==z)c.pop("");else{c.resume();c.echo("")}else c.set_command("");a.preventDefault()}else if(n.tabcompletion&&a.which==9){++H;a=l.get();if(!a.match(" ")){for(var i=RegExp("^"+a),m=k.top().command_list,w=[],r=m.length;r--;)i.test(m[r])&&
w.push(m[r]);if(w.length==1)c.set_command(w[0]);else if(w.length>1)if(H>=2){o(a);c.echo(w.join("\t"));H=0}}return false}else if(a.which==86&&a.ctrlKey){c.oneTime(1,function(){q()});return true}else if(a.which==9&&a.ctrlKey){N.length()>1&&c.focus(false);a.preventDefault()}else if(a.which==34)c.scroll(c.height());else a.which==33?c.scroll(-c.height()):c.attr({scrollTop:c.attr("scrollHeight")})}}var c=this,M=[],h,u=N.length(),K,P=[],n={name:"",prompt:">",history:true,exit:true,clear:true,enabled:true,
login:null,tabcompletion:false,onInit:null,onExit:null,keypress:null,keydown:null};if(d){d.width&&c.width(d.width);d.height&&c.height(d.height);g.extend(n,d)}var B=!n.enabled;if(c.length===0)throw'Sorry, but terminal said that "'+c.selector+'" is not valid selector!';c.ajaxSend(function(a,i){ia.push(i)});if(c.data("terminal"))return c.data("terminal");h=g("<div>").addClass("terminal-output").appendTo(c);c.addClass("terminal").append("<div/>");g.extend(c,{clear:function(){h.html("");l.set("");M=[];
c.attr({scrollTop:0});return c},paused:function(){return B},pause:function(){if(l){c.disable();l.hide()}return c},resume:function(){if(l){c.enable();l.show();q()}return c},cols:function(){return K},rows:function(){return M.length},history:function(){return l.history().data()},next:function(){if(N.length()==1)return c;else{var a=c.offset().top;c.height();c.scrollTop();var i=c,m=g(window).scrollTop(),w=m+g(window).height(),r=g(i).offset().top;if(r+g(i).height()>=m&&r<=w){N.front().disable();a=N.rotate().enable();
i=a.offset().top-50;g("html,body").animate({scrollTop:i},500);return a}else{c.enable();g("html,body").animate({scrollTop:a-50},500);return c}}},focus:function(a){c.oneTime(1,function(){if(N.length()==1)a===false?c.disable():c.enable();else if(a===false)c.next();else{N.front().disable();N.set(c);c.enable()}});return c},enable:function(){K===z&&c.resize();if(B)if(l){l.enable();B=false}return c},disable:function(){if(l){B=true;l.disable()}return c},enabled:function(){return B},signature:function(){var a=
c.cols();a=a<15?null:a<35?0:a<55?1:a<64?2:a<75?3:4;return a!==null?ha[a].join("\n")+"\n":""},version:function(){return"0.4.3"},get_command:function(){return l.get()},insert:function(a){l.insert(a);return c},set_prompt:function(a){j("prompt",a)&&l.prompt(a);return c},set_command:function(a){l.set(a);return c},set_mask:function(a){l.mask(a);return c},get_output:function(){return g.map(M,function(a,i){return typeof i=="function"?i():i}).get().join("\n")},resize:function(a,i){if(a&&i){c.width(a);c.height(i)}K=
f();l.resize(K);var m=h.detach();h.html("");g.each(M,function(w,r){y(typeof r=="function"?r():r)});c.prepend(m);q();return c},echo:function(a){M.push(a);return y(typeof a=="function"?a():a)},error:function(a){c.echo("[[;#f00;]"+a.replace(/\[/g,"&#91;").replace(/\]/g,"&#93;")+"]")},scroll:function(a){var i;if(c.prop){a>c.prop("scrollTop")&&a>0&&c.prop("scrollTop",0);i=c.prop("scrollTop");c.prop("scrollTop",i+a)}else{a>c.attr("scrollTop")&&a>0&&c.attr("scrollTop",0);i=c.attr("scrollTop");c.attr("scrollTop",
i+a)}return c},logout:n.login?function(){for(;k.size()>1;)k.pop();J();return c}:function(){throw"You don't have login function";},token:n.login?function(){var a=n.name;return g.Storage.get("token"+(a?"_"+a:""))}:null,login_name:n.login?function(){var a=n.name;return g.Storage.get("login"+(a?"_"+a:""))}:null,name:function(){return n.name},push:function(a,i){if(!i.prompt||j("prompt",i.prompt)){if(typeof a=="string")a=F(i.eval,c);k.push(g.extend({eval:a},i));R()}return c},pop:function(a){a!==z&&o(a);
if(k.top().name===n.name){if(n.login){J();if(typeof n.onExit=="function")n.onExit(c)}}else{a=k.pop();R();if(typeof a.onExit=="function")a.onExit(c)}return c}});var H=0,t;switch(typeof b){case "string":t=b;b=F(b,c);break;case "object":for(var v in b)P.push(v);b=function a(i){return function(m){if(m!==""){m=m.split(/ +/);var w=m[0],r=m.slice(1);m=i[w];var x=typeof m;if(x=="function")m.apply(c,r);else if(x=="object"||x=="string"){r=[];if(x=="object"){for(var s in m)r.push(s);m=a(m)}c.push(m,{prompt:w+
">",name:w,command_list:r})}else c.error("Command '"+w+"' Not Found")}}}(b);break;case "function":break;default:throw'Unknow object "'+String(b)+'" passed as eval';}if(t&&typeof n.login=="string"||t&&n.login)n.login=function(a){var i=1;return function(m,w,r){c.pause();g.jrpc(t,i++,a,[m,w],function(x){c.resume();!x.error&&x.result?r(x.result):r(null)},function(x,s){c.resume();c.error("&#91;AJAX&#92; Response: "+s+"\n"+x.responseText)})}}(typeof n.login=="boolean"?"login":n.login);if(j("prompt",n.prompt)){var k=
new ea({name:n.name,eval:b,prompt:n.prompt,command_list:P,greetings:n.greetings}),l=c.find(".terminal-output").next().cmd({prompt:n.prompt,history:n.history,width:"100%",keydown:L,keypress:n.keypress?function(a){return n.keypress(a,c)}:null,commands:p});c.livequery(function(){c.resize()});N.append(c);n.enabled===true?c.focus():c.disable();g(window).resize(c.resize);c.click(function(){c.focus()});c.token&&!c.token()&&c.login_name&&!c.login_name()?I():G();typeof g.fn.init.prototype.mousewheel==="function"&&
c.mousewheel(function(a,i){i>0?c.scroll(-40):c.scroll(40);return false},true)}c.data("terminal",c);return c}})(jQuery);

775
public/terminal/js/prettyprint.js Executable file
View File

@@ -0,0 +1,775 @@
/*
Copyright (c) 2009 James Padolsey. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY James Padolsey ``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 James Padolsey OR CONTRIBUTORS 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.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of James Padolsey.
AUTHOR James Padolsey (http://james.padolsey.com)
VERSION 1.03.0
UPDATED 29-10-2011
CONTRIBUTORS
David Waller
Benjamin Drucker
*/
var prettyPrint = (function(){
/* These "util" functions are not part of the core
functionality but are all necessary - mostly DOM helpers */
var util = {
el: function(type, attrs) {
/* Create new element */
var el = document.createElement(type), attr;
/*Copy to single object */
attrs = util.merge({}, attrs);
/* Add attributes to el */
if (attrs && attrs.style) {
var styles = attrs.style;
util.applyCSS( el, attrs.style );
delete attrs.style;
}
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
el[attr] = attrs[attr];
}
}
return el;
},
applyCSS: function(el, styles) {
/* Applies CSS to a single element */
for (var prop in styles) {
if (styles.hasOwnProperty(prop)) {
try{
/* Yes, IE6 SUCKS! */
el.style[prop] = styles[prop];
}catch(e){}
}
}
},
txt: function(t) {
/* Create text node */
return document.createTextNode(t);
},
row: function(cells, type, cellType) {
/* Creates new <tr> */
cellType = cellType || 'td';
/* colSpan is calculated by length of null items in array */
var colSpan = util.count(cells, null) + 1,
tr = util.el('tr'), td,
attrs = {
style: util.getStyles(cellType, type),
colSpan: colSpan,
onmouseover: function() {
var tds = this.parentNode.childNodes;
util.forEach(tds, function(cell){
if (cell.nodeName.toLowerCase() !== 'td') { return; }
util.applyCSS(cell, util.getStyles('td_hover', type));
});
},
onmouseout: function() {
var tds = this.parentNode.childNodes;
util.forEach(tds, function(cell){
if (cell.nodeName.toLowerCase() !== 'td') { return; }
util.applyCSS(cell, util.getStyles('td', type));
});
}
};
util.forEach(cells, function(cell){
if (cell === null) { return; }
/* Default cell type is <td> */
td = util.el(cellType, attrs);
if (cell.nodeType) {
/* IsDomElement */
td.appendChild(cell);
} else {
/* IsString */
td.innerHTML = util.shorten(cell.toString());
}
tr.appendChild(td);
});
return tr;
},
hRow: function(cells, type){
/* Return new <th> */
return util.row(cells, type, 'th');
},
table: function(headings, type){
headings = headings || [];
/* Creates new table: */
var attrs = {
thead: {
style:util.getStyles('thead',type)
},
tbody: {
style:util.getStyles('tbody',type)
},
table: {
style:util.getStyles('table',type)
}
},
tbl = util.el('table', attrs.table),
thead = util.el('thead', attrs.thead),
tbody = util.el('tbody', attrs.tbody);
if (headings.length) {
tbl.appendChild(thead);
thead.appendChild( util.hRow(headings, type) );
}
tbl.appendChild(tbody);
return {
/* Facade for dealing with table/tbody
Actual table node is this.node: */
node: tbl,
tbody: tbody,
thead: thead,
appendChild: function(node) {
this.tbody.appendChild(node);
},
addRow: function(cells, _type, cellType){
this.appendChild(util.row.call(util, cells, (_type || type), cellType));
return this;
}
};
},
shorten: function(str) {
var max = 40;
str = str.replace(/^\s\s*|\s\s*$|\n/g,'');
return str.length > max ? (str.substring(0, max-1) + '...') : str;
},
htmlentities: function(str) {
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
},
merge: function(target, source) {
/* Merges two (or more) objects,
giving the last one precedence */
if ( typeof target !== 'object' ) {
target = {};
}
for (var property in source) {
if ( source.hasOwnProperty(property) ) {
var sourceProperty = source[ property ];
if ( typeof sourceProperty === 'object' ) {
target[ property ] = util.merge( target[ property ], sourceProperty );
continue;
}
target[ property ] = sourceProperty;
}
}
for (var a = 2, l = arguments.length; a < l; a++) {
util.merge(target, arguments[a]);
}
return target;
},
count: function(arr, item) {
var count = 0;
for (var i = 0, l = arr.length; i< l; i++) {
if (arr[i] === item) {
count++;
}
}
return count;
},
thead: function(tbl) {
return tbl.getElementsByTagName('thead')[0];
},
forEach: function(arr, max, fn) {
if (!fn) {
fn = max;
}
/* Helper: iteration */
var len = arr.length,
index = -1;
while (++index < len) {
if(fn( arr[index], index, arr ) === false) {
break;
}
}
return true;
},
type: function(v){
try {
/* Returns type, e.g. "string", "number", "array" etc.
Note, this is only used for precise typing. */
if (v === null) { return 'null'; }
if (v === undefined) { return 'undefined'; }
var oType = Object.prototype.toString.call(v).match(/\s(.+?)\]/)[1].toLowerCase();
if (v.nodeType) {
if (v.nodeType === 1) {
return 'domelement';
}
return 'domnode';
}
if (/^(string|number|array|regexp|function|date|boolean)$/.test(oType)) {
return oType;
}
if (typeof v === 'object') {
return v.jquery && typeof v.jquery === 'string' ? 'jquery' : 'object';
}
if (v === window || v === document) {
return 'object';
}
return 'default';
} catch(e) {
return 'default';
}
},
within: function(ref) {
/* Check existence of a val within an object
RETURNS KEY */
return {
is: function(o) {
for (var i in ref) {
if (ref[i] === o) {
return i;
}
}
return '';
}
};
},
common: {
circRef: function(obj, key, settings) {
return util.expander(
'[POINTS BACK TO <strong>' + (key) + '</strong>]',
'Click to show this item anyway',
function() {
this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) );
}
);
},
depthReached: function(obj, settings) {
return util.expander(
'[DEPTH REACHED]',
'Click to show this item anyway',
function() {
try {
this.parentNode.appendChild( prettyPrintThis(obj,{maxDepth:1}) );
} catch(e) {
this.parentNode.appendChild(
util.table(['ERROR OCCURED DURING OBJECT RETRIEVAL'],'error').addRow([e.message]).node
);
}
}
);
}
},
getStyles: function(el, type) {
type = prettyPrintThis.settings.styles[type] || {};
return util.merge(
{}, prettyPrintThis.settings.styles['default'][el], type[el]
);
},
expander: function(text, title, clickFn) {
return util.el('a', {
innerHTML: util.shorten(text) + ' <b style="visibility:hidden;">[+]</b>',
title: title,
onmouseover: function() {
this.getElementsByTagName('b')[0].style.visibility = 'visible';
},
onmouseout: function() {
this.getElementsByTagName('b')[0].style.visibility = 'hidden';
},
onclick: function() {
this.style.display = 'none';
clickFn.call(this);
return false;
},
style: {
cursor: 'pointer'
}
});
},
stringify: function(obj) {
/* Bit of an ugly duckling!
- This fn returns an ATTEMPT at converting an object/array/anyType
into a string, kinda like a JSON-deParser
- This is used for when |settings.expanded === false| */
var type = util.type(obj),
str, first = true;
if ( type === 'array' ) {
str = '[';
util.forEach(obj, function(item,i){
str += (i===0?'':', ') + util.stringify(item);
});
return str + ']';
}
if (typeof obj === 'object') {
str = '{';
for (var i in obj){
if (obj.hasOwnProperty(i)) {
str += (first?'':', ') + i + ':' + util.stringify(obj[i]);
first = false;
}
}
return str + '}';
}
if (type === 'regexp') {
return '/' + obj.source + '/';
}
if (type === 'string') {
return '"' + obj.replace(/"/g,'\\"') + '"';
}
return obj.toString();
},
headerGradient: (function(){
var canvas = document.createElement('canvas');
if (!canvas.getContext) { return ''; }
var cx = canvas.getContext('2d');
canvas.height = 30;
canvas.width = 1;
var linearGrad = cx.createLinearGradient(0,0,0,30);
linearGrad.addColorStop(0,'rgba(0,0,0,0)');
linearGrad.addColorStop(1,'rgba(0,0,0,0.25)');
cx.fillStyle = linearGrad;
cx.fillRect(0,0,1,30);
var dataURL = canvas.toDataURL && canvas.toDataURL();
return 'url(' + (dataURL || '') + ')';
})()
};
// Main..
var prettyPrintThis = function(obj, options) {
/*
* obj :: Object to be printed
* options :: Options (merged with config)
*/
options = options || {};
var settings = util.merge( {}, prettyPrintThis.config, options ),
container = util.el('div'),
config = prettyPrintThis.config,
currentDepth = 0,
stack = {},
hasRunOnce = false;
/* Expose per-call settings.
Note: "config" is overwritten (where necessary) by options/"settings"
So, if you need to access/change *DEFAULT* settings then go via ".config" */
prettyPrintThis.settings = settings;
var typeDealer = {
string : function(item){
return util.txt('"' + util.shorten(item.replace(/"/g,'\\"')) + '"');
},
number : function(item) {
return util.txt(item);
},
regexp : function(item) {
var miniTable = util.table(['RegExp',null], 'regexp');
var flags = util.table();
var span = util.expander(
'/' + item.source + '/',
'Click to show more',
function() {
this.parentNode.appendChild(miniTable.node);
}
);
flags
.addRow(['g', item.global])
.addRow(['i', item.ignoreCase])
.addRow(['m', item.multiline]);
miniTable
.addRow(['source', '/' + item.source + '/'])
.addRow(['flags', flags.node])
.addRow(['lastIndex', item.lastIndex]);
return settings.expanded ? miniTable.node : span;
},
domelement : function(element, depth) {
var miniTable = util.table(['DOMElement',null], 'domelement'),
props = ['id', 'className', 'innerHTML', 'src', 'href'], elname = element.nodeName || '';
miniTable.addRow(['tag', '&lt;' + elname.toLowerCase() + '&gt;']);
util.forEach(props, function(prop){
if ( element[prop] ) {
miniTable.addRow([ prop, util.htmlentities(element[prop]) ]);
}
});
return settings.expanded ? miniTable.node : util.expander(
'DOMElement (' + elname.toLowerCase() + ')',
'Click to show more',
function() {
this.parentNode.appendChild(miniTable.node);
}
);
},
domnode : function(node){
/* Deals with all DOMNodes that aren't elements (nodeType !== 1) */
var miniTable = util.table(['DOMNode',null], 'domelement'),
data = util.htmlentities( (node.data || 'UNDEFINED').replace(/\n/g,'\\n') );
miniTable
.addRow(['nodeType', node.nodeType + ' (' + node.nodeName + ')'])
.addRow(['data', data]);
return settings.expanded ? miniTable.node : util.expander(
'DOMNode',
'Click to show more',
function() {
this.parentNode.appendChild(miniTable.node);
}
);
},
jquery : function(obj, depth, key) {
return typeDealer['array'](obj, depth, key, true);
},
object : function(obj, depth, key) {
/* Checking depth + circular refs */
/* Note, check for circular refs before depth; just makes more sense */
var stackKey = util.within(stack).is(obj);
if ( stackKey ) {
return util.common.circRef(obj, stackKey, settings);
}
stack[key||'TOP'] = obj;
if (depth === settings.maxDepth) {
return util.common.depthReached(obj, settings);
}
var table = util.table(['Object', null],'object'),
isEmpty = true;
for (var i in obj) {
if (!obj.hasOwnProperty || obj.hasOwnProperty(i)) {
var item = obj[i],
type = util.type(item);
isEmpty = false;
try {
table.addRow([i, typeDealer[ type ](item, depth+1, i)], type);
} catch(e) {
/* Security errors are thrown on certain Window/DOM properties */
if (window.console && window.console.log) {
console.log(e.message);
}
}
}
}
if (isEmpty) {
table.addRow(['<small>[empty]</small>']);
} else {
table.thead.appendChild(
util.hRow(['key','value'], 'colHeader')
);
}
var ret = (settings.expanded || hasRunOnce) ? table.node : util.expander(
util.stringify(obj),
'Click to show more',
function() {
this.parentNode.appendChild(table.node);
}
);
hasRunOnce = true;
return ret;
},
array : function(arr, depth, key, jquery) {
/* Checking depth + circular refs */
/* Note, check for circular refs before depth; just makes more sense */
var stackKey = util.within(stack).is(arr);
if ( stackKey ) {
return util.common.circRef(arr, stackKey);
}
stack[key||'TOP'] = arr;
if (depth === settings.maxDepth) {
return util.common.depthReached(arr);
}
/* Accepts a table and modifies it */
var me = jquery ? 'jQuery' : 'Array', table = util.table([me + '(' + arr.length + ')', null], jquery ? 'jquery' : me.toLowerCase()),
isEmpty = true,
count = 0;
if (jquery){
table.addRow(['selector',arr.selector]);
}
util.forEach(arr, function(item,i){
if (++count > settings.maxArray) {
table.addRow([
i + '..' + (arr.length-1),
typeDealer[ util.type(item) ]('...', depth+1, i)
]);
return false;
}
isEmpty = false;
table.addRow([i, typeDealer[ util.type(item) ](item, depth+1, i)]);
});
if (!jquery){
if (isEmpty) {
table.addRow(['<small>[empty]</small>']);
} else {
table.thead.appendChild( util.hRow(['index','value'], 'colHeader') );
}
}
return settings.expanded ? table.node : util.expander(
util.stringify(arr),
'Click to show more',
function() {
this.parentNode.appendChild(table.node);
}
);
},
'function' : function(fn, depth, key) {
/* Checking JUST circular refs */
var stackKey = util.within(stack).is(fn);
if ( stackKey ) { return util.common.circRef(fn, stackKey); }
stack[key||'TOP'] = fn;
var miniTable = util.table(['Function',null], 'function'),
argsTable = util.table(['Arguments']),
args = fn.toString().match(/\((.+?)\)/),
body = fn.toString().match(/\(.*?\)\s+?\{?([\S\s]+)/)[1].replace(/\}?$/,'');
miniTable
.addRow(['arguments', args ? args[1].replace(/[^\w_,\s]/g,'') : '<small>[none/native]</small>'])
.addRow(['body', body]);
return settings.expanded ? miniTable.node : util.expander(
'function(){...}',
'Click to see more about this function.',
function(){
this.parentNode.appendChild(miniTable.node);
}
);
},
'date' : function(date) {
var miniTable = util.table(['Date',null], 'date'),
sDate = date.toString().split(/\s/);
/* TODO: Make this work well in IE! */
miniTable
.addRow(['Time', sDate[4]])
.addRow(['Date', sDate.slice(0,4).join('-')]);
return settings.expanded ? miniTable.node : util.expander(
'Date (timestamp): ' + (+date),
'Click to see a little more info about this date',
function() {
this.parentNode.appendChild(miniTable.node);
}
);
},
'boolean' : function(bool) {
return util.txt( bool.toString().toUpperCase() );
},
'undefined' : function() {
return util.txt('UNDEFINED');
},
'null' : function() {
return util.txt('NULL');
},
'default' : function() {
/* When a type cannot be found */
return util.txt('prettyPrint: TypeNotFound Error');
}
};
container.appendChild( typeDealer[ (settings.forceObject) ? 'object' : util.type(obj) ](obj, currentDepth) );
return container;
};
/* Configuration */
/* All items can be overwridden by passing an
"options" object when calling prettyPrint */
prettyPrintThis.config = {
/* Try setting this to false to save space */
expanded: true,
forceObject: false,
maxDepth: 3,
maxArray: -1, // default is unlimited
styles: {
array: {
th: {
backgroundColor: '#6DBD2A',
color: 'white'
}
},
'function': {
th: {
backgroundColor: '#D82525'
}
},
regexp: {
th: {
backgroundColor: '#E2F3FB',
color: '#000'
}
},
object: {
th: {
backgroundColor: '#1F96CF'
}
},
jquery : {
th: {
backgroundColor: '#FBF315'
}
},
error: {
th: {
backgroundColor: 'red',
color: 'yellow'
}
},
domelement: {
th: {
backgroundColor: '#F3801E'
}
},
date: {
th: {
backgroundColor: '#A725D8'
}
},
colHeader: {
th: {
backgroundColor: '#EEE',
color: '#000',
textTransform: 'uppercase'
}
},
'default': {
table: {
borderCollapse: 'collapse',
width: '100%'
},
td: {
padding: '5px',
fontSize: '12px',
backgroundColor: '#FFF',
color: '#222',
border: '1px solid #000',
verticalAlign: 'top',
fontFamily: '"Consolas","Lucida Console",Courier,mono',
whiteSpace: 'nowrap'
},
td_hover: {
/* Styles defined here will apply to all tr:hover > td,
- Be aware that "inheritable" properties (e.g. fontWeight) WILL BE INHERITED */
},
th: {
padding: '5px',
fontSize: '12px',
backgroundColor: '#222',
color: '#EEE',
textAlign: 'left',
border: '1px solid #000',
verticalAlign: 'top',
fontFamily: '"Consolas","Lucida Console",Courier,mono',
backgroundImage: util.headerGradient,
backgroundRepeat: 'repeat-x'
}
}
}
};
return prettyPrintThis;
})();