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 20KB

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