1 /*
  2     Copyright 2008-2013
  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.98
 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) {
125             var boxid, renderer;
126 
127             if (typeof document === 'object' && box !== null) {
128                 boxid = document.getElementById(box);
129 
130                 // Remove everything from the container before initializing the renderer and the board
131                 while (boxid.firstChild) {
132                     boxid.removeChild(boxid.firstChild);
133                 }
134             } else {
135                 boxid = box;
136             }
137 
138             // create the renderer
139             if (Options.renderer === 'svg') {
140                 renderer = new SVGRenderer(boxid, dim);
141             } else if (Options.renderer === 'vml') {
142                 renderer = new VMLRenderer(boxid);
143             } else if (Options.renderer === 'canvas') {
144                 renderer = new CanvasRenderer(boxid, dim);
145             } else {
146                 renderer = new NoRenderer();
147             }
148 
149             return renderer;
150         },
151 
152         /**
153          * Initialise a new board.
154          * @param {String} box Html-ID to the Html-element in which the board is painted.
155          * @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
156          * <ul>
157          *     <li><b>boundingbox</b>: An array containing four numbers describing the left, top, right and bottom boundary of the board in user coordinates</li>
158          *     <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>
159          *     <li><b>showCopyright</b>: Show the copyright string in the top left corner.</li>
160          *     <li><b>showNavigation</b>: Show the navigation buttons in the bottom right corner.</li>
161          *     <li><b>zoom</b>: Allow the user to zoom with the mouse wheel or the two-fingers-zoom gesture.</li>
162          *     <li><b>pan</b>: Allow the user to pan with shift+drag mouse or two-fingers-pan gesture.</li>
163          *     <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>
164          *     <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>
165          *     <li><b>registerEvents</b>: Register mouse / touch events.</li>
166          * </ul>
167          * @returns {JXG.Board} Reference to the created board.
168          */
169         initBoard: function (box, attributes) {
170             var originX, originY, unitX, unitY,
171                 renderer,
172                 w, h, dimensions,
173                 bbox, attr, axattr,
174                 board;
175 
176             dimensions = Env.getDimensions(box);
177             attributes = attributes || {};
178 
179             // merge attributes
180             attr = Type.copyAttributes(attributes, Options, 'board');
181             attr.zoom = Type.copyAttributes(attr, Options, 'board', 'zoom');
182             attr.pan = Type.copyAttributes(attr, Options, 'board', 'pan');
183 
184             if (attr.unitx || attr.unity) {
185                 originX = Type.def(attr.originx, 150);
186                 originY = Type.def(attr.originy, 150);
187                 unitX = Type.def(attr.unitx, 50);
188                 unitY = Type.def(attr.unity, 50);
189             } else {
190                 bbox = attr.boundingbox;
191                 w = parseInt(dimensions.width, 10);
192                 h = parseInt(dimensions.height, 10);
193 
194                 if (attr.keepaspectratio) {
195                     /*
196                      * If the boundingbox attribute is given and the ratio of height and width of the
197                      * sides defined by the bounding box and the ratio of the dimensions of the div tag
198                      * which contains the board do not coincide, then the smaller side is chosen.
199                      */
200                     unitX = w / (bbox[2] - bbox[0]);
201                     unitY = h / (bbox[1] - bbox[3]);
202 
203                     if (Math.abs(unitX) < Math.abs(unitY)) {
204                         unitY = Math.abs(unitX) * unitY / Math.abs(unitY);
205                     } else {
206                         unitX = Math.abs(unitY) * unitX / Math.abs(unitX);
207                     }
208                 } else {
209                     unitX = w / (bbox[2] - bbox[0]);
210                     unitY = h / (bbox[1] - bbox[3]);
211                 }
212                 originX = -unitX * bbox[0];
213                 originY = unitY * bbox[1];
214             }
215 
216             renderer = this.initRenderer(box, dimensions);
217 
218             // create the board
219             board = new Board(box, renderer, '', [originX, originY], attr.zoomfactor * attr.zoomx, attr.zoomfactor * attr.zoomy, unitX, unitY, dimensions.width, dimensions.height, attr);
220 
221             // this is deprecated, but we'll keep it for now until everything is migrated
222             JXG.boards[board.id] = board;
223 
224             // the new board storage
225             JXG.boards[board.id] = board;
226 
227             board.resizeContainer(dimensions.width, dimensions.height, true);
228 
229             // create elements like axes, grid, navigation, ...
230             board.suspendUpdate();
231             board.initInfobox();
232 
233             if (attr.axis) {
234                 axattr = typeof attr.axis === 'object' ? attr.axis : {ticks: {drawZero: true}};
235                 board.defaultAxes = {};
236                 board.defaultAxes.x = board.create('axis', [[0, 0], [1, 0]], axattr);
237                 board.defaultAxes.y = board.create('axis', [[0, 0], [0, 1]], axattr);
238             }
239 
240             if (attr.grid) {
241                 board.create('grid', [], (typeof attr.grid === 'object' ? attr.grid : {}));
242             }
243 
244             if (attr.shownavigation) {
245                 board.renderer.drawZoomBar(board);
246             }
247             board.unsuspendUpdate();
248 
249             return board;
250         },
251 
252         /**
253          * Load a board from a file containing a construction made with either GEONExT,
254          * Intergeo, Geogebra, or Cinderella.
255          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
256          * @param {String} file base64 encoded string.
257          * @param {String} format containing the file format: 'Geonext' or 'Intergeo'.
258          * @param {Object} [attributes]
259          * @returns {JXG.Board} Reference to the created board.
260          * @see JXG.FileReader
261          * @see JXG.GeonextReader
262          * @see JXG.GeogebraReader
263          * @see JXG.IntergeoReader
264          * @see JXG.CinderellaReader
265          */
266         loadBoardFromFile: function (box, file, format, attributes, callback) {
267             var attr, renderer, board, dimensions;
268 
269             dimensions = Env.getDimensions(box);
270             renderer = this.initRenderer(box, dimensions);
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             /* User default parameters, in parse* the values in the gxt files are submitted to board */
279             board = new Board(box, renderer, '', [150, 150], 1, 1, 50, 50, dimensions.width, dimensions.height, attr);
280             board.initInfobox();
281             board.resizeContainer(dimensions.width, dimensions.height, true);
282 
283             FileReader.parseFileContent(file, board, format, true, callback);
284 
285             if (board.attr.shownavigation) {
286                 board.renderer.drawZoomBar(board);
287             }
288 
289             JXG.boards[board.id] = board;
290             return board;
291         },
292 
293         /**
294          * Load a board from a base64 encoded string containing a construction made with either GEONExT,
295          * Intergeo, Geogebra, or Cinderella.
296          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
297          * @param {String} string base64 encoded string.
298          * @param {String} format containing the file format: 'Geonext' or 'Intergeo'.
299          * @param {Object} [attributes]
300          * @returns {JXG.Board} Reference to the created board.
301          * @see JXG.FileReader
302          * @see JXG.GeonextReader
303          * @see JXG.GeogebraReader
304          * @see JXG.IntergeoReader
305          * @see JXG.CinderellaReader
306          */
307         loadBoardFromString: function (box, string, format, attributes, callback) {
308             var attr, renderer, dimensions, board;
309 
310             dimensions = Env.getDimensions(box);
311             renderer = this.initRenderer(box, dimensions);
312             attributes = attributes || {};
313 
314             // merge attributes
315             attr = Type.copyAttributes(attributes, Options, 'board');
316             attr.zoom = Type.copyAttributes(attributes, Options, 'board', 'zoom');
317             attr.pan = Type.copyAttributes(attributes, Options, 'board', 'pan');
318 
319             /* User default parameters, in parse* the values in the gxt files are submitted to board */
320             board = new Board(box, renderer, '', [150, 150], 1.0, 1.0, 50, 50, dimensions.width, dimensions.height, attr);
321             board.initInfobox();
322             board.resizeContainer(dimensions.width, dimensions.height, true);
323 
324             FileReader.parseString(string, board, format, true, callback);
325 
326             if (board.attr.shownavigation) {
327                 board.renderer.drawZoomBar(board);
328             }
329 
330             JXG.boards[board.id] = board;
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 interpret 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