Cleanup: UI code

File: ui.js
Tests Added: False

Changes:
- Fix JSHint errors
- add some curly braces to improve clarity
- move variable declarations to relevant locations instead of at the top
  of methods
This commit is contained in:
Solly Ross 2014-06-21 23:26:28 -04:00
parent b1dee94788
commit bbbf42bb5a
1 changed files with 920 additions and 944 deletions

View File

@ -7,54 +7,57 @@
* See README.md for usage and integration instructions.
*/
"use strict";
/*jslint white: false, browser: true */
/*global window, $D, Util, WebUtil, RFB, Display */
/* jslint white: false, browser: true */
/* global window, $D, Util, WebUtil, RFB, Display */
// Load supporting scripts
window.onscriptsload = function () { UI.load(); };
window.onload = function () { UI.keyboardinputReset(); };
Util.load_scripts(["webutil.js", "base64.js", "websock.js", "des.js",
var UI;
(function () {
"use strict";
// Load supporting scripts
window.onscriptsload = function () { UI.load(); };
window.onload = function () { UI.keyboardinputReset(); };
Util.load_scripts(["webutil.js", "base64.js", "websock.js", "des.js",
"keysymdef.js", "keyboard.js", "input.js", "display.js",
"jsunzip.js", "rfb.js", "keysym.js"]);
var UI = {
var UI = {
rfb_state : 'loaded',
settingsOpen : false,
connSettingsOpen : false,
popupStatusOpen : false,
clipboardOpen: false,
keyboardVisible: false,
hideKeyboardTimeout: null,
lastKeyboardinput: null,
defaultKeyboardinputLen: 100,
extraKeysVisible: false,
ctrlOn: false,
altOn: false,
isTouchDevice: false,
rfb_state : 'loaded',
settingsOpen : false,
connSettingsOpen : false,
popupStatusOpen : false,
clipboardOpen: false,
keyboardVisible: false,
hideKeyboardTimeout: null,
lastKeyboardinput: null,
defaultKeyboardinputLen: 100,
extraKeysVisible: false,
ctrlOn: false,
altOn: false,
isTouchDevice: false,
// Setup rfb object, load settings from browser storage, then call
// UI.init to setup the UI/menus
load: function (callback) {
// Setup rfb object, load settings from browser storage, then call
// UI.init to setup the UI/menus
load: function (callback) {
WebUtil.initSettings(UI.start, callback);
},
// Render default UI and initialize settings menu
start: function(callback) {
var html = '', i, sheet, sheets, llevels, port, autoconnect;
},
// Render default UI and initialize settings menu
start: function(callback) {
UI.isTouchDevice = 'ontouchstart' in document.documentElement;
// Stylesheet selection dropdown
sheet = WebUtil.selectStylesheet();
sheets = WebUtil.getStylesheets();
var sheet = WebUtil.selectStylesheet();
var sheets = WebUtil.getStylesheets();
var i;
for (i = 0; i < sheets.length; i += 1) {
UI.addOption($D('noVNC_stylesheet'),sheets[i].title, sheets[i].title);
}
// Logging selection dropdown
llevels = ['error', 'warn', 'info', 'debug'];
var llevels = ['error', 'warn', 'info', 'debug'];
for (i = 0; i < llevels.length; i += 1) {
UI.addOption($D('noVNC_logging'),llevels[i], llevels[i]);
}
@ -70,7 +73,7 @@ start: function(callback) {
// if port == 80 (or 443) then it won't be present and should be
// set manually
port = window.location.port;
var port = window.location.port;
if (!port) {
if (window.location.protocol.substring(0,5) == 'https') {
port = 443;
@ -92,13 +95,13 @@ start: function(callback) {
UI.initSetting('path', 'websockify');
UI.initSetting('repeaterID', '');
UI.rfb = RFB({'target': $D('noVNC_canvas'),
UI.rfb = new RFB({'target': $D('noVNC_canvas'),
'onUpdateState': UI.updateState,
'onXvpInit': UI.updateXvpVisualState,
'onClipboard': UI.clipReceive,
'onDesktopName': UI.updateDocumentTitle});
autoconnect = WebUtil.getQueryVar('autoconnect', false);
var autoconnect = WebUtil.getQueryVar('autoconnect', false);
if (autoconnect === 'true' || autoconnect == '1') {
autoconnect = true;
UI.connect();
@ -108,14 +111,6 @@ start: function(callback) {
UI.updateVisualState();
// Unfocus clipboard when over the VNC area
//$D('VNC_screen').onmousemove = function () {
// var keyboard = UI.rfb.get_keyboard();
// if ((! keyboard) || (! keyboard.get_focused())) {
// $D('VNC_clipboard_text').blur();
// }
// };
// Show mouse selector buttons on touch screen devices
if (UI.isTouchDevice) {
// Show mobile buttons
@ -167,9 +162,9 @@ start: function(callback) {
if (typeof callback === "function") {
callback(UI.rfb);
}
},
},
addMouseHandlers: function() {
addMouseHandlers: function() {
// Setup interface handlers that can't be inline
$D("noVNC_view_drag_button").onclick = UI.setViewDrag;
$D("noVNC_mouse_button0").onclick = function () { UI.setMouseButton(1); };
@ -210,12 +205,12 @@ addMouseHandlers: function() {
$D("noVNC_apply").onclick = UI.settingsApply;
$D("noVNC_connect_button").onclick = UI.connect;
},
},
// Read form control compatible setting from cookie
getSetting: function(name) {
var val, ctrl = $D('noVNC_' + name);
val = WebUtil.readSetting(name);
// Read form control compatible setting from cookie
getSetting: function(name) {
var ctrl = $D('noVNC_' + name);
var val = WebUtil.readSetting(name);
if (val !== null && ctrl.type === 'checkbox') {
if (val.toString().toLowerCase() in {'0':1, 'no':1, 'false':1}) {
val = false;
@ -224,13 +219,12 @@ getSetting: function(name) {
}
}
return val;
},
},
// Update cookie and form control setting. If value is not set, then
// updates from control to current cookie setting.
updateSetting: function(name, value) {
// Update cookie and form control setting. If value is not set, then
// updates from control to current cookie setting.
updateSetting: function(name, value) {
var i, ctrl = $D('noVNC_' + name);
// Save the cookie for this session
if (typeof value !== 'undefined') {
WebUtil.writeSetting(name, value);
@ -239,11 +233,12 @@ updateSetting: function(name, value) {
// Update the settings control
value = UI.getSetting(name);
var ctrl = $D('noVNC_' + name);
if (ctrl.type === 'checkbox') {
ctrl.checked = value;
} else if (typeof ctrl.options !== 'undefined') {
for (i = 0; i < ctrl.options.length; i += 1) {
for (var i = 0; i < ctrl.options.length; i += 1) {
if (ctrl.options[i].value === value) {
ctrl.selectedIndex = i;
break;
@ -257,10 +252,10 @@ updateSetting: function(name, value) {
}
ctrl.value = value;
}
},
},
// Save control setting to cookie
saveSetting: function(name) {
// Save control setting to cookie
saveSetting: function(name) {
var val, ctrl = $D('noVNC_' + name);
if (ctrl.type === 'checkbox') {
val = ctrl.checked;
@ -272,31 +267,28 @@ saveSetting: function(name) {
WebUtil.writeSetting(name, val);
//Util.Debug("Setting saved '" + name + "=" + val + "'");
return val;
},
// Initial page load read/initialization of settings
initSetting: function(name, defVal) {
var val;
},
// Initial page load read/initialization of settings
initSetting: function(name, defVal) {
// Check Query string followed by cookie
val = WebUtil.getQueryVar(name);
var val = WebUtil.getQueryVar(name);
if (val === null) {
val = WebUtil.readSetting(name, defVal);
}
UI.updateSetting(name, val);
//Util.Debug("Setting '" + name + "' initialized to '" + val + "'");
return val;
},
},
// Force a setting to be a certain value
forceSetting: function(name, val) {
// Force a setting to be a certain value
forceSetting: function(name, val) {
UI.updateSetting(name, val);
return val;
},
},
// Show the popup status panel
togglePopupStatusPanel: function() {
// Show the popup status panel
togglePopupStatusPanel: function() {
var psp = $D('noVNC_popup_status_panel');
if (UI.popupStatusOpen === true) {
psp.style.display = "none";
@ -308,10 +300,10 @@ togglePopupStatusPanel: function() {
parseInt(window.getComputedStyle(psp, false).width)/2 -30 + "px";
UI.popupStatusOpen = true;
}
},
},
// Show the XVP panel
toggleXvpPanel: function() {
// Show the XVP panel
toggleXvpPanel: function() {
// Close the description panel
$D('noVNC_description').style.display = "none";
// Close settings if open
@ -341,10 +333,10 @@ toggleXvpPanel: function() {
$D('xvpButton').className = "noVNC_status_button_selected";
UI.xvpOpen = true;
}
},
},
// Show the clipboard panel
toggleClipboardPanel: function() {
// Show the clipboard panel
toggleClipboardPanel: function() {
// Close the description panel
$D('noVNC_description').style.display = "none";
// Close settings if open
@ -374,10 +366,10 @@ toggleClipboardPanel: function() {
$D('clipboardButton').className = "noVNC_status_button_selected";
UI.clipboardOpen = true;
}
},
},
// Show the connection settings panel/menu
toggleConnectPanel: function() {
// Show the connection settings panel/menu
toggleConnectPanel: function() {
// Close the description panel
$D('noVNC_description').style.display = "none";
// Close connection settings if open
@ -413,12 +405,12 @@ toggleConnectPanel: function() {
UI.connSettingsOpen = true;
$D('noVNC_host').focus();
}
},
},
// Toggle the settings menu:
// On open, settings are refreshed from saved cookies.
// On close, settings are applied
toggleSettingsPanel: function() {
// Toggle the settings menu:
// On open, settings are refreshed from saved cookies.
// On close, settings are applied
toggleSettingsPanel: function() {
// Close the description panel
$D('noVNC_description').style.display = "none";
if (UI.settingsOpen) {
@ -443,10 +435,10 @@ toggleSettingsPanel: function() {
UI.openSettingsMenu();
}
},
},
// Open menu
openSettingsMenu: function() {
// Open menu
openSettingsMenu: function() {
// Close the description panel
$D('noVNC_description').style.display = "none";
// Close clipboard panel if open
@ -468,17 +460,17 @@ openSettingsMenu: function() {
$D('noVNC_settings').style.display = "block";
$D('settingsButton').className = "noVNC_status_button_selected";
UI.settingsOpen = true;
},
},
// Close menu (without applying settings)
closeSettingsMenu: function() {
// Close menu (without applying settings)
closeSettingsMenu: function() {
$D('noVNC_settings').style.display = "none";
$D('settingsButton').className = "noVNC_status_button";
UI.settingsOpen = false;
},
},
// Save/apply settings when 'Apply' button is pressed
settingsApply: function() {
// Save/apply settings when 'Apply' button is pressed
settingsApply: function() {
//Util.Debug(">> settingsApply");
UI.saveSetting('encrypt');
UI.saveSetting('true_color');
@ -499,11 +491,11 @@ settingsApply: function() {
UI.setViewClip();
UI.setViewDrag(UI.rfb.get_viewportDrag());
//Util.Debug("<< settingsApply");
},
},
setPassword: function() {
setPassword: function() {
UI.rfb.sendPassword($D('noVNC_password').value);
//Reset connect button.
$D('noVNC_connect_button').value = "Connect";
@ -511,27 +503,25 @@ setPassword: function() {
//Hide connection panel.
UI.toggleConnectPanel();
return false;
},
},
sendCtrlAltDel: function() {
sendCtrlAltDel: function() {
UI.rfb.sendCtrlAltDel();
},
},
xvpShutdown: function() {
xvpShutdown: function() {
UI.rfb.xvpShutdown();
},
},
xvpReboot: function() {
xvpReboot: function() {
UI.rfb.xvpReboot();
},
},
xvpReset: function() {
xvpReset: function() {
UI.rfb.xvpReset();
},
setMouseButton: function(num) {
var b, blist = [0, 1,2,4], button;
},
setMouseButton: function(num) {
if (typeof num === 'undefined') {
// Disable mouse buttons
num = -1;
@ -540,25 +530,20 @@ setMouseButton: function(num) {
UI.rfb.get_mouse().set_touchButton(num);
}
for (b = 0; b < blist.length; b++) {
button = $D('noVNC_mouse_button' + blist[b]);
var blist = [0, 1,2,4];
for (var b = 0; b < blist.length; b++) {
var button = $D('noVNC_mouse_button' + blist[b]);
if (blist[b] === num) {
button.style.display = "";
} else {
button.style.display = "none";
/*
button.style.backgroundColor = "black";
button.style.color = "lightgray";
button.style.backgroundColor = "";
button.style.color = "";
*/
}
}
},
},
updateState: function(rfb, state, oldstate, msg) {
var s, sb, c, d, cad, vd, klass;
updateState: function(rfb, state, oldstate, msg) {
UI.rfb_state = state;
var klass;
switch (state) {
case 'failed':
case 'fatal':
@ -569,7 +554,7 @@ updateState: function(rfb, state, oldstate, msg) {
break;
case 'disconnected':
$D('noVNC_logo').style.display = "block";
// Fall through
/* falls through */
case 'loaded':
klass = "noVNC_status_normal";
break;
@ -593,10 +578,10 @@ updateState: function(rfb, state, oldstate, msg) {
}
UI.updateVisualState();
},
},
// Disable/enable controls depending on connection state
updateVisualState: function() {
// Disable/enable controls depending on connection state
updateVisualState: function() {
var connected = UI.rfb_state === 'normal' ? true : false;
//Util.Debug(">> updateVisualState");
@ -649,10 +634,10 @@ updateVisualState: function() {
}
//Util.Debug("<< updateVisualState");
},
},
// Disable/enable XVP button
updateXvpVisualState: function(ver) {
// Disable/enable XVP button
updateXvpVisualState: function(ver) {
if (ver >= 1) {
$D('xvpButton').style.display = 'inline';
} else {
@ -662,34 +647,29 @@ updateXvpVisualState: function(ver) {
UI.toggleXvpPanel();
}
}
},
},
// Display the desktop name in the document title
updateDocumentTitle: function(rfb, name) {
// Display the desktop name in the document title
updateDocumentTitle: function(rfb, name) {
document.title = name + " - noVNC";
},
},
clipReceive: function(rfb, text) {
clipReceive: function(rfb, text) {
Util.Debug(">> UI.clipReceive: " + text.substr(0,40) + "...");
$D('noVNC_clipboard_text').value = text;
Util.Debug("<< UI.clipReceive");
},
connect: function() {
var host, port, password, path;
},
connect: function() {
UI.closeSettingsMenu();
UI.toggleConnectPanel();
host = $D('noVNC_host').value;
port = $D('noVNC_port').value;
password = $D('noVNC_password').value;
path = $D('noVNC_path').value;
var host = $D('noVNC_host').value;
var port = $D('noVNC_port').value;
var password = $D('noVNC_password').value;
var path = $D('noVNC_path').value;
if ((!host) || (!port)) {
throw("Must set host and port");
throw new Error("Must set host and port");
}
UI.rfb.set_encrypt(UI.getSetting('encrypt'));
@ -704,51 +684,49 @@ connect: function() {
//Close dialog.
setTimeout(UI.setBarPosition, 100);
$D('noVNC_logo').style.display = "none";
},
},
disconnect: function() {
disconnect: function() {
UI.closeSettingsMenu();
UI.rfb.disconnect();
$D('noVNC_logo').style.display = "block";
UI.connSettingsOpen = false;
UI.toggleConnectPanel();
},
},
displayBlur: function() {
displayBlur: function() {
UI.rfb.get_keyboard().set_focused(false);
UI.rfb.get_mouse().set_focused(false);
},
},
displayFocus: function() {
displayFocus: function() {
UI.rfb.get_keyboard().set_focused(true);
UI.rfb.get_mouse().set_focused(true);
},
},
clipClear: function() {
clipClear: function() {
$D('noVNC_clipboard_text').value = "";
UI.rfb.clipboardPasteFrom("");
},
},
clipSend: function() {
clipSend: function() {
var text = $D('noVNC_clipboard_text').value;
Util.Debug(">> UI.clipSend: " + text.substr(0,40) + "...");
UI.rfb.clipboardPasteFrom(text);
Util.Debug("<< UI.clipSend");
},
// Enable/disable and configure viewport clipping
setViewClip: function(clip) {
var display, cur_clip, pos, new_w, new_h;
},
// Enable/disable and configure viewport clipping
setViewClip: function(clip) {
var display;
if (UI.rfb) {
display = UI.rfb.get_display();
} else {
return;
}
cur_clip = display.get_viewport();
var cur_clip = display.get_viewport();
if (typeof(clip) !== 'boolean') {
// Use current setting
@ -768,16 +746,16 @@ setViewClip: function(clip) {
if (UI.getSetting('clip')) {
// If clipping, update clipping settings
$D('noVNC_canvas').style.position = 'absolute';
pos = Util.getPosition($D('noVNC_canvas'));
new_w = window.innerWidth - pos.x;
new_h = window.innerHeight - pos.y;
var pos = Util.getPosition($D('noVNC_canvas'));
var new_w = window.innerWidth - pos.x;
var new_h = window.innerHeight - pos.y;
display.set_viewport(true);
display.viewportChange(0, 0, new_w, new_h);
}
},
},
// Toggle/set/unset the viewport drag/move button
setViewDrag: function(drag) {
// Toggle/set/unset the viewport drag/move button
setViewDrag: function(drag) {
var vmb = $D('noVNC_view_drag_button');
if (!UI.rfb) { return; }
@ -800,14 +778,13 @@ setViewDrag: function(drag) {
vmb.className = "noVNC_status_button";
UI.rfb.set_viewportDrag(false);
}
},
},
// On touch devices, show the OS keyboard
showKeyboard: function() {
var kbi, skb, l;
kbi = $D('keyboardinput');
skb = $D('showKeyboard');
l = kbi.value.length;
// On touch devices, show the OS keyboard
showKeyboard: function() {
var kbi = $D('keyboardinput');
var skb = $D('showKeyboard');
var l = kbi.value.length;
if(UI.keyboardVisible === false) {
kbi.focus();
try { kbi.setSelectionRange(l, l); } // Move the caret to the end
@ -819,9 +796,9 @@ showKeyboard: function() {
skb.className = "noVNC_status_button";
UI.keyboardVisible = false;
}
},
},
keepKeyboard: function() {
keepKeyboard: function() {
clearTimeout(UI.hideKeyboardTimeout);
if(UI.keyboardVisible === true) {
$D('keyboardinput').focus();
@ -830,23 +807,23 @@ keepKeyboard: function() {
$D('keyboardinput').blur();
$D('showKeyboard').className = "noVNC_status_button";
}
},
},
keyboardinputReset: function() {
keyboardinputReset: function() {
var kbi = $D('keyboardinput');
kbi.value = Array(UI.defaultKeyboardinputLen).join("_");
kbi.value = new Array(UI.defaultKeyboardinputLen).join("_");
UI.lastKeyboardinput = kbi.value;
},
},
// When normal keyboard events are left uncought, use the input events from
// the keyboardinput element instead and generate the corresponding key events.
// This code is required since some browsers on Android are inconsistent in
// sending keyCodes in the normal keyboard events when using on screen keyboards.
keyInput: function(event) {
var newValue, oldValue, newLen, oldLen;
newValue = event.target.value;
oldValue = UI.lastKeyboardinput;
// When normal keyboard events are left uncought, use the input events from
// the keyboardinput element instead and generate the corresponding key events.
// This code is required since some browsers on Android are inconsistent in
// sending keyCodes in the normal keyboard events when using on screen keyboards.
keyInput: function(event) {
var newValue = event.target.value;
var oldValue = UI.lastKeyboardinput;
var newLen;
try {
// Try to check caret position since whitespace at the end
// will not be considered by value.length in some browsers
@ -855,18 +832,20 @@ keyInput: function(event) {
// selectionStart is undefined in Google Chrome
newLen = newValue.length;
}
oldLen = oldValue.length;
var oldLen = oldValue.length;
var backspaces;
var inputs = newLen - oldLen;
if (inputs < 0)
if (inputs < 0) {
backspaces = -inputs;
else
} else {
backspaces = 0;
}
// Compare the old string with the new to account for
// text-corrections or other input that modify existing text
for (var i = 0; i < Math.min(oldLen, newLen); i++) {
var i;
for (i = 0; i < Math.min(oldLen, newLen); i++) {
if (newValue.charAt(i) != oldValue.charAt(i)) {
inputs = newLen - i;
backspaces = oldLen - i;
@ -875,10 +854,12 @@ keyInput: function(event) {
}
// Send the key events
for (var i = 0; i < backspaces; i++)
for (i = 0; i < backspaces; i++) {
UI.rfb.sendKey(XK_BackSpace);
for (var i = newLen - inputs; i < newLen; i++)
}
for (i = newLen - inputs; i < newLen; i++) {
UI.rfb.sendKey(newValue.charCodeAt(i));
}
// Control the text content length in the keyboardinput element
if (newLen > 2 * UI.defaultKeyboardinputLen) {
@ -893,21 +874,20 @@ keyInput: function(event) {
event.target.blur();
// This has to be ran outside of the input handler in order to work
setTimeout(function() { UI.keepKeyboard(); }, 0);
} else {
UI.lastKeyboardinput = newValue;
}
},
},
keyInputBlur: function() {
keyInputBlur: function() {
$D('showKeyboard').className = "noVNC_status_button";
//Weird bug in iOS if you change keyboardVisible
//here it does not actually occur so next time
//you click keyboard icon it doesnt work.
UI.hideKeyboardTimeout = setTimeout(function() { UI.setKeyboard(); },100);
},
},
showExtraKeys: function() {
showExtraKeys: function() {
UI.keepKeyboard();
if(UI.extraKeysVisible === false) {
$D('toggleCtrlButton').style.display = "inline";
@ -924,9 +904,9 @@ showExtraKeys: function() {
$D('showExtraKeysButton').className = "noVNC_status_button";
UI.extraKeysVisible = false;
}
},
},
toggleCtrl: function() {
toggleCtrl: function() {
UI.keepKeyboard();
if(UI.ctrlOn === false) {
UI.rfb.sendKey(XK_Control_L, true);
@ -937,9 +917,9 @@ toggleCtrl: function() {
$D('toggleCtrlButton').className = "noVNC_status_button";
UI.ctrlOn = false;
}
},
},
toggleAlt: function() {
toggleAlt: function() {
UI.keepKeyboard();
if(UI.altOn === false) {
UI.rfb.sendKey(XK_Alt_L, true);
@ -950,54 +930,50 @@ toggleAlt: function() {
$D('toggleAltButton').className = "noVNC_status_button";
UI.altOn = false;
}
},
},
sendTab: function() {
sendTab: function() {
UI.keepKeyboard();
UI.rfb.sendKey(XK_Tab);
},
},
sendEsc: function() {
sendEsc: function() {
UI.keepKeyboard();
UI.rfb.sendKey(XK_Escape);
},
},
setKeyboard: function() {
setKeyboard: function() {
UI.keyboardVisible = false;
},
},
// iOS < Version 5 does not support position fixed. Javascript workaround:
setOnscroll: function() {
// iOS < Version 5 does not support position fixed. Javascript workaround:
setOnscroll: function() {
window.onscroll = function() {
UI.setBarPosition();
};
},
},
setResize: function () {
setResize: function () {
window.onResize = function() {
UI.setBarPosition();
};
},
},
//Helper to add options to dropdown.
addOption: function(selectbox,text,value )
{
//Helper to add options to dropdown.
addOption: function(selectbox, text, value) {
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
},
},
setBarPosition: function() {
setBarPosition: function() {
$D('noVNC-control-bar').style.top = (window.pageYOffset) + 'px';
$D('noVNC_mobile_buttons').style.left = (window.pageXOffset) + 'px';
var vncwidth = $D('noVNC_screen').style.offsetWidth;
$D('noVNC-control-bar').style.width = vncwidth + 'px';
}
};
}
};
})();