1 /*
  2     Copyright 2008-2014
  3         Matthias Ehmann,
  4         Michael Gerhaeuser,
  5         Carsten Miller,
  6         Bianca Valentin,
  7         Alfred Wassermann,
  8         Peter Wilfahrt
  9 
 10     This file is part of JSXGraph.
 11 
 12     JSXGraph is free software dual licensed under the GNU LGPL or MIT License.
 13 
 14     You can redistribute it and/or modify it under the terms of the
 15 
 16       * GNU Lesser General Public License as published by
 17         the Free Software Foundation, either version 3 of the License, or
 18         (at your option) any later version
 19       OR
 20       * MIT License: https://github.com/jsxgraph/jsxgraph/blob/master/LICENSE.MIT
 21 
 22     JSXGraph is distributed in the hope that it will be useful,
 23     but WITHOUT ANY WARRANTY; without even the implied warranty of
 24     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 25     GNU Lesser General Public License for more details.
 26 
 27     You should have received a copy of the GNU Lesser General Public License and
 28     the MIT License along with JSXGraph. If not, see <http://www.gnu.org/licenses/>
 29     and <http://opensource.org/licenses/MIT/>.
 30  */
 31 
 32 
 33 /*global JXG: true, document:true, jQuery:true, define: true, window: true*/
 34 /*jslint nomen: true, plusplus: true*/
 35 
 36 /* depends:
 37  jxg
 38  utils/env
 39  utils/type
 40  base/board
 41  reader/file
 42  options
 43  renderer/svg
 44  renderer/vml
 45  renderer/canvas
 46  renderer/no
 47  */
 48 
 49 /**
 50  * @fileoverview The JSXGraph object is defined in this file. JXG.JSXGraph controls all boards.
 51  * It has methods to create, save, load and free boards. Additionally some helper functions are
 52  * defined in this file directly in the JXG namespace.
 53  * @version 0.99
 54  */
 55 
 56 define([
 57     'jxg', 'utils/env', 'utils/type', 'base/board', 'reader/file', 'options',
 58     'renderer/svg', 'renderer/vml', 'renderer/canvas', 'renderer/no'
 59 ], function (JXG, Env, Type, Board, FileReader, Options, SVGRenderer, VMLRenderer, CanvasRenderer, NoRenderer) {
 60 
 61     "use strict";
 62 
 63     /**
 64      * Constructs a new JSXGraph singleton object.
 65      * @class The JXG.JSXGraph singleton stores all properties required
 66      * to load, save, create and free a board.
 67      */
 68     JXG.JSXGraph = {
 69         /**
 70          * Stores the renderer that is used to draw the boards.
 71          * @type String
 72          */
 73         rendererType: (function () {
 74             Options.renderer = 'no';
 75 
 76             if (Env.supportsVML()) {
 77                 Options.renderer = 'vml';
 78                 // Ok, this is some real magic going on here. IE/VML always was so
 79                 // terribly slow, except in one place: Examples placed in a moodle course
 80                 // was almost as fast as in other browsers. So i grabbed all the css and
 81                 // lib scripts from our moodle, added them to a jsxgraph example and it
 82                 // worked. next step was to strip all the css/lib code which didn't affect
 83                 // the VML update speed. The following five lines are what was left after
 84                 // the last step and yes - it basically does nothing but reads two
 85                 // properties of document.body on every mouse move. why? we don't know. if
 86                 // you know, please let us know.
 87                 //
 88                 // If we want to use the strict mode we have to refactor this a little bit. Let's
 89                 // hope the magic isn't gone now. Anywho... it's only useful in old versions of IE
 90                 // which should not be used anymore.
 91                 document.onmousemove = function () {
 92                     var t;
 93 
 94                     if (document.body) {
 95                         t = document.body.scrollLeft;
 96                         t += document.body.scrollTop;
 97                     }
 98 
 99                     return t;
100                 };
101             }
102 
103             if (Env.supportsCanvas()) {
104                 Options.renderer = 'canvas';
105             }
106 
107             if (Env.supportsSVG()) {
108                 Options.renderer = 'svg';
109             }
110 
111             // we are inside node
112             if (Env.isNode() && Env.supportsCanvas()) {
113                 Options.renderer = 'canvas';
114             }
115 
116             if (Env.isNode() || Options.renderer === 'no') {
117                 Options.text.display = 'internal';
118                 Options.infobox.display = 'internal';
119             }
120 
121             return Options.renderer;
122         }()),
123 
124         initRenderer: function (box, dim, doc) {
125             var boxid, renderer;
126 
127             // Former version:
128             // doc = doc || document
129             if ((!Type.exists(doc) || doc === false) && typeof document === 'object') {
130                 doc = document;
131             }
132 
133             if (typeof doc === 'object' && box !== null) {
134                 boxid = doc.getElementById(box);
135 
136                 // Remove everything from the container before initializing the renderer and the board
137                 while (boxid.firstChild) {
138                     boxid.removeChild(boxid.firstChild);
139                 }
140             } else {
141                 boxid = box;
142             }
143 
144             // create the renderer
145             if (Options.renderer === 'svg') {
146                 renderer = new SVGRenderer(boxid, dim);
147             } else if (Options.renderer === 'vml') {
148                 renderer = new VMLRenderer(boxid);
149             } else if (Options.renderer === 'canvas') {
150                 renderer = new CanvasRenderer(boxid, dim);
151             } else {
152                 renderer = new NoRenderer();
153             }
154 
155             return renderer;
156         },
157 
158         /**
159          * Initialise a new board.
160          * @param {String} box Html-ID to the Html-element in which the board is painted.
161          * @param {Object} attributes An object that sets some of the board properties. Most of these properties can be set via JXG.Options. Valid properties are
162          * <ul>
163          *     <li><b>boundingbox</b>: An array containing four numbers describing the left, top, right and bottom boundary of the board in user coordinates</li>
164          *     <li><b>keepaspectratio</b>: If <tt>true</tt>, the bounding box is adjusted to the same aspect ratio as the aspect ratio of the div containing the board.</li>
165          *     <li><b>showCopyright</b>: Show the copyright string in the top left corner.</li>
166          *     <li><b>showNavigation</b>: Show the navigation buttons in the bottom right corner.</li>
167          *     <li><b>zoom</b>: Allow the user to zoom with the mouse wheel or the two-fingers-zoom gesture.</li>
168          *     <li><b>pan</b>: Allow the user to pan with shift+drag mouse or two-fingers-pan gesture.</li>
169          *     <li><b>axis</b>: If set to true, show the axis. Can also be set to an object that is given to both axes as an attribute object.</li>
170          *     <li><b>grid</b>: If set to true, shows the grid. Can also bet set to an object that is given to the grid as its attribute object.</li>
171          *     <li><b>registerEvents</b>: Register mouse / touch events.</li>
172          * </ul>
173          * @returns {JXG.Board} Reference to the created board.
174          */
175         initBoard: function (box, attributes) {
176             var originX, originY, unitX, unitY,
177                 renderer,
178                 w, h, dimensions,
179                 bbox, attr, axattr,
180                 board;
181 
182             attributes = attributes || {};
183 
184             // merge attributes
185             attr = Type.copyAttributes(attributes, Options, 'board');
186             attr.zoom = Type.copyAttributes(attr, Options, 'board', 'zoom');
187             attr.pan = Type.copyAttributes(attr, Options, 'board', 'pan');
188 
189             dimensions = Env.getDimensions(box, attr.document);
190 
191             if (attr.unitx || attr.unity) {
192                 originX = Type.def(attr.originx, 150);
193                 originY = Type.def(attr.originy, 150);
194                 unitX = Type.def(attr.unitx, 50);
195                 unitY = Type.def(attr.unity, 50);
196             } else {
197                 bbox = attr.boundingbox;
198                 w = parseInt(dimensions.width, 10);
199                 h = parseInt(dimensions.height, 10);
200 
201                 if (attr.keepaspectratio) {
202                     /*
203                      * If the boundingbox attribute is given and the ratio of height and width of the
204                      * sides defined by the bounding box and the ratio of the dimensions of the div tag
205                      * which contains the board do not coincide, then the smaller side is chosen.
206                      */
207                     unitX = w / (bbox[2] - bbox[0]);
208                     unitY = h / (bbox[1] - bbox[3]);
209 
210                     if (Math.abs(unitX) < Math.abs(unitY)) {
211                         unitY = Math.abs(unitX) * unitY / Math.abs(unitY);
212                     } else {
213                         unitX = Math.abs(unitY) * unitX / Math.abs(unitX);
214                     }
215                 } else {
216                     unitX = w / (bbox[2] - bbox[0]);
217                     unitY = h / (bbox[1] - bbox[3]);
218                 }
219                 originX = -unitX * bbox[0];
220                 originY = unitY * bbox[1];
221             }
222 
223             renderer = this.initRenderer(box, dimensions, attr.document);
224 
225             // create the board
226             board = new Board(box, renderer, attr.id, [originX, originY], attr.zoomfactor * attr.zoomx, attr.zoomfactor * attr.zoomy, unitX, unitY, dimensions.width, dimensions.height, attr);
227 
228             JXG.boards[board.id] = board;
229 
230             board.keepaspectratio = attr.keepaspectratio;
231             board.resizeContainer(dimensions.width, dimensions.height, true, true);
232 
233             // create elements like axes, grid, navigation, ...
234             board.suspendUpdate();
235             board.initInfobox();
236 
237             if (attr.axis) {
238                 axattr = typeof attr.axis === 'object' ? attr.axis : {ticks: {drawZero: true}};
239                 board.defaultAxes = {};
240                 board.defaultAxes.x = board.create('axis', [[0, 0], [1, 0]], axattr);
241                 board.defaultAxes.y = board.create('axis', [[0, 0], [0, 1]], axattr);
242             }
243 
244             if (attr.grid) {
245                 board.create('grid', [], (typeof attr.grid === 'object' ? attr.grid : {}));
246             }
247 
248             board.renderer.drawZoomBar(board);
249             board.unsuspendUpdate();
250 
251             return board;
252         },
253 
254         /**
255          * Load a board from a file containing a construction made with either GEONExT,
256          * Intergeo, Geogebra, or Cinderella.
257          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
258          * @param {String} file base64 encoded string.
259          * @param {String} format containing the file format: 'Geonext' or 'Intergeo'.
260          * @param {Object} [attributes]
261          * @returns {JXG.Board} Reference to the created board.
262          * @see JXG.FileReader
263          * @see JXG.GeonextReader
264          * @see JXG.GeogebraReader
265          * @see JXG.IntergeoReader
266          * @see JXG.CinderellaReader
267          */
268         loadBoardFromFile: function (box, file, format, attributes, callback) {
269             var attr, renderer, board, dimensions;
270 
271             attributes = attributes || {};
272 
273             // merge attributes
274             attr = Type.copyAttributes(attributes, Options, 'board');
275             attr.zoom = Type.copyAttributes(attributes, Options, 'board', 'zoom');
276             attr.pan = Type.copyAttributes(attributes, Options, 'board', 'pan');
277 
278             dimensions = Env.getDimensions(box, attr.document);
279             renderer = this.initRenderer(box, dimensions, attr.document);
280 
281             /* User default parameters, in parse* the values in the gxt files are submitted to board */
282             board = new Board(box, renderer, '', [150, 150], 1, 1, 50, 50, dimensions.width, dimensions.height, attr);
283             board.initInfobox();
284             board.resizeContainer(dimensions.width, dimensions.height, true, true);
285 
286             FileReader.parseFileContent(file, board, format, true, callback);
287 
288             board.renderer.drawZoomBar(board);
289             JXG.boards[board.id] = board;
290 
291             return board;
292         },
293 
294         /**
295          * Load a board from a base64 encoded string containing a construction made with either GEONExT,
296          * Intergeo, Geogebra, or Cinderella.
297          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
298          * @param {String} string base64 encoded string.
299          * @param {String} format containing the file format: 'Geonext' or 'Intergeo'.
300          * @param {Object} [attributes]
301          * @returns {JXG.Board} Reference to the created board.
302          * @see JXG.FileReader
303          * @see JXG.GeonextReader
304          * @see JXG.GeogebraReader
305          * @see JXG.IntergeoReader
306          * @see JXG.CinderellaReader
307          */
308         loadBoardFromString: function (box, string, format, attributes, callback) {
309             var attr, renderer, dimensions, board;
310 
311             attributes = attributes || {};
312 
313             // merge attributes
314             attr = Type.copyAttributes(attributes, Options, 'board');
315             attr.zoom = Type.copyAttributes(attributes, Options, 'board', 'zoom');
316             attr.pan = Type.copyAttributes(attributes, Options, 'board', 'pan');
317 
318             dimensions = Env.getDimensions(box, attr.document);
319             renderer = this.initRenderer(box, dimensions, attr.document);
320 
321             /* User default parameters, in parse* the values in the gxt files are submitted to board */
322             board = new Board(box, renderer, '', [150, 150], 1.0, 1.0, 50, 50, dimensions.width, dimensions.height, attr);
323             board.initInfobox();
324             board.resizeContainer(dimensions.width, dimensions.height, true, true);
325 
326             FileReader.parseString(string, board, format, true, callback);
327 
328             board.renderer.drawZoomBar(board);
329             JXG.boards[board.id] = board;
330 
331             return board;
332         },
333 
334         /**
335          * Delete a board and all its contents.
336          * @param {JXG.Board,String} board HTML-ID to the DOM-element in which the board is drawn.
337          */
338         freeBoard: function (board) {
339             var el;
340 
341             if (typeof board === 'string') {
342                 board = JXG.boards[board];
343             }
344 
345             board.removeEventHandlers();
346             board.suspendUpdate();
347 
348             // Remove all objects from the board.
349             for (el in board.objects) {
350                 if (board.objects.hasOwnProperty(el)) {
351                     board.objects[el].remove();
352                 }
353             }
354 
355             // Remove all the other things, left on the board, XHTML save
356             while (board.containerObj.firstChild) {
357                 board.containerObj.removeChild(board.containerObj.firstChild);
358             }
359 
360             // Tell the browser the objects aren't needed anymore
361             for (el in board.objects) {
362                 if (board.objects.hasOwnProperty(el)) {
363                     delete board.objects[el];
364                 }
365             }
366 
367             // Free the renderer and the algebra object
368             delete board.renderer;
369 
370             // clear the creator cache
371             board.jc.creator.clearCache();
372             delete board.jc;
373 
374             // Finally remove the board itself from the boards array
375             delete JXG.boards[board.id];
376         },
377 
378         /**
379          * @deprecated Use JXG#registerElement
380          * @param element
381          * @param creator
382          */
383         registerElement: function (element, creator) {
384             JXG.registerElement(element, creator);
385         },
386 
387         /**
388          * @deprecated
389          * @param element
390          */
391         unregisterElement: function (element) {
392             throw new Error('Unimplemented');
393         }
394     };
395 
396     // JessieScript/JessieCode startup: Search for script tags of type text/jessiescript and interprete them.
397     if (Env.isBrowser && typeof window === 'object' && typeof document === 'object') {
398         Env.addEvent(window, 'load', function () {
399             var type, i, j, div, id, board, width, height, bbox, axis, grid, code,
400                 scripts = document.getElementsByTagName('script'),
401                 init = function (code, type, bbox) {
402                     var board = JXG.JSXGraph.initBoard(id, {boundingbox: bbox, keepaspectratio: true, grid: grid, axis: axis, showReload: true});
403 
404                     if (type.toLowerCase().indexOf('script') > -1) {
405                         board.construct(code);
406                     } else {
407                         try {
408                             board.jc.parse(code);
409                         } catch (e2) {
410                             JXG.debug(e2);
411                         }
412                     }
413 
414                     return board;
415                 },
416                 makeReload = function (board, code, type, bbox) {
417                     return function () {
418                         var newBoard;
419 
420                         JXG.JSXGraph.freeBoard(board);
421                         newBoard = init(code, type, bbox);
422                         newBoard.reload = makeReload(newBoard, code, type, bbox);
423                     };
424                 };
425 
426             for (i = 0; i < scripts.length; i++) {
427                 type = scripts[i].getAttribute('type', false);
428 
429                 if (Type.exists(type) && (type.toLowerCase() === 'text/jessiescript' || type.toLowerCase() === 'jessiescript' || type.toLowerCase() === 'text/jessiecode' || type.toLowerCase() === 'jessiecode')) {
430                     width = scripts[i].getAttribute('width', false) || '500px';
431                     height = scripts[i].getAttribute('height', false) || '500px';
432                     bbox = scripts[i].getAttribute('boundingbox', false) || '-5, 5, 5, -5';
433                     id = scripts[i].getAttribute('container', false);
434 
435                     bbox = bbox.split(',');
436                     if (bbox.length !== 4) {
437                         bbox = [-5, 5, 5, -5];
438                     } else {
439                         for (j = 0; j < bbox.length; j++) {
440                             bbox[j] = parseFloat(bbox[j]);
441                         }
442                     }
443                     axis = Type.str2Bool(scripts[i].getAttribute('axis', false) || 'false');
444                     grid = Type.str2Bool(scripts[i].getAttribute('grid', false) || 'false');
445 
446                     if (!Type.exists(id)) {
447                         id = 'jessiescript_autgen_jxg_' + i;
448                         div = document.createElement('div');
449                         div.setAttribute('id', id);
450                         div.setAttribute('style', 'width:' + width + '; height:' + height + '; float:left');
451                         div.setAttribute('class', 'jxgbox');
452                         try {
453                             document.body.insertBefore(div, scripts[i]);
454                         } catch (e) {
455                             // there's probably jquery involved...
456                             if (typeof jQuery === 'object') {
457                                 jQuery(div).insertBefore(scripts[i]);
458                             }
459                         }
460                     } else {
461                         div = document.getElementById(id);
462                     }
463 
464                     if (document.getElementById(id)) {
465                         code = scripts[i].innerHTML;
466                         code = code.replace(/<!\[CDATA\[/g, '').replace(/\]\]>/g, '');
467                         scripts[i].innerHTML = code;
468 
469                         board = init(code, type, bbox);
470                         board.reload = makeReload(board, code, type, bbox);
471                     } else {
472                         JXG.debug('JSXGraph: Apparently the div injection failed. Can\'t create a board, sorry.');
473                     }
474                 }
475             }
476         }, window);
477     }
478 
479     return JXG.JSXGraph;
480 });
481