You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

board.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /**
  2. * WHITEBOPHIR
  3. *********************************************************
  4. * @licstart The following is the entire license notice for the
  5. * JavaScript code in this page.
  6. *
  7. * Copyright (C) 2013 Ophir LOJKINE
  8. *
  9. *
  10. * The JavaScript code in this page is free software: you can
  11. * redistribute it and/or modify it under the terms of the GNU
  12. * General Public License (GNU GPL) as published by the Free Software
  13. * Foundation, either version 3 of the License, or (at your option)
  14. * any later version. The code is distributed WITHOUT ANY WARRANTY;
  15. * without even the implied warranty of MERCHANTABILITY or FITNESS
  16. * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
  17. *
  18. * As additional permission under GNU GPL version 3 section 7, you
  19. * may distribute non-source (e.g., minimized or compacted) forms of
  20. * that code without the copy of the GNU GPL normally required by
  21. * section 4, provided you include this license notice and a URL
  22. * through which recipients can access the Corresponding Source.
  23. *
  24. * @licend
  25. */
  26. var Tools = {};
  27. Tools.i18n = (function i18n() {
  28. var translations = JSON.parse(document.getElementById("translations").text);
  29. return {
  30. "t": function translate(s) {
  31. var key = s.toLowerCase().replace(/ /g, '_');
  32. return translations[key] || s;
  33. }
  34. };
  35. })();
  36. Tools.server_config = JSON.parse(document.getElementById("configuration").text);
  37. Tools.board = document.getElementById("board");
  38. Tools.svg = document.getElementById("canvas");
  39. Tools.drawingArea = Tools.svg.getElementById("drawingArea");
  40. //Initialization
  41. Tools.curTool = null;
  42. Tools.drawingEvent = true;
  43. Tools.showMarker = true;
  44. Tools.showOtherCursors = true;
  45. Tools.showMyCursor = true;
  46. Tools.isIE = /MSIE|Trident/.test(window.navigator.userAgent);
  47. Tools.socket = null;
  48. Tools.connect = function () {
  49. var self = this;
  50. // Destroy socket if one already exists
  51. if (self.socket) {
  52. self.socket.destroy();
  53. delete self.socket;
  54. self.socket = null;
  55. }
  56. this.socket = io.connect('', {
  57. "path": window.location.pathname.split("/boards/")[0] + "/socket.io",
  58. "reconnection": true,
  59. "reconnectionDelay": 100, //Make the xhr connections as fast as possible
  60. "timeout": 1000 * 60 * 20 // Timeout after 20 minutes
  61. });
  62. //Receive draw instructions from the server
  63. this.socket.on("broadcast", function (msg) {
  64. handleMessage(msg).finally(function afterload() {
  65. var loadingEl = document.getElementById("loadingMessage");
  66. loadingEl.classList.add("hidden");
  67. });
  68. });
  69. this.socket.on("reconnect", function onReconnection() {
  70. Tools.socket.emit('joinboard', Tools.boardName);
  71. });
  72. };
  73. Tools.connect();
  74. Tools.boardName = (function () {
  75. var path = window.location.pathname.split("/");
  76. return decodeURIComponent(path[path.length - 1]);
  77. })();
  78. //Get the board as soon as the page is loaded
  79. Tools.socket.emit("getboard", Tools.boardName);
  80. function saveBoardNametoLocalStorage() {
  81. var boardName = Tools.boardName;
  82. if (boardName.toLowerCase() === 'anonymous') return;
  83. var recentBoards, key = "recent-boards";
  84. try {
  85. recentBoards = JSON.parse(localStorage.getItem(key));
  86. if (!Array.isArray(recentBoards)) throw new Error("Invalid type");
  87. } catch(e) {
  88. // On localstorage or json error, reset board list
  89. recentBoards = [];
  90. console.log("Board history loading error", e);
  91. }
  92. recentBoards = recentBoards.filter(function (name) {
  93. return name !== boardName;
  94. });
  95. recentBoards.unshift(boardName);
  96. recentBoards = recentBoards.slice(0, 20);
  97. localStorage.setItem(key, JSON.stringify(recentBoards));
  98. }
  99. // Refresh recent boards list on each page show
  100. window.addEventListener("pageshow", saveBoardNametoLocalStorage);
  101. Tools.HTML = {
  102. template: new Minitpl("#tools > .tool"),
  103. addShortcut: function addShortcut(key, callback) {
  104. window.addEventListener("keydown", function (e) {
  105. if (e.key === key && !e.target.matches("input[type=text], textarea")) {
  106. callback();
  107. }
  108. });
  109. },
  110. addTool: function (toolName, toolIcon, toolIconHTML, toolShortcut, oneTouch) {
  111. var callback = function () {
  112. Tools.change(toolName);
  113. };
  114. this.addShortcut(toolShortcut, function () {
  115. Tools.change(toolName);
  116. document.activeElement.blur && document.activeElement.blur();
  117. });
  118. return this.template.add(function (elem) {
  119. elem.addEventListener("click", callback);
  120. elem.id = "toolID-" + toolName;
  121. elem.getElementsByClassName("tool-name")[0].textContent = Tools.i18n.t(toolName);
  122. var toolIconElem = elem.getElementsByClassName("tool-icon")[0];
  123. toolIconElem.src = toolIcon;
  124. toolIconElem.alt = toolIcon;
  125. if (oneTouch) elem.classList.add("oneTouch");
  126. elem.title =
  127. Tools.i18n.t(toolName) + " (" +
  128. Tools.i18n.t("keyboard shortcut") + ": " +
  129. toolShortcut + ")" +
  130. (Tools.list[toolName].secondary ? " [" + Tools.i18n.t("click_to_toggle") + "]" : "");
  131. if (Tools.list[toolName].secondary) {
  132. elem.classList.add('hasSecondary');
  133. var secondaryIcon = elem.getElementsByClassName('secondaryIcon')[0];
  134. secondaryIcon.src = Tools.list[toolName].secondary.icon;
  135. toolIconElem.classList.add("primaryIcon");
  136. }
  137. });
  138. },
  139. changeTool: function (oldToolName, newToolName) {
  140. var oldTool = document.getElementById("toolID-" + oldToolName);
  141. var newTool = document.getElementById("toolID-" + newToolName);
  142. if (oldTool) oldTool.classList.remove("curTool");
  143. if (newTool) newTool.classList.add("curTool");
  144. },
  145. toggle: function (toolName, name, icon) {
  146. var elem = document.getElementById("toolID-" + toolName);
  147. // Change secondary icon
  148. var primaryIcon = elem.getElementsByClassName("primaryIcon")[0];
  149. var secondaryIcon = elem.getElementsByClassName("secondaryIcon")[0];
  150. var primaryIconSrc = primaryIcon.src;
  151. var secondaryIconSrc = secondaryIcon.src;
  152. primaryIcon.src = secondaryIconSrc;
  153. secondaryIcon.src = primaryIconSrc;
  154. // Change primary icon
  155. elem.getElementsByClassName("tool-icon")[0].src = icon;
  156. elem.getElementsByClassName("tool-name")[0].textContent = Tools.i18n.t(name);
  157. },
  158. addStylesheet: function (href) {
  159. //Adds a css stylesheet to the html or svg document
  160. var link = document.createElement("link");
  161. link.href = href;
  162. link.rel = "stylesheet";
  163. link.type = "text/css";
  164. document.head.appendChild(link);
  165. },
  166. colorPresetTemplate: new Minitpl("#colorPresetSel .colorPresetButton"),
  167. addColorButton: function (button) {
  168. var setColor = Tools.setColor.bind(Tools, button.color);
  169. if (button.key) this.addShortcut(button.key, setColor);
  170. return this.colorPresetTemplate.add(function (elem) {
  171. elem.addEventListener("click", setColor);
  172. elem.id = "color_" + button.color.replace(/^#/, '');
  173. elem.style.backgroundColor = button.color;
  174. if (button.key) {
  175. elem.title = Tools.i18n.t("keyboard shortcut") + ": " + button.key;
  176. }
  177. });
  178. }
  179. };
  180. Tools.list = {}; // An array of all known tools. {"toolName" : {toolObject}}
  181. Tools.isBlocked = function toolIsBanned(tool) {
  182. if (tool.name.includes(",")) throw new Error("Tool Names must not contain a comma");
  183. return Tools.server_config.BLOCKED_TOOLS.includes(tool.name);
  184. };
  185. /**
  186. * Register a new tool, without touching the User Interface
  187. */
  188. Tools.register = function registerTool(newTool) {
  189. if (Tools.isBlocked(newTool)) return;
  190. if (newTool.name in Tools.list) {
  191. console.log("Tools.add: The tool '" + newTool.name + "' is already" +
  192. "in the list. Updating it...");
  193. }
  194. //Format the new tool correctly
  195. Tools.applyHooks(Tools.toolHooks, newTool);
  196. //Add the tool to the list
  197. Tools.list[newTool.name] = newTool;
  198. // Register the change handlers
  199. if (newTool.onSizeChange) Tools.sizeChangeHandlers.push(newTool.onSizeChange);
  200. //There may be pending messages for the tool
  201. var pending = Tools.pendingMessages[newTool.name];
  202. if (pending) {
  203. console.log("Drawing pending messages for '%s'.", newTool.name);
  204. var msg;
  205. while (msg = pending.shift()) {
  206. //Transmit the message to the tool (precising that it comes from the network)
  207. newTool.draw(msg, false);
  208. }
  209. }
  210. };
  211. /**
  212. * Add a new tool to the user interface
  213. */
  214. Tools.add = function (newTool) {
  215. if (Tools.isBlocked(newTool)) return;
  216. Tools.register(newTool);
  217. if (newTool.stylesheet) {
  218. Tools.HTML.addStylesheet(newTool.stylesheet);
  219. }
  220. //Add the tool to the GUI
  221. Tools.HTML.addTool(newTool.name, newTool.icon, newTool.iconHTML, newTool.shortcut, newTool.oneTouch);
  222. };
  223. Tools.change = function (toolName) {
  224. var newTool = Tools.list[toolName];
  225. var oldTool = Tools.curTool;
  226. if (!newTool) throw new Error("Trying to select a tool that has never been added!");
  227. if (newTool === oldTool) {
  228. if (newTool.secondary) {
  229. newTool.secondary.active = !newTool.secondary.active;
  230. var props = newTool.secondary.active ? newTool.secondary : newTool;
  231. Tools.HTML.toggle(newTool.name, props.name, props.icon);
  232. if (newTool.secondary.switch) newTool.secondary.switch();
  233. }
  234. return;
  235. }
  236. if (!newTool.oneTouch) {
  237. //Update the GUI
  238. var curToolName = (Tools.curTool) ? Tools.curTool.name : "";
  239. try {
  240. Tools.HTML.changeTool(curToolName, toolName);
  241. } catch (e) {
  242. console.error("Unable to update the GUI with the new tool. " + e);
  243. }
  244. Tools.svg.style.cursor = newTool.mouseCursor || "auto";
  245. Tools.board.title = Tools.i18n.t(newTool.helpText || "");
  246. //There is not necessarily already a curTool
  247. if (Tools.curTool !== null) {
  248. //It's useless to do anything if the new tool is already selected
  249. if (newTool === Tools.curTool) return;
  250. //Remove the old event listeners
  251. Tools.removeToolListeners(Tools.curTool);
  252. //Call the callbacks of the old tool
  253. Tools.curTool.onquit(newTool);
  254. }
  255. //Add the new event listeners
  256. Tools.addToolListeners(newTool);
  257. Tools.curTool = newTool;
  258. }
  259. //Call the start callback of the new tool
  260. newTool.onstart(oldTool);
  261. };
  262. Tools.addToolListeners = function addToolListeners(tool) {
  263. for (var event in tool.compiledListeners) {
  264. var listener = tool.compiledListeners[event];
  265. var target = listener.target || Tools.board;
  266. target.addEventListener(event, listener, { 'passive': false });
  267. }
  268. };
  269. Tools.removeToolListeners = function removeToolListeners(tool) {
  270. for (var event in tool.compiledListeners) {
  271. var listener = tool.compiledListeners[event];
  272. var target = listener.target || Tools.board;
  273. target.removeEventListener(event, listener);
  274. // also attempt to remove with capture = true in IE
  275. if (Tools.isIE) target.removeEventListener(event, listener, true);
  276. }
  277. };
  278. (function () {
  279. // Handle secondary tool switch with shift (key code 16)
  280. function handleShift(active, evt) {
  281. if (evt.keyCode === 16 && Tools.curTool.secondary && Tools.curTool.secondary.active !== active) {
  282. Tools.change(Tools.curTool.name);
  283. }
  284. }
  285. window.addEventListener("keydown", handleShift.bind(null, true));
  286. window.addEventListener("keyup", handleShift.bind(null, false));
  287. })();
  288. Tools.send = function (data, toolName) {
  289. toolName = toolName || Tools.curTool.name;
  290. var d = data;
  291. d.tool = toolName;
  292. Tools.applyHooks(Tools.messageHooks, d);
  293. var message = {
  294. "board": Tools.boardName,
  295. "data": d
  296. };
  297. Tools.socket.emit('broadcast', message);
  298. };
  299. Tools.drawAndSend = function (data, tool) {
  300. if (tool == null) tool = Tools.curTool;
  301. tool.draw(data, true);
  302. Tools.send(data, tool.name);
  303. };
  304. //Object containing the messages that have been received before the corresponding tool
  305. //is loaded. keys : the name of the tool, values : array of messages for this tool
  306. Tools.pendingMessages = {};
  307. // Send a message to the corresponding tool
  308. function messageForTool(message) {
  309. var name = message.tool,
  310. tool = Tools.list[name];
  311. if (tool) {
  312. Tools.applyHooks(Tools.messageHooks, message);
  313. tool.draw(message, false);
  314. } else {
  315. ///We received a message destinated to a tool that we don't have
  316. //So we add it to the pending messages
  317. if (!Tools.pendingMessages[name]) Tools.pendingMessages[name] = [message];
  318. else Tools.pendingMessages[name].push(message);
  319. }
  320. if (message.tool !== 'Hand' && message.deltax != null && message.deltay != null) {
  321. //this message has special info for the mover
  322. messageForTool({ tool: 'Hand', type: 'update', deltax: message.deltax || 0, deltay: message.deltay || 0, id: message.id });
  323. }
  324. }
  325. // Apply the function to all arguments by batches
  326. function batchCall(fn, args) {
  327. var BATCH_SIZE = 1024;
  328. if (args.length === 0) {
  329. return Promise.resolve();
  330. } else {
  331. var batch = args.slice(0, BATCH_SIZE);
  332. var rest = args.slice(BATCH_SIZE);
  333. return Promise.all(batch.map(fn))
  334. .then(function () {
  335. return new Promise(requestAnimationFrame);
  336. }).then(batchCall.bind(null, fn, rest));
  337. }
  338. }
  339. // Call messageForTool recursively on the message and its children
  340. function handleMessage(message) {
  341. //Check if the message is in the expected format
  342. if (!message.tool && !message._children) {
  343. console.error("Received a badly formatted message (no tool). ", message);
  344. }
  345. if (message.tool) messageForTool(message);
  346. if (message._children) return batchCall(handleMessage, message._children);
  347. else return Promise.resolve();
  348. }
  349. Tools.unreadMessagesCount = 0;
  350. Tools.newUnreadMessage = function () {
  351. Tools.unreadMessagesCount++;
  352. updateDocumentTitle();
  353. };
  354. window.addEventListener("focus", function () {
  355. Tools.unreadMessagesCount = 0;
  356. updateDocumentTitle();
  357. });
  358. function updateDocumentTitle() {
  359. document.title =
  360. (Tools.unreadMessagesCount ? '(' + Tools.unreadMessagesCount + ') ' : '') +
  361. Tools.boardName +
  362. " | WBO";
  363. }
  364. (function () {
  365. // Scroll and hash handling
  366. var scrollTimeout, lastStateUpdate = Date.now();
  367. window.addEventListener("scroll", function onScroll() {
  368. var scale = Tools.getScale();
  369. var x = document.documentElement.scrollLeft / scale,
  370. y = document.documentElement.scrollTop / scale;
  371. clearTimeout(scrollTimeout);
  372. scrollTimeout = setTimeout(function updateHistory() {
  373. var hash = '#' + (x | 0) + ',' + (y | 0) + ',' + Tools.getScale().toFixed(1);
  374. if (Date.now() - lastStateUpdate > 5000 && hash !== window.location.hash) {
  375. window.history.pushState({}, "", hash);
  376. lastStateUpdate = Date.now();
  377. } else {
  378. window.history.replaceState({}, "", hash);
  379. }
  380. }, 100);
  381. });
  382. function setScrollFromHash() {
  383. var coords = window.location.hash.slice(1).split(',');
  384. var x = coords[0] | 0;
  385. var y = coords[1] | 0;
  386. var scale = parseFloat(coords[2]);
  387. resizeCanvas({ x: x, y: y });
  388. Tools.setScale(scale);
  389. window.scrollTo(x * scale, y * scale);
  390. }
  391. window.addEventListener("hashchange", setScrollFromHash, false);
  392. window.addEventListener("popstate", setScrollFromHash, false);
  393. window.addEventListener("DOMContentLoaded", setScrollFromHash, false);
  394. })();
  395. function resizeCanvas(m) {
  396. //Enlarge the canvas whenever something is drawn near its border
  397. var x = m.x | 0, y = m.y | 0
  398. var MAX_BOARD_SIZE = Tools.server_config.MAX_BOARD_SIZE || 65536; // Maximum value for any x or y on the board
  399. if (x > Tools.svg.width.baseVal.value - 2000) {
  400. Tools.svg.width.baseVal.value = Math.min(x + 2000, MAX_BOARD_SIZE);
  401. }
  402. if (y > Tools.svg.height.baseVal.value - 2000) {
  403. Tools.svg.height.baseVal.value = Math.min(y + 2000, MAX_BOARD_SIZE);
  404. }
  405. }
  406. function updateUnreadCount(m) {
  407. if (document.hidden && ["child", "update"].indexOf(m.type) === -1) {
  408. Tools.newUnreadMessage();
  409. }
  410. }
  411. // List of hook functions that will be applied to messages before sending or drawing them
  412. Tools.messageHooks = [resizeCanvas, updateUnreadCount];
  413. Tools.scale = 1.0;
  414. var scaleTimeout = null;
  415. Tools.setScale = function setScale(scale) {
  416. var fullScale = Math.max(window.innerWidth, window.innerHeight) / Tools.server_config.MAX_BOARD_SIZE;
  417. var minScale = Math.max(0.1, fullScale);
  418. var maxScale = 10;
  419. if (isNaN(scale)) scale = 1;
  420. scale = Math.max(minScale, Math.min(maxScale, scale));
  421. Tools.svg.style.willChange = 'transform';
  422. Tools.svg.style.transform = 'scale(' + scale + ')';
  423. clearTimeout(scaleTimeout);
  424. scaleTimeout = setTimeout(function () {
  425. Tools.svg.style.willChange = 'auto';
  426. }, 1000);
  427. Tools.scale = scale;
  428. return scale;
  429. }
  430. Tools.getScale = function getScale() {
  431. return Tools.scale;
  432. }
  433. //List of hook functions that will be applied to tools before adding them
  434. Tools.toolHooks = [
  435. function checkToolAttributes(tool) {
  436. if (typeof (tool.name) !== "string") throw "A tool must have a name";
  437. if (typeof (tool.listeners) !== "object") {
  438. tool.listeners = {};
  439. }
  440. if (typeof (tool.onstart) !== "function") {
  441. tool.onstart = function () { };
  442. }
  443. if (typeof (tool.onquit) !== "function") {
  444. tool.onquit = function () { };
  445. }
  446. },
  447. function compileListeners(tool) {
  448. //compile listeners into compiledListeners
  449. var listeners = tool.listeners;
  450. //A tool may provide precompiled listeners
  451. var compiled = tool.compiledListeners || {};
  452. tool.compiledListeners = compiled;
  453. function compile(listener) { //closure
  454. return (function listen(evt) {
  455. var x = evt.pageX / Tools.getScale(),
  456. y = evt.pageY / Tools.getScale();
  457. return listener(x, y, evt, false);
  458. });
  459. }
  460. function compileTouch(listener) { //closure
  461. return (function touchListen(evt) {
  462. //Currently, we don't handle multitouch
  463. if (evt.changedTouches.length === 1) {
  464. //evt.preventDefault();
  465. var touch = evt.changedTouches[0];
  466. var x = touch.pageX / Tools.getScale(),
  467. y = touch.pageY / Tools.getScale();
  468. return listener(x, y, evt, true);
  469. }
  470. return true;
  471. });
  472. }
  473. function wrapUnsetHover(f, toolName) {
  474. return (function unsetHover(evt) {
  475. document.activeElement && document.activeElement.blur && document.activeElement.blur();
  476. return f(evt);
  477. });
  478. }
  479. if (listeners.press) {
  480. compiled["mousedown"] = wrapUnsetHover(compile(listeners.press), tool.name);
  481. compiled["touchstart"] = wrapUnsetHover(compileTouch(listeners.press), tool.name);
  482. }
  483. if (listeners.move) {
  484. compiled["mousemove"] = compile(listeners.move);
  485. compiled["touchmove"] = compileTouch(listeners.move);
  486. }
  487. if (listeners.release) {
  488. var release = compile(listeners.release),
  489. releaseTouch = compileTouch(listeners.release);
  490. compiled["mouseup"] = release;
  491. if (!Tools.isIE) compiled["mouseleave"] = release;
  492. compiled["touchleave"] = releaseTouch;
  493. compiled["touchend"] = releaseTouch;
  494. compiled["touchcancel"] = releaseTouch;
  495. }
  496. }
  497. ];
  498. Tools.applyHooks = function (hooks, object) {
  499. //Apply every hooks on the object
  500. hooks.forEach(function (hook) {
  501. hook(object);
  502. });
  503. };
  504. // Utility functions
  505. Tools.generateUID = function (prefix, suffix) {
  506. var uid = Date.now().toString(36); //Create the uids in chronological order
  507. uid += (Math.round(Math.random() * 36)).toString(36); //Add a random character at the end
  508. if (prefix) uid = prefix + uid;
  509. if (suffix) uid = uid + suffix;
  510. return uid;
  511. };
  512. Tools.createSVGElement = function createSVGElement(name, attrs) {
  513. var elem = document.createElementNS(Tools.svg.namespaceURI, name);
  514. if (typeof (attrs) !== "object") return elem;
  515. Object.keys(attrs).forEach(function (key, i) {
  516. elem.setAttributeNS(null, key, attrs[key]);
  517. });
  518. return elem;
  519. };
  520. Tools.positionElement = function (elem, x, y) {
  521. elem.style.top = y + "px";
  522. elem.style.left = x + "px";
  523. };
  524. Tools.colorPresets = [
  525. { color: "#001f3f", key: '1' },
  526. { color: "#FF4136", key: '2' },
  527. { color: "#0074D9", key: '3' },
  528. { color: "#FF851B", key: '4' },
  529. { color: "#FFDC00", key: '5' },
  530. { color: "#3D9970", key: '6' },
  531. { color: "#91E99B", key: '7' },
  532. { color: "#90468b", key: '8' },
  533. { color: "#7FDBFF", key: '9' },
  534. { color: "#AAAAAA", key: '0' },
  535. { color: "#E65194" }
  536. ];
  537. Tools.color_chooser = document.getElementById("chooseColor");
  538. Tools.setColor = function (color) {
  539. Tools.color_chooser.value = color;
  540. };
  541. Tools.getColor = (function color() {
  542. var color_index = (Math.random() * Tools.colorPresets.length) | 0;
  543. var initial_color = Tools.colorPresets[color_index].color;
  544. Tools.setColor(initial_color);
  545. return function () { return Tools.color_chooser.value; };
  546. })();
  547. Tools.colorPresets.forEach(Tools.HTML.addColorButton.bind(Tools.HTML));
  548. Tools.sizeChangeHandlers = [];
  549. Tools.setSize = (function size() {
  550. var chooser = document.getElementById("chooseSize");
  551. function update() {
  552. var size = Math.max(1, Math.min(50, chooser.value | 0));
  553. chooser.value = size;
  554. Tools.sizeChangeHandlers.forEach(function (handler) {
  555. handler(size);
  556. });
  557. }
  558. update();
  559. chooser.onchange = chooser.oninput = update;
  560. return function (value) {
  561. if (value !== null && value !== undefined) { chooser.value = value; update(); }
  562. return parseInt(chooser.value);
  563. };
  564. })();
  565. Tools.getSize = (function () { return Tools.setSize() });
  566. Tools.getOpacity = (function opacity() {
  567. var chooser = document.getElementById("chooseOpacity");
  568. var opacityIndicator = document.getElementById("opacityIndicator");
  569. function update() {
  570. opacityIndicator.setAttribute("opacity", chooser.value);
  571. }
  572. update();
  573. chooser.onchange = chooser.oninput = update;
  574. return function () {
  575. return Math.max(0.1, Math.min(1, chooser.value));
  576. };
  577. })();
  578. //Scale the canvas on load
  579. Tools.svg.width.baseVal.value = document.body.clientWidth;
  580. Tools.svg.height.baseVal.value = document.body.clientHeight;
  581. /**
  582. What does a "tool" object look like?
  583. newtool = {
  584. "name" : "SuperTool",
  585. "listeners" : {
  586. "press" : function(x,y,evt){...},
  587. "move" : function(x,y,evt){...},
  588. "release" : function(x,y,evt){...},
  589. },
  590. "draw" : function(data, isLocal){
  591. //Print the data on Tools.svg
  592. },
  593. "onstart" : function(oldTool){...},
  594. "onquit" : function(newTool){...},
  595. "stylesheet" : "style.css",
  596. }
  597. */