Split util into two file:

- util.js that contains essential functions
 - webutils.js that contains the GUI utility function.js

this helps to include noVNC in other project, especially Cappuccino Application
This commit is contained in:
Antoine Mercadal 2010-09-29 20:09:09 +02:00
parent a679a97d1b
commit c3a7f53253
8 changed files with 236 additions and 229 deletions

View File

@ -10,7 +10,7 @@
/*jslint browser: true, white: false, bitwise: false */
/*global window, Util, Base64 */
function Canvas(conf) {
var Canvas = function(conf) {
conf = conf || {}; // Configuration
var that = {}, // Public API interface
@ -38,7 +38,6 @@ function cdef(v, type, defval, desc) {
// Capability settings, default can be overridden
cdef('prefer_js', 'raw', null, 'Prefer Javascript over canvas methods');
cdef('cursor_uri', 'raw', null, 'Can we render cursor using data URI');
cdef('target', 'dom', null, 'Canvas element for VNC viewport');
cdef('focusContainer', 'dom', document, 'DOM element that traps keyboard input');
cdef('true_color', 'bool', true, 'Request true color pixel data');
@ -46,8 +45,6 @@ cdef('focused', 'bool', true, 'Capture and send key strokes');
cdef('colourMap', 'raw', [], 'Colour map array (not true color)');
cdef('scale', 'float', 1, 'VNC viewport scale factor');
cdef('render_mode', 'str', '', 'Canvas rendering mode (read-only)');
// Override some specific getters/setters
that.set_prefer_js = function(val) {
if (val && c_forceCanvas) {
@ -74,8 +71,6 @@ that.set_colourMap = function(val, idx) {
}
};
that.set_render_mode = function () { throw("render_mode is read-only"); };
// Add some other getters/setters
that.get_width = function() {
return c_width;
@ -84,8 +79,6 @@ that.get_height = function() {
return c_height;
};
//
// Private functions
//
@ -139,12 +132,9 @@ function constructor() {
if (ctx.createImageData) {
// If it's there, it's faster
Util.Info("Using Canvas createImageData");
conf.render_mode = "createImageData rendering";
that.imageData = that.imageDataCreate;
} else if (ctx.getImageData) {
// I think this is mostly just Opera
Util.Info("Using Canvas getImageData");
conf.render_mode = "getImageData rendering";
that.imageData = that.imageDataGet;
}
Util.Info("Prefering javascript operations");
@ -155,7 +145,6 @@ function constructor() {
that.cmapImage = that.cmapImageData;
} else {
Util.Warn("Canvas lacks imageData, using fillRect (slow)");
conf.render_mode = "fillRect rendering (slow)";
c_forceCanvas = true;
conf.prefer_js = false;
that.rgbxImage = that.rgbxImageFill;
@ -418,30 +407,44 @@ that.start = function(keyPressFunc, mouseButtonFunc, mouseMoveFunc) {
that.rescale = function(factor) {
var c, tp, x, y,
properties = ['transform', 'WebkitTransform', 'MozTransform', null];
properties = ['transform', 'WebkitTransform', 'MozTransform', 'oTransform', null],
origin = ['transformOrigin', 'WebkitTransformOrigin', 'MozTransformOrigin', 'oTransformOrigin', null];
if (conf.scale === factor) {
return;
}
c = conf.target;
tp = properties.shift();
while (tp) {
if (typeof c.style[tp] !== 'undefined') {
conf.scale = factor;
x = c.width - c.width * factor;
y = c.height - c.height * factor;
//tp = properties.shift();
if (typeof(c.style.zoom) != "undefined") {
c.style.zoom = conf.scale;
return
}
while (tp = properties.shift()) {
if (typeof c.style[tp] != 'undefined') {
break;
}
tp = properties.shift();
}
while (tpo = origin.shift()) {
if (typeof c.style[tpo] != 'undefined') {
break;
}
}
if (tp === null) {
Util.Debug("No scaling support");
return;
}
if (conf.scale === factor) {
//Util.Debug("Canvas already scaled to '" + factor + "'");
return;
}
conf.scale = factor;
x = c.width - c.width * factor;
y = c.height - c.height * factor;
c.style[tp] = "scale(" + conf.scale + ") translate(-" + x + "px, -" + y + "px)";
c.style[tpo] = "top left";
c.style[tp] = "scale(" + conf.scale + ")";
};
that.resize = function(width, height, true_color) {

View File

@ -56,8 +56,8 @@ load: function(target) {
// Stylesheet selection dropdown
html += ' <li><select id="VNC_stylesheet" name="vncStyle">';
html += ' <option value="default">default</option>';
sheet = Util.selectStylesheet();
sheets = Util.getStylesheets();
sheet = WebUtil.selectStylesheet();
sheets = WebUtil.getStylesheets();
for (i = 0; i < sheets.length; i += 1) {
html += '<option value="' + sheets[i].title + '">' + sheets[i].title + '</option>';
}
@ -102,11 +102,11 @@ load: function(target) {
// Settings with immediate effects
DC.initSetting('logging', 'warn');
Util.init_logging(DC.getSetting('logging'));
WebUtil.init_logging(DC.getSetting('logging'));
DC.initSetting('stylesheet', 'default');
Util.selectStylesheet(null); // call twice to get around webkit bug
Util.selectStylesheet(DC.getSetting('stylesheet'));
WebUtil.selectStylesheet(null); // call twice to get around webkit bug
WebUtil.selectStylesheet(DC.getSetting('stylesheet'));
/* Populate the controls if defaults are provided in the URL */
DC.initSetting('host', '');
@ -134,7 +134,7 @@ load: function(target) {
// Read form control compatible setting from cookie
getSetting: function(name) {
var val, ctrl = $('VNC_' + name);
val = Util.readCookie(name);
val = WebUtil.readCookie(name);
if (ctrl.type === 'checkbox') {
if (val.toLowerCase() in {'0':1, 'no':1, 'false':1}) {
val = false;
@ -151,7 +151,7 @@ updateSetting: function(name, value) {
var i, ctrl = $('VNC_' + name);
// Save the cookie for this session
if (typeof value !== 'undefined') {
Util.createCookie(name, value);
WebUtil.createCookie(name, value);
}
// Update the settings control
@ -180,7 +180,7 @@ saveSetting: function(name) {
} else {
val = ctrl.value;
}
Util.createCookie(name, val);
WebUtil.createCookie(name, val);
//Util.Debug("Setting saved '" + name + "=" + val + "'");
return val;
},
@ -190,9 +190,9 @@ initSetting: function(name, defVal) {
var val;
// Check Query string followed by cookie
val = Util.getQueryVar(name);
val = WebUtil.getQueryVar(name);
if (val === null) {
val = Util.readCookie(name, defVal);
val = WebUtil.readCookie(name, defVal);
}
DefaultControls.updateSetting(name, val);
//Util.Debug("Setting '" + name + "' initialized to '" + val + "'");
@ -267,8 +267,8 @@ settingsApply: function() {
DC.saveSetting('logging');
// Settings with immediate (non-connected related) effect
Util.selectStylesheet(DC.getSetting('stylesheet'));
Util.init_logging(DC.getSetting('logging'));
WebUtil.selectStylesheet(DC.getSetting('stylesheet'));
WebUtil.init_logging(DC.getSetting('logging'));
//Util.Debug("<< settingsApply");
},

View File

@ -7,18 +7,17 @@
*/
"use strict";
/*jslint white: false, browser: true, bitwise: false, plusplus: false */
/*jslint white: false, browser: true, bitwise: false */
/*global window, WebSocket, Util, Canvas, VNC_native_ws, Base64, DES */
function RFB(conf) {
var RFB = function(conf) {
conf = conf || {}; // Configuration
var that = {}, // Public API interface
// Pre-declare private functions used before definitions (jslint)
init_vars, updateState, init_msg, normal_msg, recv_message,
framebufferUpdate, print_stats,
framebufferUpdate,
pixelFormat, clientEncodings, fbUpdateRequest,
keyEvent, pointerEvent, clientCutText,
@ -61,7 +60,6 @@ var that = {}, // Public API interface
encHandlers = {},
encNames = {},
encStats = {}, // [rectCnt, rectCntTot]
ws = null, // Web Socket object
canvas = null, // Canvas object
@ -210,14 +208,13 @@ function rQshiftBytes(len) {
// Create the public API interface and initialize
function constructor() {
var i, rmode;
var i;
Util.Debug(">> RFB.constructor");
// Create lookup tables based encoding number
for (i=0; i < encodings.length; i+=1) {
encHandlers[encodings[i][1]] = encHandlers[encodings[i][0]];
encNames[encodings[i][1]] = encodings[i][0];
encStats[encodings[i][1]] = [0, 0];
}
// Initialize canvas
try {
@ -227,25 +224,15 @@ function constructor() {
Util.Error("Canvas exception: " + exc);
updateState('fatal', "No working Canvas");
}
rmode = canvas.get_render_mode();
init_vars();
/* Check web-socket-js if no builtin WebSocket support */
if (VNC_native_ws) {
Util.Info("Using native WebSockets");
updateState('loaded', 'noVNC ready: native WebSockets, ' + rmode);
updateState('loaded', 'noVNC ready (using native WebSockets)');
} else {
Util.Warn("Using web-socket-js flash bridge");
if ((! Util.Flash) ||
(Util.Flash.version < 9)) {
updateState('fatal', "WebSockets or Adobe Flash is required");
} else if (document.location.href.substr(0, 7) === "file://") {
updateState('fatal',
"'file://' URL is incompatible with Adobe Flash");
} else {
updateState('loaded', 'noVNC ready: WebSockets emulation, ' + rmode);
}
throw new Error("This version doesn't support WebSocket of other type than native websocket");
}
Util.Debug("<< RFB.constructor");
@ -311,32 +298,6 @@ init_vars = function() {
FBU.imgQ = []; // TIGHT_PNG image queue
mouse_buttonMask = 0;
mouse_arr = [];
// Clear the per connection encoding stats
for (i=0; i < encodings.length; i+=1) {
encStats[encodings[i][1]][0] = 0;
}
};
// Print statistics
print_stats = function() {
var i, encName, s;
Util.Info("Encoding stats for this connection:");
for (i=0; i < encodings.length; i+=1) {
s = encStats[encodings[i][1]];
if ((s[0] + s[1]) > 0) {
Util.Info(" " + encodings[i][0] + ": " +
s[0] + " rects");
}
}
Util.Info("Encoding stats since page load:");
for (i=0; i < encodings.length; i+=1) {
s = encStats[encodings[i][1]];
if ((s[0] + s[1]) > 0) {
Util.Info(" " + encodings[i][0] + ": "
+ s[1] + " rects");
}
}
};
//
@ -467,9 +428,6 @@ updateState = function(state, statusMsg) {
updateState('failed', "Disconnect timeout");
}, conf.disconnectTimeout * 1000);
}
print_stats();
// WebSocket.onclose transitions to 'disconnected'
break;
@ -974,7 +932,7 @@ normal_msg = function() {
};
framebufferUpdate = function() {
var now, hdr, fbu_rt_diff, ret = true, ctx;
var now, hdr, fbu_rt_diff, last_bytes, last_rects, ret = true;
if (FBU.rects === 0) {
//Util.Debug("New FBU: rQ.slice(0,20): " + rQ.slice(0,20));
@ -1041,17 +999,15 @@ framebufferUpdate = function() {
}
timing.last_fbu = (new Date()).getTime();
last_bytes = rQlen();
last_rects = FBU.rects;
// false ret means need more data
ret = encHandlers[FBU.encoding]();
now = (new Date()).getTime();
timing.cur_fbu += (now - timing.last_fbu);
if (ret) {
encStats[FBU.encoding][0] += 1;
encStats[FBU.encoding][1] += 1;
}
if (FBU.rects === 0) {
if (((FBU.width === fb_width) &&
(FBU.height === fb_height)) ||
@ -1090,7 +1046,7 @@ framebufferUpdate = function() {
//
encHandlers.RAW = function display_raw() {
//Util.Debug(">> display_raw (" + rQlen() + " bytes)");
//Util.Debug(">> display_raw");
var cur_y, cur_height;
@ -1116,7 +1072,6 @@ encHandlers.RAW = function display_raw() {
FBU.rects -= 1;
FBU.bytes = 0;
}
//Util.Debug("<< display_raw (" + rQlen() + " bytes)");
return true;
};
@ -1620,6 +1575,12 @@ that.disconnect = function() {
//Util.Debug("<< disconnect");
};
that.force_disconnect = function() {
//Util.Debug(">> disconnect");
updateState('disconnected', 'Disconnected');
//Util.Debug("<< disconnect");
};
that.sendPassword = function(passwd) {
rfb_password = passwd;
rfb_state = "Authentication";

View File

@ -8,28 +8,12 @@
"use strict";
/*jslint bitwise: false, white: false */
/*global window, console, document, navigator, ActiveXObject*/
/*global window, document, navigator, ActiveXObject*/
// Globals defined here
var Util = {}, $;
var Util = {};
/*
* Simple DOM selector by ID
*/
if (!window.$) {
$ = function (id) {
if (document.getElementById) {
return document.getElementById(id);
} else if (document.all) {
return document.all[id];
} else if (document.layers) {
return document.layers[id];
}
return undefined;
};
}
/*
* Make arrays quack
*/
@ -49,22 +33,16 @@ Array.prototype.push32 = function (num) {
(num ) & 0xFF );
};
/*
* ------------------------------------------------------
* Namespaced in Util
* ------------------------------------------------------
*/
/*
* Logging/debug routines
*/
Util._log_level = 'warn';
Util.init_logging = function (level) {
if (typeof level === 'undefined') {
Util._log_level = (document.location.href.match(
/logging=([A-Za-z0-9\._\-]*)/) ||
['', Util._log_level])[1];
if (typeof level === 'undefined' || !level) {
level = Util._log_level;
} else {
Util._log_level = level;
@ -85,50 +63,30 @@ Util.init_logging = function (level) {
Util.Debug = Util.Info = Util.Warn = Util.Error = function (msg) {};
switch (level) {
case 'debug': Util.Debug = function (msg) { console.log(msg); };
case 'info': Util.Info = function (msg) { console.log(msg); };
case 'warn': Util.Warn = function (msg) { console.warn(msg); };
case 'error': Util.Error = function (msg) { console.error(msg); };
case 'debug':
Util.Debug = function (msg) { console.log(msg); };
break;
case 'info':
Util.Info = function (msg) { console.log(msg); };
break;
case 'warn':
Util.Warn = function (msg) { console.warn(msg); };
break;
case 'error':
Util.Error = function (msg) { console.error(msg); };
break;
case 'none':
break;
default:
throw("invalid logging type '" + level + "'");
}
};
Util.get_logging = function () {
return Util._log_level;
}
// Initialize logging level
Util.init_logging();
return Util._log_level;
}
Util.dirObj = function (obj, depth, parent) {
var i, msg = "", val = "";
if (! depth) { depth=2; }
if (! parent) { parent= ""; }
// Print the properties of the passed-in object
for (i in obj) {
if ((depth > 1) && (typeof obj[i] === "object")) {
// Recurse attributes that are objects
msg += Util.dirObj(obj[i], depth-1, parent + "." + i);
} else {
//val = new String(obj[i]).replace("\n", " ");
val = obj[i].toString().replace("\n", " ");
if (val.length > 30) {
val = val.substr(0,30) + "...";
}
msg += parent + "." + i + ": " + val + "\n";
}
}
return msg;
};
// Read a query string variable
Util.getQueryVar = function(name, defVal) {
var re = new RegExp('[?][^#]*' + name + '=([^&#]*)');
if (typeof defVal === 'undefined') { defVal = null; }
return (document.location.href.match(re) || ['',defVal])[1];
};
// Set defaults for Crockford style function namespaces
Util.conf_default = function(cfg, api, v, type, defval, desc) {
@ -240,6 +198,7 @@ Util.stopEvent = function(e) {
};
// Set browser engine versions. Based on mootools.
Util.Features = {xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector)};
@ -269,70 +228,9 @@ Util.Flash = (function(){
}
version = v.match(/\d+/g);
return {version: parseInt(version[0] || 0 + '.' + version[1], 10) || 0, build: parseInt(version[2], 10) || 0};
}());
}());
/*
* Cookie handling. Dervied from: http://www.quirksmode.org/js/cookies.html
*/
// No days means only for this browser session
Util.createCookie = function(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
};
Util.readCookie = function(name, defaultValue) {
var i, c, nameEQ = name + "=", ca = document.cookie.split(';');
for(i=0; i < ca.length; i += 1) {
c = ca[i];
while (c.charAt(0) === ' ') { c = c.substring(1,c.length); }
if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); }
}
return (typeof defaultValue !== 'undefined') ? defaultValue : null;
};
Util.eraseCookie = function(name) {
Util.createCookie(name,"",-1);
};
/*
* Alternate stylesheet selection
*/
Util.getStylesheets = function() { var i, links, sheets = [];
links = document.getElementsByTagName("link");
for (i = 0; i < links.length; i += 1) {
if (links[i].title &&
links[i].rel.toUpperCase().indexOf("STYLESHEET") > -1) {
sheets.push(links[i]);
}
}
return sheets;
};
// No sheet means try and use value from cookie, null sheet used to
// clear all alternates.
Util.selectStylesheet = function(sheet) {
var i, link, sheets = Util.getStylesheets();
if (typeof sheet === 'undefined') {
sheet = 'default';
}
for (i=0; i < sheets.length; i += 1) {
link = sheets[i];
if (link.title === sheet) {
Util.Debug("Using stylesheet " + sheet);
link.disabled = false;
} else {
//Util.Debug("Skipping stylesheet " + link.title);
link.disabled = true;
}
}
return sheet;
};

View File

@ -31,6 +31,7 @@ function get_VNC_uri_prefix() {
// "firebug-lite-compressed.js'><\/script>";
extra += start + "util.js" + end;
extra += start + "webutil.js" + end;
extra += start + "base64.js" + end;
extra += start + "des.js" + end;
extra += start + "canvas.js" + end;

144
include/webutil.js Normal file
View File

@ -0,0 +1,144 @@
/*
* noVNC: HTML5 VNC client
* Copyright (C) 2010 Joel Martin
* Licensed under LGPL-3 (see LICENSE.txt)
*
* See README.md for usage and integration instructions.
*/
"use strict";
/*jslint bitwise: false, white: false */
/*global window, console, document, navigator, ActiveXObject*/
// Globals defined here
var WebUtil = {}, $;
/*
* Simple DOM selector by ID
*/
if (!window.$) {
$ = function (id) {
if (document.getElementById) {
return document.getElementById(id);
} else if (document.all) {
return document.all[id];
} else if (document.layers) {
return document.layers[id];
}
return undefined;
};
}
/*
* ------------------------------------------------------
* Namespaced in WebUtil
* ------------------------------------------------------
*/
// init log level reading the logging HTTP param
WebUtil.init_logging = function() {
Util._log_level = (document.location.href.match(
/logging=([A-Za-z0-9\._\-]*)/) ||
['', Util._log_level])[1];
Util.init_logging()
}
WebUtil.init_logging();
WebUtil.dirObj = function (obj, depth, parent) {
var i, msg = "", val = "";
if (! depth) { depth=2; }
if (! parent) { parent= ""; }
// Print the properties of the passed-in object
for (i in obj) {
if ((depth > 1) && (typeof obj[i] === "object")) {
// Recurse attributes that are objects
msg += WebUtil.dirObj(obj[i], depth-1, parent + "." + i);
} else {
//val = new String(obj[i]).replace("\n", " ");
val = obj[i].toString().replace("\n", " ");
if (val.length > 30) {
val = val.substr(0,30) + "...";
}
msg += parent + "." + i + ": " + val + "\n";
}
}
return msg;
};
// Read a query string variable
WebUtil.getQueryVar = function(name, defVal) {
var re = new RegExp('[?][^#]*' + name + '=([^&#]*)');
if (typeof defVal === 'undefined') { defVal = null; }
return (document.location.href.match(re) || ['',defVal])[1];
};
/*
* Cookie handling. Dervied from: http://www.quirksmode.org/js/cookies.html
*/
// No days means only for this browser session
WebUtil.createCookie = function(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
};
WebUtil.readCookie = function(name, defaultValue) {
var i, c, nameEQ = name + "=", ca = document.cookie.split(';');
for(i=0; i < ca.length; i += 1) {
c = ca[i];
while (c.charAt(0) === ' ') { c = c.substring(1,c.length); }
if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); }
}
return (typeof defaultValue !== 'undefined') ? defaultValue : null;
};
WebUtil.eraseCookie = function(name) {
WebUtil.createCookie(name,"",-1);
};
/*
* Alternate stylesheet selection
*/
WebUtil.getStylesheets = function() { var i, links, sheets = [];
links = document.getElementsByTagName("link");
for (i = 0; i < links.length; i += 1) {
if (links[i].title &&
links[i].rel.toUpperCase().indexOf("STYLESHEET") > -1) {
sheets.push(links[i]);
}
}
return sheets;
};
// No sheet means try and use value from cookie, null sheet used to
// clear all alternates.
WebUtil.selectStylesheet = function(sheet) {
var i, link, sheets = WebUtil.getStylesheets();
if (typeof sheet === 'undefined') {
sheet = 'default';
}
for (i=0; i < sheets.length; i += 1) {
link = sheets[i];
if (link.title === sheet) {
Util.Debug("Using stylesheet " + sheet);
link.disabled = false;
} else {
//Util.Debug("Skipping stylesheet " + link.title);
link.disabled = true;
}
}
return sheet;
};

View File

@ -50,7 +50,7 @@
cell.scrollTop = cell.scrollHeight;
}
fname = Util.getQueryVar('data', null);
fname = WebUtil.getQueryVar('data', null);
if (fname) {
message("Loading " + fname);
@ -109,9 +109,9 @@
}
window.onload = function() {
iterations = Util.getQueryVar('iterations', 3);
iterations = WebUtil.getQueryVar('iterations', 3);
$('iterations').value = iterations;
mode = Util.getQueryVar('mode', 3);
mode = WebUtil.getQueryVar('mode', 3);
if (mode === 'realtime') {
$('mode2').checked = true;
} else {

View File

@ -91,18 +91,18 @@
$('sendCtrlAltDelButton').onclick = sendCtrlAltDel;
host = Util.getQueryVar('host', null);
port = Util.getQueryVar('port', null);
password = Util.getQueryVar('password', '');
host = WebUtil.getQueryVar('host', null);
port = WebUtil.getQueryVar('port', null);
password = WebUtil.getQueryVar('password', '');
if ((!host) || (!port)) {
updateState('failed',
"Must specify host and port in URL");
return;
}
rfb = new RFB({'encrypt': Util.getQueryVar('encrypt', false),
'true_color': Util.getQueryVar('true_color', true),
'local_cursor': Util.getQueryVar('cursor', true),
rfb = new RFB({'encrypt': WebUtil.getQueryVar('encrypt', false),
'true_color': WebUtil.getQueryVar('true_color', true),
'local_cursor': WebUtil.getQueryVar('cursor', true),
'updateState': updateState});
rfb.connect(host, port, password);
};