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             doc = doc || document;
128             if (typeof doc === 'object' && box !== null) {
129                 boxid = doc.getElementById(box);
130 
131                 // Remove everything from the container before initializing the renderer and the board
132                 while (boxid.firstChild) {
133                     boxid.removeChild(boxid.firstChild);
134                 }
135             } else {
136                 boxid = box;
137             }
138 
139             // create the renderer
140             if (Options.renderer === 'svg') {
141                 renderer = new SVGRenderer(boxid, dim);
142             } else if (Options.renderer === 'vml') {
143                 renderer = new VMLRenderer(boxid);
144             } else if (Options.renderer === 'canvas') {
145                 renderer = new CanvasRenderer(boxid, dim);
146             } else {
147                 renderer = new NoRenderer();
148             }
149 
150             return renderer;
151         },
152 
153         /**
154          * Initialise a new board.
155          * @param {String} box Html-ID to the Html-element in which the board is painted.
156          * @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
157          * <ul>
158          *     <li><b>boundingbox</b>: An array containing four numbers describing the left, top, right and bottom boundary of the board in user coordinates</li>
159          *     <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>
160          *     <li><b>showCopyright</b>: Show the copyright string in the top left corner.</li>
161          *     <li><b>showNavigation</b>: Show the navigation buttons in the bottom right corner.</li>
162          *     <li><b>zoom</b>: Allow the user to zoom with the mouse wheel or the two-fingers-zoom gesture.</li>
163          *     <li><b>pan</b>: Allow the user to pan with shift+drag mouse or two-fingers-pan gesture.</li>
164          *     <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>
165          *     <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>
166          *     <li><b>registerEvents</b>: Register mouse / touch events.</li>
167          * </ul>
168          * @returns {JXG.Board} Reference to the created board.
169          */
170         initBoard: function (box, attributes) {
171             var originX, originY, unitX, unitY,
172                 renderer,
173                 w, h, dimensions,
174                 bbox, attr, axattr,
175                 board;
176 
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             dimensions = Env.getDimensions(box, attr.document);
185 
186             if (attr.unitx || attr.unity) {
187                 originX = Type.def(attr.originx, 150);
188                 originY = Type.def(attr.originy, 150);
189                 unitX = Type.def(attr.unitx, 50);
190                 unitY = Type.def(attr.unity, 50);
191             } else {
192                 bbox = attr.boundingbox;
193                 w = parseInt(dimensions.width, 10);
194                 h = parseInt(dimensions.height, 10);
195 
196                 if (attr.keepaspectratio) {
197                     /*
198                      * If the boundingbox attribute is given and the ratio of height and width of the
199                      * sides defined by the bounding box and the ratio of the dimensions of the div tag
200                      * which contains the board do not coincide, then the smaller side is chosen.
201                      */
202                     unitX = w / (bbox[2] - bbox[0]);
203                     unitY = h / (bbox[1] - bbox[3]);
204 
205                     if (Math.abs(unitX) < Math.abs(unitY)) {
206                         unitY = Math.abs(unitX) * unitY / Math.abs(unitY);
207                     } else {
208                         unitX = Math.abs(unitY) * unitX / Math.abs(unitX);
209                     }
210                 } else {
211                     unitX = w / (bbox[2] - bbox[0]);
212                     unitY = h / (bbox[1] - bbox[3]);
213                 }
214                 originX = -unitX * bbox[0];
215                 originY = unitY * bbox[1];
216             }
217 
218             renderer = this.initRenderer(box, dimensions, attr.document);
219 
220             // create the board
221             board = new Board(box, renderer, '', [originX, originY], attr.zoomfactor * attr.zoomx, attr.zoomfactor * attr.zoomy, unitX, unitY, dimensions.width, dimensions.height, attr);
222 
223             // this is deprecated, but we'll keep it for now until everything is migrated
224             JXG.boards[board.id] = board;
225 
226             // the new board storage
227             JXG.boards[board.id] = board;
228 
229             board.resizeContainer(dimensions.width, dimensions.height, true);
230 
231             // create elements like axes, grid, navigation, ...
232             board.suspendUpdate();
233             board.initInfobox();
234 
235             if (attr.axis) {
236                 axattr = typeof attr.axis === 'object' ? attr.axis : {ticks: {drawZero: true}};
237                 board.defaultAxes = {};
238                 board.defaultAxes.x = board.create('axis', [[0, 0], [1, 0]], axattr);
239                 board.defaultAxes.y = board.create('axis', [[0, 0], [0, 1]], axattr);
240             }
241 
242             if (attr.grid) {
243                 board.create('grid', [], (typeof attr.grid === 'object' ? attr.grid : {}));
244             }
245 
246             board.renderer.drawZoomBar(board);
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             attributes = attributes || {};
270 
271             // merge attributes
272             attr = Type.copyAttributes(attributes, Options, 'board');
273             attr.zoom = Type.copyAttributes(attributes, Options, 'board', 'zoom');
274             attr.pan = Type.copyAttributes(attributes, Options, 'board', 'pan');
275 
276             dimensions = Env.getDimensions(box, attr.document);
277             renderer = this.initRenderer(box, dimensions, attr.document);
278 
279             /* User default parameters, in parse* the values in the gxt files are submitted to board */
280             board = new Board(box, renderer, '', [150, 150], 1, 1, 50, 50, dimensions.width, dimensions.height, attr);
281             board.initInfobox();
282             board.resizeContainer(dimensions.width, dimensions.height, true);
283 
284             FileReader.parseFileContent(file, board, format, true, callback);
285 
286             board.renderer.drawZoomBar(board);
287             JXG.boards[board.id] = board;
288             
289             return board;
290         },
291 
292         /**
293          * Load a board from a base64 encoded string containing a construction made with either GEONExT,
294          * Intergeo, Geogebra, or Cinderella.
295          * @param {String} box HTML-ID to the HTML-element in which the board is painted.
296          * @param {String} string base64 encoded string.
297          * @param {String} format containing the file format: 'Geonext' or 'Intergeo'.
298          * @param {Object} [attributes]
299          * @returns {JXG.Board} Reference to the created board.
300          * @see JXG.FileReader
301          * @see JXG.GeonextReader
302          * @see JXG.GeogebraReader
303          * @see JXG.IntergeoReader
304          * @see JXG.CinderellaReader
305          */
306         loadBoardFromString: function (box, string, format, attributes, callback) {
307             var attr, renderer, dimensions, board;
308 
309             attributes = attributes || {};
310 
311             // merge attributes
312             attr = Type.copyAttributes(attributes, Options, 'board');
313             attr.zoom = Type.copyAttributes(attributes, Options, 'board', 'zoom');
314             attr.pan = Type.copyAttributes(attributes, Options, 'board', 'pan');
315 
316             dimensions = Env.getDimensions(box, attr.document);
317             renderer = this.initRenderer(box, dimensions, attr.document);
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             board.renderer.drawZoomBar(board);
327             JXG.boards[board.id] = board;
328             
329             return board;
330         },
331 
332         /**
333          * Delete a board and all its contents.
334          * @param {JXG.Board,String} board HTML-ID to the DOM-element in which the board is drawn.
335          */
336         freeBoard: function (board) {
337             var el;
338 
339             if (typeof board === 'string') {
340                 board = JXG.boards[board];
341             }
342 
343             board.removeEventHandlers();
344             board.suspendUpdate();
345 
346             // Remove all objects from the board.
347             for (el in board.objects) {
348                 if (board.objects.hasOwnProperty(el)) {
349                     board.objects[el].remove();
350                 }
351             }
352 
353             // Remove all the other things, left on the board, XHTML save
354             while (board.containerObj.firstChild) {
355                 board.containerObj.removeChild(board.containerObj.firstChild);
356             }
357 
358             // Tell the browser the objects aren't needed anymore
359             for (el in board.objects) {
360                 if (board.objects.hasOwnProperty(el)) {
361                     delete board.objects[el];
362                 }
363             }
364 
365             // Free the renderer and the algebra object
366             delete board.renderer;
367 
368             // clear the creator cache
369             board.jc.creator.clearCache();
370             delete board.jc;
371 
372             // Finally remove the board itself from the boards array
373             delete JXG.boards[board.id];
374         },
375 
376         /**
377          * @deprecated Use JXG#registerElement
378          * @param element
379          * @param creator
380          */
381         registerElement: function (element, creator) {
382             JXG.registerElement(element, creator);
383         },
384 
385         /**
386          * @deprecated
387          * @param element
388          */
389         unregisterElement: function (element) {
390             throw new Error('Unimplemented');
391         }
392     };
393 
394     // JessieScript/JessieCode startup: Search for script tags of type text/jessiescript and interpret them.
395     if (Env.isBrowser && typeof window === 'object' && typeof document === 'object') {
396         Env.addEvent(window, 'load', function () {
397             var type, i, j, div, id, board, width, height, bbox, axis, grid, code,
398                 scripts = document.getElementsByTagName('script'),
399                 init = function (code, type, bbox) {
400                     var board = JXG.JSXGraph.initBoard(id, {boundingbox: bbox, keepaspectratio: true, grid: grid, axis: axis, showReload: true});
401 
402                     if (type.toLowerCase().indexOf('script') > -1) {
403                         board.construct(code);
404                     } else {
405                         try {
406                             board.jc.parse(code);
407                         } catch (e2) {
408                             JXG.debug(e2);
409                         }
410                     }
411 
412                     return board;
413                 },
414                 makeReload = function (board, code, type, bbox) {
415                     return function () {
416                         var newBoard;
417 
418                         JXG.JSXGraph.freeBoard(board);
419                         newBoard = init(code, type, bbox);
420                         newBoard.reload = makeReload(newBoard, code, type, bbox);
421                     };
422                 };
423 
424             for (i = 0; i < scripts.length; i++) {
425                 type = scripts[i].getAttribute('type', false);
426 
427                 if (Type.exists(type) && (type.toLowerCase() === 'text/jessiescript' || type.toLowerCase() === 'jessiescript' || type.toLowerCase() === 'text/jessiecode' || type.toLowerCase() === 'jessiecode')) {
428                     width = scripts[i].getAttribute('width', false) || '500px';
429                     height = scripts[i].getAttribute('height', false) || '500px';
430                     bbox = scripts[i].getAttribute('boundingbox', false) || '-5, 5, 5, -5';
431                     id = scripts[i].getAttribute('container', false);
432 
433                     bbox = bbox.split(',');
434                     if (bbox.length !== 4) {
435                         bbox = [-5, 5, 5, -5];
436                     } else {
437                         for (j = 0; j < bbox.length; j++) {
438                             bbox[j] = parseFloat(bbox[j]);
439                         }
440                     }
441                     axis = Type.str2Bool(scripts[i].getAttribute('axis', false) || 'false');
442                     grid = Type.str2Bool(scripts[i].getAttribute('grid', false) || 'false');
443 
444                     if (!Type.exists(id)) {
445                         id = 'jessiescript_autgen_jxg_' + i;
446                         div = document.createElement('div');
447                         div.setAttribute('id', id);
448                         div.setAttribute('style', 'width:' + width + '; height:' + height + '; float:left');
449                         div.setAttribute('class', 'jxgbox');
450                         try {
451                             document.body.insertBefore(div, scripts[i]);
452                         } catch (e) {
453                             // there's probably jquery involved...
454                             if (typeof jQuery === 'object') {
455                                 jQuery(div).insertBefore(scripts[i]);
456                             }
457                         }
458                     } else {
459                         div = document.getElementById(id);
460                     }
461 
462                     if (document.getElementById(id)) {
463                         code = scripts[i].innerHTML;
464                         code = code.replace(/<!\[CDATA\[/g, '').replace(/\]\]>/g, '');
465                         scripts[i].innerHTML = code;
466 
467                         board = init(code, type, bbox);
468                         board.reload = makeReload(board, code, type, bbox);
469                     } else {
470                         JXG.debug('JSXGraph: Apparently the div injection failed. Can\'t create a board, sorry.');
471                     }
472                 }
473             }
474         }, window);
475     }
476 
477     return JXG.JSXGraph;
478 });
479