cirandas.net

ref: master

plugins/web_odf/public/wodotexteditor-0.5.9/wodotexteditor/wodotexteditor.js


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
/**
 * Copyright (C) 2014 KO GmbH <copyright@kogmbh.com>
 *
 * @licstart
 * This file is part of WebODF.
 *
 * WebODF is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License (GNU AGPL)
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * WebODF is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with WebODF.  If not, see <http://www.gnu.org/licenses/>.
 * @licend
 *
 * @source: http://www.webodf.org/
 * @source: https://github.com/kogmbh/WebODF/
 */

/*global window, document, alert, navigator, require, dojo, runtime, core, gui, ops, odf, WodoFromSource*/

/**
 * Namespace of the Wodo.TextEditor
 * @namespace
 * @name Wodo
 */
window.Wodo = window.Wodo || (function () {
    "use strict";

    function getInstallationPath() {
        /**
         * Sees to get the url of this script on top of the stack trace.
         * @param {!string|undefined} stack
         * @return {!string|undefined}
         */
        function getScriptUrlFromStack(stack) {
            var url, matches;

            if (typeof stack === "string" && stack) {
                /*jslint regexp: true*/
                matches = stack.match(/((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
                /*jslint regexp: false*/
                url = matches && matches[1];
            }
            if (typeof url === "string" && url) {
                return url;
            }
            return undefined;
        }

        /**
         * Tries by various tricks to get the url of this script.
         * To be called if document.currentScript is not supported
         * @return {!string|undefined}
         */
        function getCurrentScriptElementSrcByTricks() {
            var scriptElements = document.getElementsByTagName("script");

            // if there is only one script, it must be this
            if (scriptElements.length === 1) {
                return scriptElements[0].src;
            }

            // otherwise get it from the stacktrace
            try {
                throw new Error();
            } catch (err) {
                return getScriptUrlFromStack(err.stack);
            }
        }

        var path = ".", scriptElementSrc,
            a, pathname, pos;

        if (document.currentScript && document.currentScript.src) {
            scriptElementSrc = document.currentScript.src;
        } else {
            scriptElementSrc = getCurrentScriptElementSrcByTricks();
        }

        if (scriptElementSrc) {
            a = document.createElement('a');
            a.href = scriptElementSrc;
            pathname = a.pathname;
            if (pathname.charAt(0) !== "/") {
                // Various versions of Internet Explorer seems to neglect the leading slash under some conditions
                // (not when watching it with the dev tools of course!). This was confirmed in IE10 + IE11
                pathname = "/" + pathname;
            }

            pos = pathname.lastIndexOf("/");
            if (pos !== -1) {
                path = pathname.substr(0, pos);
            }
        } else {
            alert("Could not estimate installation path of the Wodo.TextEditor.");
        }
        return path;
    }

    var /** @inner @const
            @type{!string} */
        installationPath = getInstallationPath(),
        /** @inner @type{!boolean} */
        isInitalized = false,
        /** @inner @type{!Array.<!function():undefined>} */
        pendingInstanceCreationCalls = [],
        /** @inner @type{!number} */
        instanceCounter = 0,
        // TODO: avatar image url needs base-url setting.
        // so far Wodo itself does not have a setup call,
        // but then the avatar is also not used yet here
        defaultUserData = {
            fullName: "",
            color:    "black",
            imageUrl: "avatar-joe.png"
        },
        /** @inner @const
            @type{!Array.<!string>} */
        userDataFieldNames = ["fullName", "color", "imageUrl"],
        /** @inner @const
            @type{!string} */
        memberId = "localuser",
        // constructors
        BorderContainer, ContentPane, FullWindowZoomHelper, EditorSession, Tools,
        /** @inner @const
            @type{!string} */
        MODUS_FULLEDITING = "fullediting",
        /** @inner @const
            @type{!string} */
        MODUS_REVIEW = "review",
        /** @inner @const
            @type{!string} */
        EVENT_UNKNOWNERROR = "unknownError",
        /** @inner @const
            @type {!string} */
        EVENT_DOCUMENTMODIFIEDCHANGED = "documentModifiedChanged",
        /** @inner @const
            @type {!string} */
        EVENT_METADATACHANGED = "metadataChanged";

    window.dojoConfig = (function () {
        var WebODFEditorDojoLocale = "C";

        if (navigator && navigator.language && navigator.language.match(/^(de)/)) {
            WebODFEditorDojoLocale = navigator.language.substr(0, 2);
        }

        return {
            locale: WebODFEditorDojoLocale,
            paths: {
                "webodf/editor": installationPath,
                "dijit":         installationPath + "/dijit",
                "dojox":         installationPath + "/dojox",
                "dojo":          installationPath + "/dojo",
                "resources":     installationPath + "/resources"
            }
        };
    }());

    /**
     * @return {undefined}
     */
    function initTextEditor() {
        require([
            "dijit/layout/BorderContainer",
            "dijit/layout/ContentPane",
            "webodf/editor/FullWindowZoomHelper",
            "webodf/editor/EditorSession",
            "webodf/editor/Tools",
            "webodf/editor/Translator"],
            function (BC, CP, FWZH, ES, T, Translator) {
                var locale = navigator.language || "en-US",
                    editorBase = dojo.config && dojo.config.paths && dojo.config.paths["webodf/editor"],
                    translationsDir = editorBase + '/translations',
                    t;

                BorderContainer = BC;
                ContentPane = CP;
                FullWindowZoomHelper = FWZH;
                EditorSession = ES;
                Tools = T;

                // TODO: locale cannot be set by the user, also different for different editors
                t = new Translator(translationsDir, locale, function (editorTranslator) {
                    runtime.setTranslator(editorTranslator.translate);
                    // Extend runtime with a convenient translation function
                    runtime.translateContent = function (node) {
                        var i,
                            element,
                            tag,
                            placeholder,
                            translatable = node.querySelectorAll("*[text-i18n]");

                        for (i = 0; i < translatable.length; i += 1) {
                            element = translatable[i];
                            tag = element.localName;
                            placeholder = element.getAttribute('text-i18n');
                            if (tag === "label"
                                    || tag === "span"
                                    || /h\d/i.test(tag)) {
                                element.textContent = runtime.tr(placeholder);
                            }
                        }
                    };

                    defaultUserData.fullName = runtime.tr("Unknown Author");

                    isInitalized = true;
                    pendingInstanceCreationCalls.forEach(function (create) { create(); });
                });

                // only done to make jslint see the var used
                return t;
            }
        );
    }

    /**
     * Creates a new record with userdata, and for all official fields
     * copies over the value from the original or, if not present there,
     * sets it to the default value.
     * @param {?Object.<!string,!string>|undefined} original, defaults to {}
     * @return {!Object.<!string,!string>}
     */
    function cloneUserData(original) {
        var result = {};

        if (!original) {
            original = {};
        }

        userDataFieldNames.forEach(function (fieldName) {
            result[fieldName] = original[fieldName] || defaultUserData[fieldName];
        });

        return result;
    }

    /**
     * @name TextEditor
     * @constructor
     * @param {!string} mainContainerElementId
     * @param {!Object.<!string,!*>} editorOptions
     */
    function TextEditor(mainContainerElementId, editorOptions) {
        instanceCounter = instanceCounter + 1;

        /**
        * Returns true if either all features are wanted and this one is not explicitely disabled
        * or if not all features are wanted by default and it is explicitely enabled
        * @param {?boolean|undefined} isFeatureEnabled explicit flag which enables a feature
        * @return {!boolean}
        */
        function isEnabled(isFeatureEnabled) {
            return editorOptions.allFeaturesEnabled ? (isFeatureEnabled !== false) : isFeatureEnabled;
        }

        var userData,
            //
            mainContainerElement = document.getElementById(mainContainerElementId),
            canvasElement,
            canvasContainerElement,
            toolbarElement,
            toolbarContainerElement, // needed because dijit toolbar overwrites direct classList
            editorElement,
            /** @inner @const
                @type{!string} */
            canvasElementId = "webodfeditor-canvas" + instanceCounter,
            /** @inner @const
                @type{!string} */
            canvasContainerElementId = "webodfeditor-canvascontainer" + instanceCounter,
            /** @inner @const
                @type{!string} */
            toolbarElementId = "webodfeditor-toolbar" + instanceCounter,
            /** @inner @const
                @type{!string} */
            editorElementId = "webodfeditor-editor" + instanceCounter,
            //
            fullWindowZoomHelper,
            //
            mainContainer,
            tools,
            odfCanvas,
            //
            editorSession,
            session,
            //
            loadOdtFile = editorOptions.loadCallback,
            saveOdtFile = editorOptions.saveCallback,
            saveAsOdtFile = editorOptions.saveAsCallback,
            downloadOdtFile = editorOptions.downloadCallback,
            close =       editorOptions.closeCallback,
            //
            reviewModeEnabled = (editorOptions.modus === MODUS_REVIEW),
            directTextStylingEnabled = isEnabled(editorOptions.directTextStylingEnabled),
            directParagraphStylingEnabled = isEnabled(editorOptions.directParagraphStylingEnabled),
            paragraphStyleSelectingEnabled = (!reviewModeEnabled) && isEnabled(editorOptions.paragraphStyleSelectingEnabled),
            paragraphStyleEditingEnabled =   (!reviewModeEnabled) && isEnabled(editorOptions.paragraphStyleEditingEnabled),
            imageEditingEnabled =            (!reviewModeEnabled) && isEnabled(editorOptions.imageEditingEnabled),
            hyperlinkEditingEnabled = isEnabled(editorOptions.hyperlinkEditingEnabled),
            annotationsEnabled = reviewModeEnabled || isEnabled(editorOptions.annotationsEnabled),
            undoRedoEnabled = isEnabled(editorOptions.undoRedoEnabled),
            zoomingEnabled = isEnabled(editorOptions.zoomingEnabled),
            //
            pendingMemberId,
            pendingEditorReadyCallback,
            //
            eventNotifier = new core.EventNotifier([
                EVENT_UNKNOWNERROR,
                EVENT_DOCUMENTMODIFIEDCHANGED,
                EVENT_METADATACHANGED
            ]);

        runtime.assert(Boolean(mainContainerElement), "No id of an existing element passed to Wodo.createTextEditor(): " + mainContainerElementId);

        /**
         * @param {!Object} changes
         * @return {undefined}
         */
        function relayMetadataSignal(changes) {
            eventNotifier.emit(EVENT_METADATACHANGED, changes);
        }

        /**
         * @param {!Object} changes
         * @return {undefined}
         */
        function relayModifiedSignal(modified) {
            eventNotifier.emit(EVENT_DOCUMENTMODIFIEDCHANGED, modified);
        }

        /**
         * @return {undefined}
         */
        function createSession() {
            var viewOptions = {
                    editInfoMarkersInitiallyVisible: false,
                    caretAvatarsInitiallyVisible: false,
                    caretBlinksOnRangeSelect: true
                };

            // create session around loaded document
            session = new ops.Session(odfCanvas);
            editorSession = new EditorSession(session, pendingMemberId, {
                viewOptions: viewOptions,
                directTextStylingEnabled: directTextStylingEnabled,
                directParagraphStylingEnabled: directParagraphStylingEnabled,
                paragraphStyleSelectingEnabled: paragraphStyleSelectingEnabled,
                paragraphStyleEditingEnabled: paragraphStyleEditingEnabled,
                imageEditingEnabled: imageEditingEnabled,
                hyperlinkEditingEnabled: hyperlinkEditingEnabled,
                annotationsEnabled: annotationsEnabled,
                zoomingEnabled: zoomingEnabled,
                reviewModeEnabled: reviewModeEnabled
            });
            if (undoRedoEnabled) {
                editorSession.sessionController.setUndoManager(new gui.TrivialUndoManager());
                editorSession.sessionController.getUndoManager().subscribe(gui.UndoManager.signalDocumentModifiedChanged, relayModifiedSignal);
            }

            // Relay any metadata changes to the Editor's consumer as an event
            editorSession.sessionController.getMetadataController().subscribe(gui.MetadataController.signalMetadataChanged, relayMetadataSignal);

            // and report back to caller
            pendingEditorReadyCallback();
            // reset
            pendingEditorReadyCallback = null;
            pendingMemberId = null;
        }

        /**
         * @return {undefined}
         */
        function startEditing() {
            runtime.assert(editorSession, "editorSession should exist here.");

            tools.setEditorSession(editorSession);
            editorSession.sessionController.insertLocalCursor();
            editorSession.sessionController.startEditing();
        }

        /**
         * @return {undefined}
         */
        function endEditing() {
            runtime.assert(editorSession, "editorSession should exist here.");

            tools.setEditorSession(undefined);
            editorSession.sessionController.endEditing();
            editorSession.sessionController.removeLocalCursor();
        }

        /**
         * Loads an ODT document into the editor.
         * @name TextEditor#openDocumentFromUrl
         * @function
         * @param {!string} docUrl url from which the ODT document can be loaded
         * @param {!function(!Error=):undefined} callback Called once the document has been opened, passes an error object in case of error
         * @return {undefined}
         */
        this.openDocumentFromUrl = function (docUrl, editorReadyCallback) {
            runtime.assert(docUrl, "document should be defined here.");
            runtime.assert(!pendingEditorReadyCallback, "pendingEditorReadyCallback should not exist here.");
            runtime.assert(!editorSession, "editorSession should not exist here.");
            runtime.assert(!session, "session should not exist here.");

            pendingMemberId = memberId;
            pendingEditorReadyCallback = function () {
                var op = new ops.OpAddMember();
                op.init({
                    memberid: memberId,
                    setProperties: userData
                });
                session.enqueue([op]);
                startEditing();
                if (editorReadyCallback) {
                    editorReadyCallback();
                }
            };

            odfCanvas.load(docUrl);
        };

        /**
         * Closes the document, and does cleanup.
         * @name TextEditor#closeDocument
         * @function
         * @param {!function(!Error=):undefined} callback  Called once the document has been closed, passes an error object in case of error
         * @return {undefined}
         */
        this.closeDocument = function (callback) {
            runtime.assert(session, "session should exist here.");

            endEditing();

            var op = new ops.OpRemoveMember();
            op.init({
                memberid: memberId
            });
            session.enqueue([op]);

            session.close(function (err) {
                if (err) {
                    callback(err);
                } else {
                    editorSession.sessionController.getMetadataController().unsubscribe(gui.MetadataController.signalMetadataChanged, relayMetadataSignal);
                    editorSession.destroy(function (err) {
                        if (err) {
                            callback(err);
                        } else {
                            editorSession = undefined;
                            session.destroy(function (err) {
                                if (err) {
                                    callback(err);
                                } else {
                                    session = undefined;
                                    callback();
                                }
                            });
                        }
                    });
                }
            });
        };

        /**
         * @name TextEditor#getDocumentAsByteArray
         * @function
         * @param {!function(err:?Error, file:!Uint8Array=):undefined} callback Called with the current document as ODT file as bytearray, passes an error object in case of error
         * @return {undefined}
         */
        this.getDocumentAsByteArray = function (callback) {
            var odfContainer = odfCanvas.odfContainer();

            if (odfContainer) {
                odfContainer.createByteArray(function (ba) {
                    callback(null, ba);
                }, function (errorString) {
                    callback(new Error(errorString || "Could not create bytearray from OdfContainer."));
                });
            } else {
                callback(new Error("No odfContainer set!"));
            }
        };

        /**
         * Sets the metadata fields from the given properties map.
         * Avoid setting certain fields since they are automatically set:
         *    dc:creator
         *    dc:date
         *    meta:editing-cycles
         *
         * The following properties are never used and will be removed for semantic
         * consistency from the document:
         *     meta:editing-duration
         *     meta:document-statistic
         *
         * Setting any of the above mentioned fields using this method will have no effect.
         *
         * @name TextEditor#setMetadata
         * @function
         * @param {?Object.<!string, !string>} setProperties A flat object that is a string->string map of field name -> value.
         * @param {?Array.<!string>} removedProperties An array of metadata field names (prefixed).
         * @return {undefined}
         */
        this.setMetadata = function (setProperties, removedProperties) {
            runtime.assert(editorSession, "editorSession should exist here.");

            editorSession.sessionController.getMetadataController().setMetadata(setProperties, removedProperties);
        };

        /**
         * Returns the value of the requested document metadata field.
         * @name TextEditor#getMetadata
         * @function
         * @param {!string} property A namespace-prefixed field name, for example
         * dc:creator
         * @return {?string}
         */
        this.getMetadata = function (property) {
            runtime.assert(editorSession, "editorSession should exist here.");

            return editorSession.sessionController.getMetadataController().getMetadata(property);
        };

        /**
         * Sets the data for the person that is editing the document.
         * The supported fields are:
         *     "fullName": the full name of the editing person
         *     "color": color to use for the user specific UI elements
         * @name TextEditor#setUserData
         * @function
         * @param {?Object.<!string,!string>|undefined} data
         * @return {undefined}
         */
        function setUserData(data) {
            userData = cloneUserData(data);
        }
        this.setUserData = setUserData;

        /**
         * Returns the data set for the person that is editing the document.
         * @name TextEditor#getUserData
         * @function
         * @return {!Object.<!string,!string>}
         */
        this.getUserData = function () {
            return cloneUserData(userData);
        };

        /**
         * Sets the current state of the document to be either the unmodified state
         * or a modified state.
         * If @p modified is @true and the current state was already a modified state,
         * this call has no effect and also does not remove the unmodified flag
         * from the state which has it set.
         *
         * @name TextEditor#setDocumentModified
         * @function
         * @param {!boolean} modified
         * @return {undefined}
         */
        this.setDocumentModified = function (modified) {
            runtime.assert(editorSession, "editorSession should exist here.");

            if (undoRedoEnabled) {
                editorSession.sessionController.getUndoManager().setDocumentModified(modified);
            }
        };

        /**
         * Returns if the current state of the document matches the unmodified state.
         * @name TextEditor#isDocumentModified
         * @function
         * @return {!boolean}
         */
        this.isDocumentModified = function () {
            runtime.assert(editorSession, "editorSession should exist here.");

            if (undoRedoEnabled) {
                return editorSession.sessionController.getUndoManager().isDocumentModified();
            }

            return false;
        };

        /**
         * @return {undefined}
         */
        function setFocusToOdfCanvas() {
            editorSession.sessionController.getEventManager().focus();
        }

        /**
         * @param {!function(!Error=):undefined} callback passes an error object in case of error
         * @return {undefined}
         */
        function destroyInternal(callback) {
            mainContainerElement.removeChild(editorElement);

            callback();
        }

        /**
         * Destructs the editor object completely.
         * @name TextEditor#destroy
         * @function
         * @param {!function(!Error=):undefined} callback Called once the destruction has been completed, passes an error object in case of error
         * @return {undefined}
         */
        this.destroy = function (callback) {
            var destroyCallbacks = [];

            // TODO: decide if some forced close should be done here instead of enforcing proper API usage
            runtime.assert(!session, "session should not exist here.");

            // TODO: investigate what else needs to be done
            mainContainer.destroyRecursive(true);

            destroyCallbacks = destroyCallbacks.concat([
                fullWindowZoomHelper.destroy,
                tools.destroy,
                odfCanvas.destroy,
                destroyInternal
            ]);

            core.Async.destroyAll(destroyCallbacks, callback);
        };

        // TODO:
        // this.openDocumentFromByteArray = openDocumentFromByteArray; see also https://github.com/kogmbh/WebODF/issues/375
        // setReadOnly: setReadOnly,

        /**
         * Registers a callback which should be called if the given event happens.
         * @name TextEditor#addEventListener
         * @function
         * @param {!string} eventId
         * @param {!Function} callback
         * @return {undefined}
         */
        this.addEventListener = eventNotifier.subscribe;
        /**
         * Unregisters a callback for the given event.
         * @name TextEditor#removeEventListener
         * @function
         * @param {!string} eventId
         * @param {!Function} callback
         * @return {undefined}
         */
        this.removeEventListener = eventNotifier.unsubscribe;


        /**
         * @return {undefined}
         */
        function init() {
            var editorPane,
                /** @inner @const
                    @type{!string} */
                documentns = document.documentElement.namespaceURI;

            /**
             * @param {!string} tagLocalName
             * @param {!string|undefined} id
             * @param {!string} className
             * @return {!Element}
             */
            function createElement(tagLocalName, id, className) {
                var element;
                element = document.createElementNS(documentns, tagLocalName);
                if (id) {
                    element.id = id;
                }
                element.classList.add(className);
                return element;
            }

            // create needed tree structure
            canvasElement = createElement('div', canvasElementId, "webodfeditor-canvas");
            canvasContainerElement = createElement('div', canvasContainerElementId, "webodfeditor-canvascontainer");
            toolbarElement = createElement('span', toolbarElementId, "webodfeditor-toolbar");
            toolbarContainerElement = createElement('span', undefined, "webodfeditor-toolbarcontainer");
            editorElement = createElement('div', editorElementId, "webodfeditor-editor");

            // put into tree
            canvasContainerElement.appendChild(canvasElement);
            toolbarContainerElement.appendChild(toolbarElement);
            editorElement.appendChild(toolbarContainerElement);
            editorElement.appendChild(canvasContainerElement);
            mainContainerElement.appendChild(editorElement);

            // style all elements with Dojo's claro.
            // Not nice to do this on body, but then there is no other way known
            // to style also all dialogs, which are attached directly to body
            document.body.classList.add("claro");

            // prevent browser translation service messing up internal address system
            // TODO: this should be done more centrally, but where exactly?
            canvasElement.setAttribute("translate", "no");
            canvasElement.classList.add("notranslate");

            // create widgets
            mainContainer = new BorderContainer({}, mainContainerElementId);

            editorPane = new ContentPane({
                region: 'center'
            }, editorElementId);
            mainContainer.addChild(editorPane);

            mainContainer.startup();

            tools = new Tools(toolbarElementId, {
                onToolDone: setFocusToOdfCanvas,
                loadOdtFile: loadOdtFile,
                saveOdtFile: saveOdtFile,
                saveAsOdtFile: saveAsOdtFile,
                downloadOdtFile: downloadOdtFile,
                close: close,
                directTextStylingEnabled: directTextStylingEnabled,
                directParagraphStylingEnabled: directParagraphStylingEnabled,
                paragraphStyleSelectingEnabled: paragraphStyleSelectingEnabled,
                paragraphStyleEditingEnabled: paragraphStyleEditingEnabled,
                imageInsertingEnabled: imageEditingEnabled,
                hyperlinkEditingEnabled: hyperlinkEditingEnabled,
                annotationsEnabled: annotationsEnabled,
                undoRedoEnabled: undoRedoEnabled,
                zoomingEnabled: zoomingEnabled,
                aboutEnabled: true
            });

            odfCanvas = new odf.OdfCanvas(canvasElement);
            odfCanvas.enableAnnotations(annotationsEnabled, true);

            odfCanvas.addListener("statereadychange", createSession);

            fullWindowZoomHelper = new FullWindowZoomHelper(toolbarContainerElement, canvasContainerElement);

            setUserData(editorOptions.userData);
        }

        init();
    }

    function loadDojoAndStuff(callback) {
        var head = document.getElementsByTagName("head")[0],
            frag = document.createDocumentFragment(),
            link,
            script;

        // append two link and two script elements to the header
        link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = installationPath + "/app/resources/app.css";
        link.type = "text/css";
        link.async = false;
        frag.appendChild(link);
        link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = installationPath + "/wodotexteditor.css";
        link.type = "text/css";
        link.async = false;
        frag.appendChild(link);
        script = document.createElement("script");
        script.src = installationPath + "/dojo-amalgamation.js";
        script["data-dojo-config"] = "async: true";
        script.charset = "utf-8";
        script.type = "text/javascript";
        script.async = false;
        frag.appendChild(script);
        script = document.createElement("script");
        script.src = installationPath + "/webodf.js";
        script.charset = "utf-8";
        script.type = "text/javascript";
        script.async = false;
        script.onload = callback;
        frag.appendChild(script);
        head.appendChild(frag);
    }

    /**
     * Creates a text editor object and returns it on success in the passed callback.
     * @name Wodo#createTextEditor
     * @function
     * @param {!string} editorContainerElementId id of the existing div element which will contain the editor (should be empty before)
     * @param editorOptions options to configure the features of the editor. All entries are optional
     * @param [editorOptions.modus=Wodo.MODUS_FULLEDITING] set the editing modus. Current options: Wodo.MODUS_FULLEDITING, Wodo.MODUS_REVIEW
     * @param [editorOptions.loadCallback] parameter-less callback method, adds a "Load" button to the toolbar which triggers this method
     * @param [editorOptions.saveCallback] parameter-less callback method, adds a "Save" button to the toolbar which triggers this method
     * @param [editorOptions.saveAsCallback] parameter-less callback method, adds a "Save as" button to the toolbar which triggers this method
     * @param [editorOptions.downloadCallback] parameter-less callback method, adds a "Download" button to the right of the toolbar which triggers this method
     * @param [editorOptions.closeCallback] parameter-less callback method, adds a "Save" button to the toolbar which triggers this method
     * @param [editorOptions.allFeaturesEnabled=false] if set to 'true', switches the default for all features from 'false' to 'true'
     * @param [editorOptions.directTextStylingEnabled=false] if set to 'true', enables the direct styling of text (e.g. bold/italic or font)
     * @param [editorOptions.directParagraphStylingEnabled=false] if set to 'true', enables the direct styling of paragraphs (e.g. indentation or alignement)
     * @param [editorOptions.paragraphStyleSelectingEnabled=false] if set to 'true', enables setting of defined paragraph styles to paragraphs
     * @param [editorOptions.paragraphStyleEditingEnabled=false] if set to 'true', enables the editing of defined paragraph styles
     * @param [editorOptions.imageEditingEnabled=false] if set to 'true', enables the insertion of images
     * @param [editorOptions.hyperlinkEditingEnabled=false] if set to 'true', enables the editing of hyperlinks
     * @param [editorOptions.annotationsEnabled=false] if set to 'true', enables the display and the editing of annotations
     * @param [editorOptions.undoRedoEnabled=false] if set to 'true', enables the Undo and Redo of editing actions
     * @param [editorOptions.zoomingEnabled=false] if set to 'true', enables the zooming tool
     * @param [editorOptions.userData] data about the user editing the document
     * @param [editorOptions.userData.fullName] full name of the user, used for annotations and in the metadata of the document
     * @param [editorOptions.userData.color="black"] color to use for any user related indicators like cursor or annotations
     * @param {!function(err:?Error, editor:!TextEditor=):undefined} onEditorCreated
     * @return {undefined}
     */
    function createTextEditor(editorContainerElementId, editorOptions, onEditorCreated) {
        /**
         * @return {undefined}
         */
        function create() {
            var editor = new TextEditor(editorContainerElementId, editorOptions);
            onEditorCreated(null, editor);
        }

        if (!isInitalized) {
            pendingInstanceCreationCalls.push(create);
            // first request?
            if (pendingInstanceCreationCalls.length === 1) {
                if (String(typeof WodoFromSource) === "undefined") {
                    loadDojoAndStuff(initTextEditor);
                } else {
                    initTextEditor();
                }
            }
        } else {
            create();
        }
    }


    /**
     * @lends Wodo#
     */
    return {
        createTextEditor: createTextEditor,
        // flags
        /** Id of full editing modus */
        MODUS_FULLEDITING: MODUS_FULLEDITING,
        /** Id of review modus */
        MODUS_REVIEW: MODUS_REVIEW,
        /** Id of event for an unkown error */
        EVENT_UNKNOWNERROR: EVENT_UNKNOWNERROR,
        /** Id of event if documentModified state changes */
        EVENT_DOCUMENTMODIFIEDCHANGED: EVENT_DOCUMENTMODIFIEDCHANGED,
        /** Id of event if metadata changes */
        EVENT_METADATACHANGED: EVENT_METADATACHANGED
    };
}());