util.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. Util.getPosition = function(obj) {
  386. "use strict";
  387. // NB(sross): the Mozilla developer reference seems to indicate that
  388. // getBoundingClientRect includes border and padding, so the canvas
  389. // style should NOT include either.
  390. var objPosition = obj.getBoundingClientRect();
  391. return {'x': objPosition.left + window.pageXOffset, 'y': objPosition.top + window.pageYOffset,
  392. 'width': objPosition.width, 'height': objPosition.height};
  393. };
  394. // Get mouse event position in DOM element
  395. Util.getEventPosition = function (e, obj, scale) {
  396. "use strict";
  397. var evt, docX, docY, pos;
  398. //if (!e) evt = window.event;
  399. evt = (e ? e : window.event);
  400. evt = (evt.changedTouches ? evt.changedTouches[0] : evt.touches ? evt.touches[0] : evt);
  401. if (evt.pageX || evt.pageY) {
  402. docX = evt.pageX;
  403. docY = evt.pageY;
  404. } else if (evt.clientX || evt.clientY) {
  405. docX = evt.clientX + document.body.scrollLeft +
  406. document.documentElement.scrollLeft;
  407. docY = evt.clientY + document.body.scrollTop +
  408. document.documentElement.scrollTop;
  409. }
  410. pos = Util.getPosition(obj);
  411. if (typeof scale === "undefined") {
  412. scale = 1;
  413. }
  414. var realx = docX - pos.x;
  415. var realy = docY - pos.y;
  416. var x = Math.max(Math.min(realx, pos.width - 1), 0);
  417. var y = Math.max(Math.min(realy, pos.height - 1), 0);
  418. return {'x': x / scale, 'y': y / scale, 'realx': realx / scale, 'realy': realy / scale};
  419. };
  420. // Event registration. Based on: http://www.scottandrew.com/weblog/articles/cbs-events
  421. Util.addEvent = function (obj, evType, fn) {
  422. "use strict";
  423. if (obj.attachEvent) {
  424. var r = obj.attachEvent("on" + evType, fn);
  425. return r;
  426. } else if (obj.addEventListener) {
  427. obj.addEventListener(evType, fn, false);
  428. return true;
  429. } else {
  430. throw new Error("Handler could not be attached");
  431. }
  432. };
  433. Util.removeEvent = function (obj, evType, fn) {
  434. "use strict";
  435. if (obj.detachEvent) {
  436. var r = obj.detachEvent("on" + evType, fn);
  437. return r;
  438. } else if (obj.removeEventListener) {
  439. obj.removeEventListener(evType, fn, false);
  440. return true;
  441. } else {
  442. throw new Error("Handler could not be removed");
  443. }
  444. };
  445. Util.stopEvent = function (e) {
  446. "use strict";
  447. if (e.stopPropagation) { e.stopPropagation(); }
  448. else { e.cancelBubble = true; }
  449. if (e.preventDefault) { e.preventDefault(); }
  450. else { e.returnValue = false; }
  451. };
  452. Util._cursor_uris_supported = null;
  453. Util.browserSupportsCursorURIs = function () {
  454. if (Util._cursor_uris_supported === null) {
  455. try {
  456. var target = document.createElement('canvas');
  457. target.style.cursor = 'url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default';
  458. if (target.style.cursor) {
  459. Util.Info("Data URI scheme cursor supported");
  460. Util._cursor_uris_supported = true;
  461. } else {
  462. Util.Warn("Data URI scheme cursor not supported");
  463. Util._cursor_uris_supported = false;
  464. }
  465. } catch (exc) {
  466. Util.Error("Data URI scheme cursor test exception: " + exc);
  467. Util._cursor_uris_supported = false;
  468. }
  469. }
  470. return Util._cursor_uris_supported;
  471. };
  472. // Set browser engine versions. Based on mootools.
  473. Util.Features = {xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector)};
  474. (function () {
  475. "use strict";
  476. // 'presto': (function () { return (!window.opera) ? false : true; }()),
  477. var detectPresto = function () {
  478. return !!window.opera;
  479. };
  480. // 'trident': (function () { return (!window.ActiveXObject) ? false : ((window.XMLHttpRequest) ? ((document.querySelectorAll) ? 6 : 5) : 4);
  481. var detectTrident = function () {
  482. if (!window.ActiveXObject) {
  483. return false;
  484. } else {
  485. if (window.XMLHttpRequest) {
  486. return (document.querySelectorAll) ? 6 : 5;
  487. } else {
  488. return 4;
  489. }
  490. }
  491. };
  492. // 'webkit': (function () { try { return (navigator.taintEnabled) ? false : ((Util.Features.xpath) ? ((Util.Features.query) ? 525 : 420) : 419); } catch (e) { return false; } }()),
  493. var detectInitialWebkit = function () {
  494. try {
  495. if (navigator.taintEnabled) {
  496. return false;
  497. } else {
  498. if (Util.Features.xpath) {
  499. return (Util.Features.query) ? 525 : 420;
  500. } else {
  501. return 419;
  502. }
  503. }
  504. } catch (e) {
  505. return false;
  506. }
  507. };
  508. var detectActualWebkit = function (initial_ver) {
  509. var re = /WebKit\/([0-9\.]*) /;
  510. var str_ver = (navigator.userAgent.match(re) || ['', initial_ver])[1];
  511. return parseFloat(str_ver, 10);
  512. };
  513. // 'gecko': (function () { return (!document.getBoxObjectFor && window.mozInnerScreenX == null) ? false : ((document.getElementsByClassName) ? 19ssName) ? 19 : 18 : 18); }())
  514. var detectGecko = function () {
  515. /* jshint -W041 */
  516. if (!document.getBoxObjectFor && window.mozInnerScreenX == null) {
  517. return false;
  518. } else {
  519. return (document.getElementsByClassName) ? 19 : 18;
  520. }
  521. /* jshint +W041 */
  522. };
  523. Util.Engine = {
  524. // Version detection break in Opera 11.60 (errors on arguments.callee.caller reference)
  525. //'presto': (function() {
  526. // return (!window.opera) ? false : ((arguments.callee.caller) ? 960 : ((document.getElementsByClassName) ? 950 : 925)); }()),
  527. 'presto': detectPresto(),
  528. 'trident': detectTrident(),
  529. 'webkit': detectInitialWebkit(),
  530. 'gecko': detectGecko(),
  531. };
  532. if (Util.Engine.webkit) {
  533. // Extract actual webkit version if available
  534. Util.Engine.webkit = detectActualWebkit(Util.Engine.webkit);
  535. }
  536. })();
  537. Util.Flash = (function () {
  538. "use strict";
  539. var v, version;
  540. try {
  541. v = navigator.plugins['Shockwave Flash'].description;
  542. } catch (err1) {
  543. try {
  544. v = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
  545. } catch (err2) {
  546. v = '0 r0';
  547. }
  548. }
  549. version = v.match(/\d+/g);
  550. return {version: parseInt(version[0] || 0 + '.' + version[1], 10) || 0, build: parseInt(version[2], 10) || 0};
  551. }());