]> git.proxmox.com Git - mirror_novnc.git/blame - include/util.js
Merge pull request #368 from DirectXMan12/refactor/cleanup
[mirror_novnc.git] / include / util.js
CommitLineData
61dd52c9 1/*
15046f00 2 * noVNC: HTML5 VNC client
d58f8b51 3 * Copyright (C) 2012 Joel Martin
1d728ace 4 * Licensed under MPL 2.0 (see LICENSE.txt)
15046f00
JM
5 *
6 * See README.md for usage and integration instructions.
61dd52c9
JM
7 */
8
d21cd6c1
SR
9/* jshint white: false, nonstandard: true */
10/*global window, console, document, navigator, ActiveXObject, INCLUDE_URI */
61dd52c9 11
15046f00 12// Globals defined here
a59f1cd2 13var Util = {};
15046f00 14
81e5adaf 15
56ec48be
JM
16/*
17 * Make arrays quack
18 */
19
56ec48be 20Array.prototype.push8 = function (num) {
d21cd6c1 21 "use strict";
56ec48be
JM
22 this.push(num & 0xFF);
23};
24
56ec48be 25Array.prototype.push16 = function (num) {
d21cd6c1 26 "use strict";
56ec48be 27 this.push((num >> 8) & 0xFF,
d21cd6c1 28 num & 0xFF);
56ec48be 29};
56ec48be 30Array.prototype.push32 = function (num) {
d21cd6c1 31 "use strict";
56ec48be
JM
32 this.push((num >> 24) & 0xFF,
33 (num >> 16) & 0xFF,
34 (num >> 8) & 0xFF,
d21cd6c1 35 num & 0xFF);
56ec48be 36};
56ec48be 37
32f135d7
JM
38// IE does not support map (even in IE9)
39//This prototype is provided by the Mozilla foundation and
40//is distributed under the MIT license.
41//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
d21cd6c1
SR
42if (!Array.prototype.map) {
43 Array.prototype.map = function (fun /*, thisp*/) {
44 "use strict";
45 var len = this.length;
46 if (typeof fun != "function") {
47 throw new TypeError();
48 }
32f135d7 49
d21cd6c1
SR
50 var res = new Array(len);
51 var thisp = arguments[1];
52 for (var i = 0; i < len; i++) {
53 if (i in this) {
54 res[i] = fun.call(thisp, this[i], i, this);
55 }
56 }
57
58 return res;
59 };
32f135d7
JM
60}
61
0fe30338 62// IE <9 does not support indexOf
63//This prototype is provided by the Mozilla foundation and
64//is distributed under the MIT license.
65//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
d21cd6c1
SR
66if (!Array.prototype.indexOf) {
67 Array.prototype.indexOf = function (elt /*, from*/) {
68 "use strict";
69 var len = this.length >>> 0;
70
71 var from = Number(arguments[1]) || 0;
72 from = (from < 0) ? Math.ceil(from) : Math.floor(from);
73 if (from < 0) {
74 from += len;
75 }
76
77 for (; from < len; from++) {
78 if (from in this &&
79 this[from] === elt) {
80 return from;
81 }
82 }
83 return -1;
84 };
0fe30338 85}
86
95eb681b
SR
87// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
88if (!Object.keys) {
d21cd6c1
SR
89 Object.keys = (function () {
90 'use strict';
91 var hasOwnProperty = Object.prototype.hasOwnProperty,
92 hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
93 dontEnums = [
94 'toString',
95 'toLocaleString',
96 'valueOf',
97 'hasOwnProperty',
98 'isPrototypeOf',
99 'propertyIsEnumerable',
100 'constructor'
101 ],
102 dontEnumsLength = dontEnums.length;
103
104 return function (obj) {
105 if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
106 throw new TypeError('Object.keys called on non-object');
107 }
95eb681b 108
d21cd6c1 109 var result = [], prop, i;
95eb681b 110
d21cd6c1
SR
111 for (prop in obj) {
112 if (hasOwnProperty.call(obj, prop)) {
113 result.push(prop);
114 }
115 }
95eb681b 116
d21cd6c1
SR
117 if (hasDontEnumBug) {
118 for (i = 0; i < dontEnumsLength; i++) {
119 if (hasOwnProperty.call(obj, dontEnums[i])) {
120 result.push(dontEnums[i]);
121 }
122 }
123 }
124 return result;
125 };
126 })();
127}
95eb681b 128
d21cd6c1
SR
129// PhantomJS 1.x doesn't support bind,
130// so leave this in until PhantomJS 2.0 is released
131//This prototype is provided by the Mozilla foundation and
132//is distributed under the MIT license.
133//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
134if (!Function.prototype.bind) {
135 Function.prototype.bind = function (oThis) {
136 if (typeof this !== "function") {
137 // closest thing possible to the ECMAScript 5
138 // internal IsCallable function
139 throw new TypeError("Function.prototype.bind - " +
140 "what is trying to be bound is not callable");
95eb681b 141 }
d21cd6c1
SR
142
143 var aArgs = Array.prototype.slice.call(arguments, 1),
144 fToBind = this,
145 fNOP = function () {},
146 fBound = function () {
147 return fToBind.apply(this instanceof fNOP && oThis ? this
148 : oThis,
149 aArgs.concat(Array.prototype.slice.call(arguments)));
150 };
151
152 fNOP.prototype = this.prototype;
153 fBound.prototype = new fNOP();
154
155 return fBound;
95eb681b 156 };
95eb681b 157}
0fe30338 158
d21cd6c1 159//
34d8b844
JM
160// requestAnimationFrame shim with setTimeout fallback
161//
162
d21cd6c1
SR
163window.requestAnimFrame = (function () {
164 "use strict";
165 return window.requestAnimationFrame ||
166 window.webkitRequestAnimationFrame ||
167 window.mozRequestAnimationFrame ||
168 window.oRequestAnimationFrame ||
169 window.msRequestAnimationFrame ||
170 function (callback) {
34d8b844
JM
171 window.setTimeout(callback, 1000 / 60);
172 };
173})();
174
d21cd6c1 175/*
15046f00
JM
176 * ------------------------------------------------------
177 * Namespaced in Util
178 * ------------------------------------------------------
179 */
180
8db09746
JM
181/*
182 * Logging/debug routines
183 */
184
c1eba48f 185Util._log_level = 'warn';
8db09746 186Util.init_logging = function (level) {
d21cd6c1 187 "use strict";
c1eba48f 188 if (typeof level === 'undefined') {
c1eba48f
JM
189 level = Util._log_level;
190 } else {
191 Util._log_level = level;
192 }
8db09746
JM
193 if (typeof window.console === "undefined") {
194 if (typeof window.opera !== "undefined") {
195 window.console = {
196 'log' : window.opera.postError,
197 'warn' : window.opera.postError,
d21cd6c1
SR
198 'error': window.opera.postError
199 };
8db09746
JM
200 } else {
201 window.console = {
d21cd6c1
SR
202 'log' : function (m) {},
203 'warn' : function (m) {},
204 'error': function (m) {}
205 };
8db09746
JM
206 }
207 }
208
209 Util.Debug = Util.Info = Util.Warn = Util.Error = function (msg) {};
d21cd6c1 210 /* jshint -W086 */
8db09746 211 switch (level) {
d21cd6c1
SR
212 case 'debug':
213 Util.Debug = function (msg) { console.log(msg); };
214 case 'info':
215 Util.Info = function (msg) { console.log(msg); };
216 case 'warn':
217 Util.Warn = function (msg) { console.warn(msg); };
218 case 'error':
219 Util.Error = function (msg) { console.error(msg); };
8db09746
JM
220 case 'none':
221 break;
222 default:
d21cd6c1 223 throw new Error("invalid logging type '" + level + "'");
8db09746 224 }
d21cd6c1 225 /* jshint +W086 */
8db09746 226};
c1eba48f 227Util.get_logging = function () {
8d5d2c82 228 return Util._log_level;
d3796c14 229};
8db09746 230// Initialize logging level
c1eba48f 231Util.init_logging();
8db09746 232
d21cd6c1
SR
233Util.make_property = function (proto, name, mode, type) {
234 "use strict";
a8edf9d8 235
d21cd6c1
SR
236 var getter;
237 if (type === 'arr') {
238 getter = function (idx) {
239 if (typeof idx !== 'undefined') {
240 return this['_' + name][idx];
241 } else {
242 return this['_' + name];
243 }
244 };
245 } else {
246 getter = function () {
247 return this['_' + name];
248 };
249 }
5210330a 250
d21cd6c1
SR
251 var make_setter = function (process_val) {
252 if (process_val) {
253 return function (val, idx) {
254 if (typeof idx !== 'undefined') {
255 this['_' + name][idx] = process_val(val);
256 } else {
257 this['_' + name] = process_val(val);
258 }
259 };
5210330a 260 } else {
d21cd6c1
SR
261 return function (val, idx) {
262 if (typeof idx !== 'undefined') {
263 this['_' + name][idx] = val;
264 } else {
265 this['_' + name] = val;
266 }
267 };
5210330a
JM
268 }
269 };
270
d21cd6c1
SR
271 var setter;
272 if (type === 'bool') {
273 setter = make_setter(function (val) {
274 if (!val || (val in {'0': 1, 'no': 1, 'false': 1})) {
275 return false;
d890e864 276 } else {
d21cd6c1 277 return true;
d890e864 278 }
d21cd6c1
SR
279 });
280 } else if (type === 'int') {
281 setter = make_setter(function (val) { return parseInt(val, 10); });
282 } else if (type === 'float') {
283 setter = make_setter(parseFloat);
284 } else if (type === 'str') {
285 setter = make_setter(String);
286 } else if (type === 'func') {
287 setter = make_setter(function (val) {
5210330a 288 if (!val) {
d21cd6c1
SR
289 return function () {};
290 } else {
291 return val;
5210330a 292 }
d21cd6c1
SR
293 });
294 } else if (type === 'arr' || type === 'dom' || type == 'raw') {
295 setter = make_setter();
296 } else {
297 throw new Error('Unknown property type ' + type); // some sanity checking
298 }
5210330a 299
d21cd6c1
SR
300 // set the getter
301 if (typeof proto['get_' + name] === 'undefined') {
302 proto['get_' + name] = getter;
125d8bbb 303 }
d890e864 304
d21cd6c1
SR
305 // set the setter if needed
306 if (typeof proto['set_' + name] === 'undefined') {
307 if (mode === 'rw') {
308 proto['set_' + name] = setter;
309 } else if (mode === 'wo') {
310 proto['set_' + name] = function (val, idx) {
311 if (typeof this['_' + name] !== 'undefined') {
312 throw new Error(name + " can only be set once");
313 }
314 setter.call(this, val, idx);
315 };
316 }
125d8bbb 317 }
ff36b127 318
d21cd6c1
SR
319 // make a special setter that we can use in set defaults
320 proto['_raw_set_' + name] = function (val, idx) {
321 setter.call(this, val, idx);
322 //delete this['_init_set_' + name]; // remove it after use
323 };
324};
325
326Util.make_properties = function (constructor, arr) {
327 "use strict";
328 for (var i = 0; i < arr.length; i++) {
329 Util.make_property(constructor.prototype, arr[i][0], arr[i][1], arr[i][2]);
ff36b127 330 }
125d8bbb
JM
331};
332
d21cd6c1
SR
333Util.set_defaults = function (obj, conf, defaults) {
334 var defaults_keys = Object.keys(defaults);
335 var conf_keys = Object.keys(conf);
336 var keys_obj = {};
5210330a 337 var i;
d21cd6c1
SR
338 for (i = 0; i < defaults_keys.length; i++) { keys_obj[defaults_keys[i]] = 1; }
339 for (i = 0; i < conf_keys.length; i++) { keys_obj[conf_keys[i]] = 1; }
340 var keys = Object.keys(keys_obj);
341
342 for (i = 0; i < keys.length; i++) {
343 var setter = obj['_raw_set_' + keys[i]];
344
345 if (conf[keys[i]]) {
346 setter.call(obj, conf[keys[i]]);
347 } else {
348 setter.call(obj, defaults[keys[i]]);
349 }
5210330a 350 }
ff4bfcb7 351};
125d8bbb 352
b7996b04 353/*
354 * Decode from UTF-8
355 */
d21cd6c1
SR
356Util.decodeUTF8 = function (utf8string) {
357 "use strict";
b7996b04 358 return decodeURIComponent(escape(utf8string));
d21cd6c1 359};
b7996b04 360
361
a8edf9d8 362
15046f00
JM
363/*
364 * Cross-browser routines
365 */
366
6f4b1e40
JM
367
368// Dynamically load scripts without using document.write()
369// Reference: http://unixpapa.com/js/dyna.html
370//
371// Handles the case where load_scripts is invoked from a script that
372// itself is loaded via load_scripts. Once all scripts are loaded the
373// window.onscriptsloaded handler is called (if set).
d21cd6c1 374Util.get_include_uri = function () {
6f4b1e40 375 return (typeof INCLUDE_URI !== "undefined") ? INCLUDE_URI : "include/";
d21cd6c1 376};
73ee4fa7 377Util._loading_scripts = [];
6f4b1e40 378Util._pending_scripts = [];
d21cd6c1
SR
379Util.load_scripts = function (files) {
380 "use strict";
73ee4fa7
JM
381 var head = document.getElementsByTagName('head')[0], script,
382 ls = Util._loading_scripts, ps = Util._pending_scripts;
d21cd6c1
SR
383
384 var loadFunc = function (e) {
385 while (ls.length > 0 && (ls[0].readyState === 'loaded' ||
386 ls[0].readyState === 'complete')) {
387 // For IE, append the script to trigger execution
388 var s = ls.shift();
389 //console.log("loaded script: " + s.src);
390 head.appendChild(s);
391 }
392 if (!this.readyState ||
393 (Util.Engine.presto && this.readyState === 'loaded') ||
394 this.readyState === 'complete') {
395 if (ps.indexOf(this) >= 0) {
396 this.onload = this.onreadystatechange = null;
397 //console.log("completed script: " + this.src);
398 ps.splice(ps.indexOf(this), 1);
399
400 // Call window.onscriptsload after last script loads
401 if (ps.length === 0 && window.onscriptsload) {
402 window.onscriptsload();
403 }
404 }
405 }
406 };
407
408 for (var f = 0; f < files.length; f++) {
73ee4fa7
JM
409 script = document.createElement('script');
410 script.type = 'text/javascript';
411 script.src = Util.get_include_uri() + files[f];
412 //console.log("loading script: " + script.src);
d21cd6c1 413 script.onload = script.onreadystatechange = loadFunc;
73ee4fa7
JM
414 // In-order script execution tricks
415 if (Util.Engine.trident) {
416 // For IE wait until readyState is 'loaded' before
417 // appending it which will trigger execution
418 // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
419 ls.push(script);
420 } else {
421 // For webkit and firefox set async=false and append now
422 // https://developer.mozilla.org/en-US/docs/HTML/Element/script
423 script.async = false;
424 head.appendChild(script);
425 }
8e2d7496 426 ps.push(script);
6f4b1e40 427 }
d21cd6c1 428};
6f4b1e40 429
c77938ef 430
15046f00 431// Get DOM element position on page
c77938ef
SR
432// This solution is based based on http://www.greywyvern.com/?post=331
433// Thanks to Brian Huisman AKA GreyWyvern!
d21cd6c1
SR
434Util.getPosition = (function () {
435 "use strict";
c77938ef 436 function getStyle(obj, styleProp) {
d21cd6c1 437 var y;
c77938ef 438 if (obj.currentStyle) {
d21cd6c1 439 y = obj.currentStyle[styleProp];
c77938ef 440 } else if (window.getComputedStyle)
d21cd6c1 441 y = window.getComputedStyle(obj, null)[styleProp];
c77938ef 442 return y;
d21cd6c1 443 }
c77938ef
SR
444
445 function scrollDist() {
446 var myScrollTop = 0, myScrollLeft = 0;
447 var html = document.getElementsByTagName('html')[0];
448
449 // get the scrollTop part
450 if (html.scrollTop && document.documentElement.scrollTop) {
451 myScrollTop = html.scrollTop;
452 } else if (html.scrollTop || document.documentElement.scrollTop) {
453 myScrollTop = html.scrollTop + document.documentElement.scrollTop;
454 } else if (document.body.scrollTop) {
455 myScrollTop = document.body.scrollTop;
456 } else {
457 myScrollTop = 0;
458 }
459
460 // get the scrollLeft part
461 if (html.scrollLeft && document.documentElement.scrollLeft) {
462 myScrollLeft = html.scrollLeft;
463 } else if (html.scrollLeft || document.documentElement.scrollLeft) {
464 myScrollLeft = html.scrollLeft + document.documentElement.scrollLeft;
465 } else if (document.body.scrollLeft) {
466 myScrollLeft = document.body.scrollLeft;
467 } else {
468 myScrollLeft = 0;
469 }
470
471 return [myScrollLeft, myScrollTop];
d21cd6c1 472 }
c77938ef
SR
473
474 return function (obj) {
475 var curleft = 0, curtop = 0, scr = obj, fixed = false;
476 while ((scr = scr.parentNode) && scr != document.body) {
477 curleft -= scr.scrollLeft || 0;
478 curtop -= scr.scrollTop || 0;
479 if (getStyle(scr, "position") == "fixed") {
480 fixed = true;
481 }
482 }
483 if (fixed && !window.opera) {
484 var scrDist = scrollDist();
485 curleft += scrDist[0];
486 curtop += scrDist[1];
487 }
488
15046f00 489 do {
c77938ef
SR
490 curleft += obj.offsetLeft;
491 curtop += obj.offsetTop;
d21cd6c1 492 } while ((obj = obj.offsetParent));
c77938ef
SR
493
494 return {'x': curleft, 'y': curtop};
495 };
496})();
497
15046f00
JM
498
499// Get mouse event position in DOM element
125d8bbb 500Util.getEventPosition = function (e, obj, scale) {
d21cd6c1 501 "use strict";
15046f00
JM
502 var evt, docX, docY, pos;
503 //if (!e) evt = window.event;
504 evt = (e ? e : window.event);
ad3f7624 505 evt = (evt.changedTouches ? evt.changedTouches[0] : evt.touches ? evt.touches[0] : evt);
15046f00
JM
506 if (evt.pageX || evt.pageY) {
507 docX = evt.pageX;
508 docY = evt.pageY;
509 } else if (evt.clientX || evt.clientY) {
510 docX = evt.clientX + document.body.scrollLeft +
511 document.documentElement.scrollLeft;
512 docY = evt.clientY + document.body.scrollTop +
513 document.documentElement.scrollTop;
514 }
515 pos = Util.getPosition(obj);
125d8bbb
JM
516 if (typeof scale === "undefined") {
517 scale = 1;
518 }
ca9a9964
PD
519 var realx = docX - pos.x;
520 var realy = docY - pos.y;
d21cd6c1
SR
521 var x = Math.max(Math.min(realx, obj.width - 1), 0);
522 var y = Math.max(Math.min(realy, obj.height - 1), 0);
ca9a9964 523 return {'x': x / scale, 'y': y / scale, 'realx': realx / scale, 'realy': realy / scale};
15046f00
JM
524};
525
526
527// Event registration. Based on: http://www.scottandrew.com/weblog/articles/cbs-events
d21cd6c1
SR
528Util.addEvent = function (obj, evType, fn) {
529 "use strict";
530 if (obj.attachEvent) {
531 var r = obj.attachEvent("on" + evType, fn);
15046f00 532 return r;
d21cd6c1
SR
533 } else if (obj.addEventListener) {
534 obj.addEventListener(evType, fn, false);
d93d3e09 535 return true;
15046f00 536 } else {
d21cd6c1 537 throw new Error("Handler could not be attached");
15046f00
JM
538 }
539};
540
d21cd6c1
SR
541Util.removeEvent = function (obj, evType, fn) {
542 "use strict";
543 if (obj.detachEvent) {
544 var r = obj.detachEvent("on" + evType, fn);
15046f00 545 return r;
d21cd6c1 546 } else if (obj.removeEventListener) {
d93d3e09
JM
547 obj.removeEventListener(evType, fn, false);
548 return true;
15046f00 549 } else {
d21cd6c1 550 throw new Error("Handler could not be removed");
15046f00
JM
551 }
552};
553
d21cd6c1
SR
554Util.stopEvent = function (e) {
555 "use strict";
15046f00
JM
556 if (e.stopPropagation) { e.stopPropagation(); }
557 else { e.cancelBubble = true; }
558
559 if (e.preventDefault) { e.preventDefault(); }
560 else { e.returnValue = false; }
561};
562
563
564// Set browser engine versions. Based on mootools.
565Util.Features = {xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector)};
566
d21cd6c1
SR
567(function () {
568 "use strict";
569 // 'presto': (function () { return (!window.opera) ? false : true; }()),
570 var detectPresto = function () {
571 return !!window.opera;
572 };
573
574 // 'trident': (function () { return (!window.ActiveXObject) ? false : ((window.XMLHttpRequest) ? ((document.querySelectorAll) ? 6 : 5) : 4);
575 var detectTrident = function () {
576 if (!window.ActiveXObject) {
577 return false;
578 } else {
579 if (window.XMLHttpRequest) {
580 return (document.querySelectorAll) ? 6 : 5;
581 } else {
582 return 4;
583 }
584 }
585 };
586
587 // 'webkit': (function () { try { return (navigator.taintEnabled) ? false : ((Util.Features.xpath) ? ((Util.Features.query) ? 525 : 420) : 419); } catch (e) { return false; } }()),
588 var detectInitialWebkit = function () {
589 try {
590 if (navigator.taintEnabled) {
591 return false;
592 } else {
593 if (Util.Features.xpath) {
594 return (Util.Features.query) ? 525 : 420;
595 } else {
596 return 419;
597 }
598 }
599 } catch (e) {
600 return false;
601 }
602 };
603
604 var detectActualWebkit = function (initial_ver) {
605 var re = /WebKit\/([0-9\.]*) /;
606 var str_ver = (navigator.userAgent.match(re) || ['', initial_ver])[1];
607 return parseFloat(str_ver, 10);
608 };
609
610 // 'gecko': (function () { return (!document.getBoxObjectFor && window.mozInnerScreenX == null) ? false : ((document.getElementsByClassName) ? 19ssName) ? 19 : 18 : 18); }())
611 var detectGecko = function () {
612 /* jshint -W041 */
613 if (!document.getBoxObjectFor && window.mozInnerScreenX == null) {
614 return false;
615 } else {
616 return (document.getElementsByClassName) ? 19 : 18;
617 }
618 /* jshint +W041 */
619 };
620
621 Util.Engine = {
622 // Version detection break in Opera 11.60 (errors on arguments.callee.caller reference)
623 //'presto': (function() {
624 // return (!window.opera) ? false : ((arguments.callee.caller) ? 960 : ((document.getElementsByClassName) ? 950 : 925)); }()),
625 'presto': detectPresto(),
626 'trident': detectTrident(),
627 'webkit': detectInitialWebkit(),
628 'gecko': detectGecko(),
629 };
630
631 if (Util.Engine.webkit) {
632 // Extract actual webkit version if available
633 Util.Engine.webkit = detectActualWebkit(Util.Engine.webkit);
634 }
635})();
15046f00 636
d21cd6c1
SR
637Util.Flash = (function () {
638 "use strict";
15046f00
JM
639 var v, version;
640 try {
641 v = navigator.plugins['Shockwave Flash'].description;
d21cd6c1 642 } catch (err1) {
15046f00
JM
643 try {
644 v = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
d21cd6c1 645 } catch (err2) {
15046f00
JM
646 v = '0 r0';
647 }
648 }
649 version = v.match(/\d+/g);
650 return {version: parseInt(version[0] || 0 + '.' + version[1], 10) || 0, build: parseInt(version[2], 10) || 0};
d21cd6c1 651}());