util.js 20 KB

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