util.js 18 KB

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