<commit_before>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

/**
 *  Settings.js
 *  Presentation Editor
 *
 *  Created by Alexander Yuzhin on 11/22/16
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'core',
    'jquery',
    'underscore',
    'backbone',
    'presentationeditor/mobile/app/view/Settings'
], function (core, $, _, Backbone) {
    'use strict';

    PE.Controllers.Settings = Backbone.Controller.extend(_.extend((function() {
        // private
        var rootView,
            inProgress,
            infoObj,
            modalView,
            _licInfo,
            _lang;

        var _slideSizeArr = [
            [254, 190.5], [254, 143]
        ];

        return {
            models: [],
            collections: [],
            views: [
                'Settings'
            ],

            initialize: function () {
                Common.SharedSettings.set('readerMode', false);
                Common.NotificationCenter.on('settingscontainer:show', _.bind(this.initEvents, this));

                this.addListeners({
                    'Settings': {
                        'page:show' : this.onPageShow
                    }
                });
            },

            setApi: function (api) {
                this.api = api;

                this.api.asc_registerCallback('asc_onPresentationSize', _.bind(this.onApiPageSize, this));
                this.api.asc_registerCallback('asc_onSendThemeColorSchemes', _.bind(this.onSendThemeColorSchemes, this));
            },

            onLaunch: function () {
                this.createView('Settings').render();
            },

            setMode: function (mode) {
                this.getView('Settings').setMode(mode);
                if (mode.canBranding)
                    _licInfo = mode.customization;
                _lang = mode.lang;
            },

            initEvents: function () {
            },

            rootView : function() {
                return rootView;
            },

            showModal: function() {
                uiApp.closeModal();

                if (Common.SharedSettings.get('phone')) {
                    modalView = uiApp.popup(
                        '
' +
                            '
' +
                                '
' +
                                    this.getView('Settings').rootLayout() +
                                '
' +
                            '
' +
                        '
'
                    );
                } else {
                    modalView = uiApp.popover(
                        '
' +
                            '

' +
                            '
' +
                                '
' +
                                    '
' +
                                        this.getView('Settings').rootLayout() +
                                    '
' +
                                '
' +
                            '
' +
                        '
',
                        $$('#toolbar-settings')
                    );
                }

                if (Framework7.prototype.device.android === true) {
                    $$('.view.settings-root-view.navbar-through').removeClass('navbar-through').addClass('navbar-fixed');
                    $$('.view.settings-root-view .navbar').prependTo('.view.settings-root-view > .pages > .page');
                }

                rootView = uiApp.addView('.settings-root-view', {
                    dynamicNavbar: true,
                    domCache: true
                });

                Common.NotificationCenter.trigger('settingscontainer:show');
                this.onPageShow(this.getView('Settings'));
            },

            hideModal: function() {
                if (modalView) {
                    uiApp.closeModal(modalView);
                }
            },

            onPageShow: function(view, pageId) {
                var me = this;
                $('#settings-spellcheck input:checkbox').attr('checked', Common.Utils.InternalSettings.get("pe-mobile-spellcheck"));
                $('#settings-search').single('click',                       _.bind(me._onSearch, me));
                $('#settings-readermode input:checkbox').single('change',   _.bind(me._onReaderMode, me));
                $('#settings-spellcheck input:checkbox').single('change',   _.bind(me._onSpellcheck, me));
                $(modalView).find('.formats a').single('click',             _.bind(me._onSaveFormat, me));
                $('#page-settings-view #slide-size-block li').single('click',           _.bind(me._onSlideSize, me));
                $('#settings-print').single('click',                        _.bind(me._onPrint, me));
                $('#settings-collaboration').single('click',                _.bind(me.onCollaboration, me));

                var _userCount = PE.getController('Main').returnUserCount();
                if (_userCount > 0) {
                    $('#settings-collaboration').show();
                }

                Common.Utils.addScrollIfNeed('.page[data-page=settings-setup-view]', '.page[data-page=settings-setup-view] .page-content');
                Common.Utils.addScrollIfNeed('.page[data-page=settings-download-view]', '.page[data-page=settings-download-view] .page-content');
                Common.Utils.addScrollIfNeed('.page[data-page=settings-info-view]', '.page[data-page=settings-info-view] .page-content');
                Common.Utils.addScrollIfNeed('.page[data-page=settings-about-view]', '.page[data-page=settings-about-view] .page-content');
                Common.Utils.addScrollIfNeed('.page[data-page=color-schemes-view]', '.page[data-page=color-schemes-view] .page-content');

                me.initSettings(pageId);
            },

            initSettings: function (pageId) {
                var me = this;
                if (pageId == '#settings-setup-view') {
                    me.onApiPageSize(me.api.get_PresentationWidth(), me.api.get_PresentationHeight());
                } else if (pageId == '#settings-about-view') {
                    // About
                    me.setLicInfo(_licInfo);
                } else if ('#settings-application-view' == pageId) {
                    me.initPageApplicationSettings();
                } else if ('#color-schemes-view' == pageId) {
                    me.initPageColorSchemes();
                } else if ('#settings-info-view' == pageId) {
                    me.initPageInfo();
                }
            },

            initPageInfo: function() {
                var document = Common.SharedSettings.get('document') || {},
                    info = document.info || {};

                document.title ? $('#settings-presentation-title').html(document.title) : $('.display-presentation-title').remove();
                var value = info.owner || info.author;
                value ? $('#settings-pe-owner').html(value) : $('.display-owner').remove();
                value = info.uploaded || info.created;
                value ? $('#settings-pe-uploaded').html(value) : $('.display-uploaded').remove();
                info.folder ? $('#settings-pe-location').html(info.folder) : $('.display-location').remove();

                var appProps = (this.api) ? this.api.asc_getAppProps() : null;
                if (appProps) {
                    var appName = (appProps.asc_getApplication() || '') + ' ' + (appProps.asc_getAppVersion() || '');
                    appName ? $('#settings-pe-application').html(appName) : $('.display-application').remove();
                }

                var props = (this.api) ? this.api.asc_getCoreProps() : null;
                if (props) {
                    value = props.asc_getTitle();
                    value ? $('#settings-pe-title').html(value) : $('.display-title').remove();
                    value = props.asc_getSubject();
                    value ? $('#settings-pe-subject').html(value) : $('.display-subject').remove();
                    value = props.asc_getDescription();
                    value ? $('#settings-pe-comment').html(value) : $('.display-comment').remove();
                    value = props.asc_getModified();
                    value ? $('#settings-pe-last-mod').html(value.toLocaleString(_lang, {year: 'numeric', month: '2-digit', day: '2-digit'}) + ' ' + value.toLocaleString(_lang, {timeStyle: 'short'})) : $('.display-last-mode').remove();
                    value = props.asc_getLastModifiedBy();
                    value ? $('#settings-pe-mod-by').html(value) : $('.display-mode-by').remove();
                    value = props.asc_getCreated();
                    value ? $('#settings-pe-date').html(value.toLocaleString(_lang, {year: 'numeric', month: '2-digit', day: '2-digit'}) + ' ' + value.toLocaleString(_lang, {timeStyle: 'short'})) : $('.display-created-date').remove();
                    value = props.asc_getCreator();
                    var templateCreator = "";
                    value && value.split(/\s*[,;]\s*/).forEach(function(item) {
                        templateCreator = templateCreator + "

" + item + "

";
                    });
                    templateCreator ? $('#list-creator').html(templateCreator) : $('.display-author').remove();
                }

            },

            onCollaboration: function() {
                PE.getController('Common.Controllers.Collaboration').showModal();
            },

            initPageColorSchemes: function() {
                this.curSchemas = (this.api) ? this.api.asc_GetCurrentColorSchemeIndex() : 0;
                this.getView('Settings').renderSchemaSettings(this.curSchemas, this.schemas);
                $('.page[data-page=color-schemes-view] input:radio[name=color-schema]').single('change', _.bind(this.onColorSchemaChange, this));
                Common.Utils.addScrollIfNeed('.page[data-page=color-schemes-view', '.page[data-page=color-schemes-view] .page-content');
            },

            onSendThemeColorSchemes: function (schemas) {
                this.schemas = schemas;
            },

            onColorSchemaChange: function(event) {
                if (this.api) {
                    var ind = $(event.currentTarget).val();
                    if (this.curSchemas !== ind)
                        this.api.asc_ChangeColorSchemeByIdx(parseInt(ind));
                }
            },

            initPageApplicationSettings: function () {
                var me = this,
                    $unitMeasurement = $('.page[data-page=settings-application-view] input:radio[name=unit-of-measurement]');
                $unitMeasurement.single('change', _.bind(me.unitMeasurementChange, me));
                var value = Common.Utils.Metric.getCurrentMetric();
                $unitMeasurement.val([value]);
            },

            unitMeasurementChange: function (e) {
                var value = $(e.currentTarget).val();
                value = (value!==null) ? parseInt(value) : Common.Utils.Metric.getDefaultMetric();
                Common.Utils.Metric.setCurrentMetric(value);
                Common.localStorage.setItem("pe-mobile-settings-unit", value);
                this.api.asc_SetDocumentUnits((value==Common.Utils.Metric.c_MetricUnits.inch) ? Asc.c_oAscDocumentUnits.Inch : ((value==Common.Utils.Metric.c_MetricUnits.pt) ? Asc.c_oAscDocumentUnits.Point : Asc.c_oAscDocumentUnits.Millimeter));
            },

            setLicInfo: function(data){
                if (data && typeof data == 'object' && typeof(data.customer)=='object') {
                    $('.page[data-page=settings-about-view] .logo').hide();
                    $('#settings-about-tel').parent().hide();
                    $('#settings-about-licensor').show();

                    var customer = data.customer,
                        value = customer.name;
                    value && value.length ?
                        $('#settings-about-name').text(value) :
                        $('#settings-about-name').hide();

                    value = customer.address;
                    value && value.length ?
                        $('#settings-about-address').text(value) :
                        $('#settings-about-address').parent().hide();

                    (value = customer.mail) && value.length ?
                        $('#settings-about-email').attr('href', "mailto:"+value).text(value) :
                        $('#settings-about-email').parent().hide();

                    if ((value = customer.www) && value.length) {
                        var http = !/^https?:\/{2}/i.test(value) ? "http:\/\/" : '';
                        $('#settings-about-url').attr('href', http+value).text(value);
                    } else
                        $('#settings-about-url').hide();

                    if ((value = customer.info) && value.length) {
                        $('#settings-about-info').show().text(value);
                    }

                    if ( (value = customer.logo) && value.length ) {
                        $('#settings-about-logo').show().html('');
                    }
                }
            },

            // API handlers

            onApiPageSize: function(width, height) {
                for (var i = 0; i < _slideSizeArr.length; i++) {
                    if (Math.abs(_slideSizeArr[i][0] - width) < 0.001 && Math.abs(_slideSizeArr[i][1] - height) < 0.001) {
                        $('#page-settings-setup-view input').val([i]);
                        break;
                    }
                }
            },

            _onApiDocumentName: function(name) {
                $('#settings-presentation-title').html(name ? name : '-');
            },

            _onSearch: function (e) {
                var toolbarView = PE.getController('Toolbar').getView('Toolbar');

                if (toolbarView) {
                    toolbarView.showSearch();
                }

                this.hideModal();
            },

            _onPrint: function(e) {
                var me = this;

                _.defer(function () {
                    me.api.asc_Print();
                });
                me.hideModal();
            },

            _onSpellcheck: function (e) {
                var $checkbox = $(e.currentTarget),
                    state = $checkbox.is(':checked');
                Common.localStorage.setItem("pe-mobile-spellcheck", state ? 1 : 0);
                Common.Utils.InternalSettings.set("pe-mobile-spellcheck", state);
                this.api && this.api.asc_setSpellCheck(state);
            },

            _onReaderMode: function (e) {
                var me = this;

                Common.SharedSettings.set('readerMode', !Common.SharedSettings.get('readerMode'));

                me.api && me.api.ChangeReaderMode();

                if (Common.SharedSettings.get('phone')) {
                    _.defer(function () {
                        me.hideModal();
                    }, 1000);
                }

                Common.NotificationCenter.trigger('readermode:change', Common.SharedSettings.get('readerMode'));
            },

            _onSaveFormat: function(e) {
                var me = this,
                    format = $(e.currentTarget).data('format');

                if (format) {
                    _.defer(function () {
                        me.api.asc_DownloadAs(new Asc.asc_CDownloadOptions(format));
                    });
                }

                me.hideModal();
            },

            _onSlideSize: function(e) {
                var $target = $(e.currentTarget).find('input');
                if ($target && this.api) {
                    var value = parseFloat($target.prop('value'));
                    this.api.changeSlideSize(_slideSizeArr[value][0], _slideSizeArr[value][1]);
                }
            },

            txtLoading              : 'Loading...',
            notcriticalErrorTitle   : 'Warning'
        }
    })(), PE.Controllers.Settings || {}))
});<commit_msg>[PE mobile] Fix bug 42820<commit_after>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

/**
 *  Settings.js
 *  Presentation Editor
 *
 *  Created by Alexander Yuzhin on 11/22/16
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'core',
    'jquery',
    'underscore',
    'backbone',
    'presentationeditor/mobile/app/view/Settings'
], function (core, $, _, Backbone) {
    'use strict';

    PE.Controllers.Settings = Backbone.Controller.extend(_.extend((function() {
        // private
        var rootView,
            inProgress,
            infoObj,
            modalView,
            _licInfo,
            _lang;

        var _slideSizeArr = [
            [254, 190.5], [254, 143]
        ];

        return {
            models: [],
            collections: [],
            views: [
                'Settings'
            ],

            initialize: function () {
                Common.SharedSettings.set('readerMode', false);
                Common.NotificationCenter.on('settingscontainer:show', _.bind(this.initEvents, this));

                this.addListeners({
                    'Settings': {
                        'page:show' : this.onPageShow
                    }
                });
            },

            setApi: function (api) {
                this.api = api;

                this.api.asc_registerCallback('asc_onPresentationSize', _.bind(this.onApiPageSize, this));
                this.api.asc_registerCallback('asc_onSendThemeColorSchemes', _.bind(this.onSendThemeColorSchemes, this));
            },

            onLaunch: function () {
                this.createView('Settings').render();
            },

            setMode: function (mode) {
                this.getView('Settings').setMode(mode);
                if (mode.canBranding)
                    _licInfo = mode.customization;
                _lang = mode.lang;
            },

            initEvents: function () {
            },

            rootView : function() {
                return rootView;
            },

            showModal: function() {
                uiApp.closeModal();

                if (Common.SharedSettings.get('phone')) {
                    modalView = uiApp.popup(
                        '
' +
                            '
' +
                                '
' +
                                    this.getView('Settings').rootLayout() +
                                '
' +
                            '
' +
                        '
'
                    );
                } else {
                    modalView = uiApp.popover(
                        '
' +
                            '

' +
                            '
' +
                                '
' +
                                    '
' +
                                        this.getView('Settings').rootLayout() +
                                    '
' +
                                '
' +
                            '
' +
                        '
',
                        $$('#toolbar-settings')
                    );
                }

                if (Framework7.prototype.device.android === true) {
                    $$('.view.settings-root-view.navbar-through').removeClass('navbar-through').addClass('navbar-fixed');
                    $$('.view.settings-root-view .navbar').prependTo('.view.settings-root-view > .pages > .page');
                }

                rootView = uiApp.addView('.settings-root-view', {
                    dynamicNavbar: true,
                    domCache: true
                });

                Common.NotificationCenter.trigger('settingscontainer:show');
                this.onPageShow(this.getView('Settings'));
            },

            hideModal: function() {
                if (modalView) {
                    uiApp.closeModal(modalView);
                }
            },

            onPageShow: function(view, pageId) {
                var me = this;
                $('#settings-spellcheck input:checkbox').attr('checked', Common.Utils.InternalSettings.get("pe-mobile-spellcheck"));
                $('#settings-search').single('click',                       _.bind(me._onSearch, me));
                $('#settings-readermode input:checkbox').single('change',   _.bind(me._onReaderMode, me));
                $('#settings-spellcheck input:checkbox').single('change',   _.bind(me._onSpellcheck, me));
                $(modalView).find('.formats a').single('click',             _.bind(me._onSaveFormat, me));
                $('#page-settings-view #slide-size-block li').single('click',           _.bind(me._onSlideSize, me));
                $('#settings-print').single('click',                        _.bind(me._onPrint, me));
                $('#settings-collaboration').single('click',                _.bind(me.onCollaboration, me));

                var _userCount = PE.getController('Main').returnUserCount();
                if (_userCount > 0) {
                    $('#settings-collaboration').show();
                }

                Common.Utils.addScrollIfNeed('.page[data-page=settings-setup-view]', '.page[data-page=settings-setup-view] .page-content');
                Common.Utils.addScrollIfNeed('.page[data-page=settings-download-view]', '.page[data-page=settings-download-view] .page-content');
                Common.Utils.addScrollIfNeed('.page[data-page=settings-info-view]', '.page[data-page=settings-info-view] .page-content');
                Common.Utils.addScrollIfNeed('.page[data-page=settings-about-view]', '.page[data-page=settings-about-view] .page-content');
                Common.Utils.addScrollIfNeed('.page[data-page=color-schemes-view]', '.page[data-page=color-schemes-view] .page-content');

                me.initSettings(pageId);
            },

            initSettings: function (pageId) {
                var me = this;
                if (pageId == '#settings-setup-view') {
                    me.onApiPageSize(me.api.get_PresentationWidth(), me.api.get_PresentationHeight());
                } else if (pageId == '#settings-about-view') {
                    // About
                    me.setLicInfo(_licInfo);
                } else if ('#settings-application-view' == pageId) {
                    me.initPageApplicationSettings();
                } else if ('#color-schemes-view' == pageId) {
                    me.initPageColorSchemes();
                } else if ('#settings-info-view' == pageId) {
                    me.initPageInfo();
                }
            },

            initPageInfo: function() {
                var document = Common.SharedSettings.get('document') || {},
                    info = document.info || {};

                document.title ? $('#settings-presentation-title').html(document.title) : $('.display-presentation-title').remove();
                var value = info.owner || info.author;
                value ? $('#settings-pe-owner').html(value) : $('.display-owner').remove();
                value = info.uploaded || info.created;
                value ? $('#settings-pe-uploaded').html(value) : $('.display-uploaded').remove();
                info.folder ? $('#settings-pe-location').html(info.folder) : $('.display-location').remove();

                var appProps = (this.api) ? this.api.asc_getAppProps() : null;
                if (appProps) {
                    var appName = (appProps.asc_getApplication() || '') + ' ' + (appProps.asc_getAppVersion() || '');
                    appName ? $('#settings-pe-application').html(appName) : $('.display-application').remove();
                }

                var props = (this.api) ? this.api.asc_getCoreProps() : null;
                if (props) {
                    value = props.asc_getTitle();
                    value ? $('#settings-pe-title').html(value) : $('.display-title').remove();
                    value = props.asc_getSubject();
                    value ? $('#settings-pe-subject').html(value) : $('.display-subject').remove();
                    value = props.asc_getDescription();
                    value ? $('#settings-pe-comment').html(value) : $('.display-comment').remove();
                    value = props.asc_getModified();
                    value ? $('#settings-pe-last-mod').html(value.toLocaleString(_lang, {year: 'numeric', month: '2-digit', day: '2-digit'}) + ' ' + value.toLocaleString(_lang, {timeStyle: 'short'})) : $('.display-last-mode').remove();
                    value = props.asc_getLastModifiedBy();
                    value ? $('#settings-pe-mod-by').html(value) : $('.display-mode-by').remove();
                    value = props.asc_getCreated();
                    value ? $('#settings-pe-date').html(value.toLocaleString(_lang, {year: 'numeric', month: '2-digit', day: '2-digit'}) + ' ' + value.toLocaleString(_lang, {timeStyle: 'short'})) : $('.display-created-date').remove();
                    value = props.asc_getCreator();
                    var templateCreator = "";
                    value && value.split(/\s*[,;]\s*/).forEach(function(item) {
                        templateCreator = templateCreator + "

" + item + "

";
                    });
                    templateCreator ? $('#list-creator').html(templateCreator) : $('.display-author').remove();
                }

            },

            onCollaboration: function() {
                PE.getController('Common.Controllers.Collaboration').showModal();
            },

            initPageColorSchemes: function() {
                this.curSchemas = (this.api) ? this.api.asc_GetCurrentColorSchemeIndex() : 0;
                this.getView('Settings').renderSchemaSettings(this.curSchemas, this.schemas);
                $('.page[data-page=color-schemes-view] input:radio[name=color-schema]').single('change', _.bind(this.onColorSchemaChange, this));
                Common.Utils.addScrollIfNeed('.page[data-page=color-schemes-view', '.page[data-page=color-schemes-view] .page-content');
            },

            onSendThemeColorSchemes: function (schemas) {
                this.schemas = schemas;
            },

            onColorSchemaChange: function(event) {
                if (this.api) {
                    var ind = $(event.currentTarget).val();
                    if (this.curSchemas !== ind)
                        this.api.asc_ChangeColorSchemeByIdx(parseInt(ind));
                }
            },

            initPageApplicationSettings: function () {
                var me = this,
                    $unitMeasurement = $('.page[data-page=settings-application-view] input:radio[name=unit-of-measurement]');
                $unitMeasurement.single('change', _.bind(me.unitMeasurementChange, me));
                var value = Common.Utils.Metric.getCurrentMetric();
                $unitMeasurement.val([value]);
            },

            unitMeasurementChange: function (e) {
                var value = $(e.currentTarget).val();
                value = (value!==null) ? parseInt(value) : Common.Utils.Metric.getDefaultMetric();
                Common.Utils.Metric.setCurrentMetric(value);
                Common.localStorage.setItem("pe-mobile-settings-unit", value);
                this.api.asc_SetDocumentUnits((value==Common.Utils.Metric.c_MetricUnits.inch) ? Asc.c_oAscDocumentUnits.Inch : ((value==Common.Utils.Metric.c_MetricUnits.pt) ? Asc.c_oAscDocumentUnits.Point : Asc.c_oAscDocumentUnits.Millimeter));
            },

            setLicInfo: function(data){
                if (data && typeof data == 'object' && typeof(data.customer)=='object') {
                    $('.page[data-page=settings-about-view] .logo').hide();
                    $('#settings-about-tel').parent().hide();
                    $('#settings-about-licensor').show();

                    var customer = data.customer,
                        value = customer.name;
                    value && value.length ?
                        $('#settings-about-name').text(value) :
                        $('#settings-about-name').hide();

                    value = customer.address;
                    value && value.length ?
                        $('#settings-about-address').text(value) :
                        $('#settings-about-address').parent().hide();

                    (value = customer.mail) && value.length ?
                        $('#settings-about-email').attr('href', "mailto:"+value).text(value) :
                        $('#settings-about-email').parent().hide();

                    if ((value = customer.www) && value.length) {
                        var http = !/^https?:\/{2}/i.test(value) ? "http:\/\/" : '';
                        $('#settings-about-url').attr('href', http+value).text(value);
                    } else
                        $('#settings-about-url').hide();

                    if ((value = customer.info) && value.length) {
                        $('#settings-about-info').show().text(value);
                    }

                    if ( (value = customer.logo) && value.length ) {
                        $('#settings-about-logo').show().html('');
                    }
                }
            },

            // API handlers

            onApiPageSize: function(width, height) {
                var $input = $('#page-settings-view input[name="slide-size"]');
                if ($input.length > 0) {
                    for (var i = 0; i < _slideSizeArr.length; i++) {
                        if (Math.abs(_slideSizeArr[i][0] - width) < 0.001 && Math.abs(_slideSizeArr[i][1] - height) < 0.001) {
                            $input.val([i]);
                            break;
                        }
                    }
                }
            },

            _onApiDocumentName: function(name) {
                $('#settings-presentation-title').html(name ? name : '-');
            },

            _onSearch: function (e) {
                var toolbarView = PE.getController('Toolbar').getView('Toolbar');

                if (toolbarView) {
                    toolbarView.showSearch();
                }

                this.hideModal();
            },

            _onPrint: function(e) {
                var me = this;

                _.defer(function () {
                    me.api.asc_Print();
                });
                me.hideModal();
            },

            _onSpellcheck: function (e) {
                var $checkbox = $(e.currentTarget),
                    state = $checkbox.is(':checked');
                Common.localStorage.setItem("pe-mobile-spellcheck", state ? 1 : 0);
                Common.Utils.InternalSettings.set("pe-mobile-spellcheck", state);
                this.api && this.api.asc_setSpellCheck(state);
            },

            _onReaderMode: function (e) {
                var me = this;

                Common.SharedSettings.set('readerMode', !Common.SharedSettings.get('readerMode'));

                me.api && me.api.ChangeReaderMode();

                if (Common.SharedSettings.get('phone')) {
                    _.defer(function () {
                        me.hideModal();
                    }, 1000);
                }

                Common.NotificationCenter.trigger('readermode:change', Common.SharedSettings.get('readerMode'));
            },

            _onSaveFormat: function(e) {
                var me = this,
                    format = $(e.currentTarget).data('format');

                if (format) {
                    _.defer(function () {
                        me.api.asc_DownloadAs(new Asc.asc_CDownloadOptions(format));
                    });
                }

                me.hideModal();
            },

            _onSlideSize: function(e) {
                var $target = $(e.currentTarget).find('input');
                if ($target && this.api) {
                    var value = parseFloat($target.prop('value'));
                    this.api.changeSlideSize(_slideSizeArr[value][0], _slideSizeArr[value][1]);
                }
            },

            txtLoading              : 'Loading...',
            notcriticalErrorTitle   : 'Warning'
        }
    })(), PE.Controllers.Settings || {}))
});<|endoftext|>


<commit_before>// this file is automatically generated using scripts/updatePackageVersions.js
export default {
  "addon-active": "1.0.0-beta.5",
  "addon-ancestors": "1.0.0-beta.5",
  "addon-prefetch": "1.0.0-beta.5",
  "core": "1.0.0-beta.19",
  "react": "1.0.0-beta.13",
  "redux": "1.0.0-beta.1",
  "side-effect-scroll": "1.0.0-beta.5",
  "side-effect-title": "1.0.0-beta.5",
  "svelte": "1.0.0-beta.1",
  "vue": "1.0.0-beta.10"
};
<commit_msg>(docs) Update side effect pkg versions [ci skip]<commit_after>// this file is automatically generated using scripts/updatePackageVersions.js
export default {
  "addon-active": "1.0.0-beta.5",
  "addon-ancestors": "1.0.0-beta.5",
  "addon-prefetch": "1.0.0-beta.5",
  "core": "1.0.0-beta.19",
  "react": "1.0.0-beta.13",
  "redux": "1.0.0-beta.1",
  "side-effect-scroll": "1.0.0-beta.6",
  "side-effect-title": "1.0.0-beta.6",
  "svelte": "1.0.0-beta.1",
  "vue": "1.0.0-beta.10"
};
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');

const RNFetchBlob = require('react-native-fetch-blob').default;

const {
    fs
} = RNFetchBlob;

const baseCacheDir = fs.dirs.CacheDir + '/imagesCacheDir';

const SHA1 = require("crypto-js/sha1");
const URL = require('url-parse');

const defaultHeaders = {};
const defaultImageTypes = ['png', 'jpeg', 'jpg', 'gif', 'bmp', 'tiff', 'tif'];
const defaultResolveHeaders = _.constant(defaultHeaders);

const defaultOptions = {
    useQueryParamsInCacheKey: false
};

const activeDownloads = {};

function serializeObjectKeys(obj) {
    return _(obj)
        .toPairs()
        .sortBy(a => a[0])
        .map(a => a[1])
        .value();
}

function getQueryForCacheKey(url, useQueryParamsInCacheKey) {
    if (_.isArray(useQueryParamsInCacheKey)) {
        return serializeObjectKeys(_.pick(url.query, useQueryParamsInCacheKey));
    }
    if (useQueryParamsInCacheKey) {
        return serializeObjectKeys(url.query);
    }
    return '';
}

function generateCacheKey(url, options) {
    const parsedUrl = new URL(url, null, true);

    const pathParts = parsedUrl.pathname.split('/');

    // last path part is the file name
    const fileName = pathParts.pop();
    const filePath = pathParts.join('/');

    const parts = fileName.split('.');
    const fileType = parts.length > 1 ? _.toLower(parts.pop()) : '';
    const type = defaultImageTypes.includes(fileType) ? fileType : 'jpg';

    const cacheable = filePath + fileName + type + getQueryForCacheKey(parsedUrl, options.useQueryParamsInCacheKey);
    return SHA1(cacheable) + '.' + type;
}

function getCachePath(url, options) {
    if (options.cacheGroup) {
        return options.cacheGroup;
    }
    const {
        host
    } = new URL(url);
    return host.replace(/[^a-z0-9]/gi, '').toLowerCase();
}

function getCachedImageFilePath(url, options) {
    const cachePath = getCachePath(url, options);
    const cacheKey = generateCacheKey(url, options);

    return `${baseCacheDir}/${cachePath}/${cacheKey}`;
}

function deleteFile(filePath) {
    return fs.stat(filePath)
        .then(res => res && res.type === 'file')
        .then(exists => exists && fs.unlink(filePath))
        .catch((err) => {
            // swallow error to always resolve
        });
}

function getDirPath(filePath) {
    return _.initial(filePath.split('/')).join('/');
}

function ensurePath(dirPath) {
    return fs.isDir(dirPath)
        .then(exists =>
            !exists && fs.mkdir(dirPath)
        )
        .catch(err => {
            // swallow folder already exists errors
            if (err.message.includes('folder already exists')) {
                return;
            }
            throw err;
        });
}

/**
 * returns a promise that is resolved when the download of the requested file
 * is complete and the file is saved.
 * if the download fails, or was stopped the partial file is deleted, and the
 * promise is rejected
 * @param fromUrl   String source url
 * @param toFile    String destination path
 * @param headers   Object headers to use when downloading the file
 * @returns {Promise}
 */
function downloadImage(fromUrl, toFile, headers = {}) {
    // use toFile as the key as is was created using the cacheKey
    if (!_.has(activeDownloads, toFile)) {
        //Using a temporary file, if the download is accidentally interrupted, it will not produce a disabled file
        const tmpFile = toFile + '.tmp';
        // create an active download for this file
        activeDownloads[toFile] = new Promise((resolve, reject) => {
            RNFetchBlob
                .config({path: tmpFile})
                .fetch('GET', fromUrl, headers)
                .then(res => {
                    if (Math.floor(res.respInfo.status / 100) !== 2) {
                        throw new Error('Failed to successfully download image');
                    }
                    //The download is complete and rename the temporary file
                    return fs.mv(tmpFile, toFile);
                })
                .then(() => resolve(toFile))
                .catch(err => {
                    return deleteFile(toFile)
                        .then(() => reject(err));
                })
                .finally(() => {
                    // cleanup
                    delete activeDownloads[toFile];
                });
        });
    }
    return activeDownloads[toFile];
}

function createPrefetcer(list) {
    const urls = _.clone(list);
    return {
        next() {
            return urls.shift();
        }
    };
}

function runPrefetchTask(prefetcher, options) {
    const url = prefetcher.next();
    if (!url) {
        return Promise.resolve();
    }
    // if url is cacheable - cache it
    if (isCacheable(url)) {
        // check cache
        return getCachedImagePath(url, options)
        // if not found download
            .catch(() => cacheImage(url, options))
            // allow prefetch task to fail without terminating other prefetch tasks
            .catch(_.noop)
            // then run next task
            .then(() => runPrefetchTask(prefetcher, options));
    }
    // else get next
    return runPrefetchTask(prefetcher, options);
}

function collectFilesInfo(basePath) {
    return fs.stat(basePath)
        .then((info) => {
            if (info.type === 'file') {
                return [info];
            }
            return fs.ls(basePath)
                .then(files => {
                    const promises = _.map(files, file => {
                        return collectFilesInfo(`${basePath}/${file}`);
                    });
                    return Promise.all(promises);
                });
        })
        .catch(err => {
            return [];
        });
}

// API

/**
 * Check whether a url is cacheable.
 * Takes an image source and if it's a valid url return `true`
 * @param url
 * @returns {boolean}
 */
function isCacheable(url) {
    return _.isString(url) && (_.startsWith(url, 'http://') || _.startsWith(url, 'https://'));
}

/**
 * Get the local path corresponding to the given url and options.
 * @param url
 * @param options
 * @returns {Promise.<String>}
 */
function getCachedImagePath(url, options = defaultOptions) {
    const filePath = getCachedImageFilePath(url, options);
    return fs.stat(filePath)
        .then(res => {
            if (res.type !== 'file') {
                // reject the promise if res is not a file
                throw new Error('Failed to get image from cache');
            }
            if (!res.size) {
                // something went wrong with the download, file size is 0, remove it
                return deleteFile(filePath)
                    .then(() => {
                        throw new Error('Failed to get image from cache');
                    });
            }
            return filePath;
        })
        .catch(err => {
            throw err;
        })
}

/**
 * Download the image to the cache and return the local file path.
 * @param url
 * @param options
 * @param resolveHeaders
 * @returns {Promise.<String>}
 */
function cacheImage(url, options = defaultOptions, resolveHeaders = defaultResolveHeaders) {
    const filePath = getCachedImageFilePath(url, options);
    const dirPath = getDirPath(filePath);
    return ensurePath(dirPath)
        .then(() => resolveHeaders())
        .then(headers => downloadImage(url, filePath, headers));
}

/**
 * Delete the cached image corresponding to the given url and options.
 * @param url
 * @param options
 * @returns {Promise}
 */
function deleteCachedImage(url, options = defaultOptions) {
    const filePath = getCachedImageFilePath(url, options);
    return deleteFile(filePath);
}

/**
 * Cache an array of urls.
 * Usually used to prefetch images.
 * @param urls
 * @param options
 * @returns {Promise}
 */
function cacheMultipleImages(urls, options = defaultOptions) {
    const prefetcher = createPrefetcer(urls);
    const numberOfWorkers = urls.length;
    const promises = _.times(numberOfWorkers, () =>
        runPrefetchTask(prefetcher, options)
    );
    return Promise.all(promises);
}

/**
 * Delete an array of cached images by their urls.
 * Usually used to clear the prefetched images.
 * @param urls
 * @param options
 * @returns {Promise}
 */
function deleteMultipleCachedImages(urls, options = defaultOptions) {
    return _.reduce(urls, (p, url) =>
            p.then(() => deleteCachedImage(url, options)),
        Promise.resolve()
    );
}

/**
* Seed the cache of a specified url with a local image
* Handy if you have a local copy of a remote image, e.g. you just uploaded local to url.
* @param local
* @param url
* @param options
* @returns {Promise}
*/
function seedCache(local, url, options = defaultOptions) {
  const filePath = getCachedImageFilePath(url, options);
  const dirPath = getDirPath(filePath);
  return ensurePath(dirPath)
    .then(() => fs.cp(local, filePath))
}

/**
 * Clear the entire cache.
 * @returns {Promise}
 */
function clearCache() {
    return fs.unlink(baseCacheDir)
        .catch(() => {
            // swallow exceptions if path doesn't exist
        })
        .then(() => ensurePath(baseCacheDir));
}

/**
 * Return info about the cache, list of files and the total size of the cache.
 * @returns {Promise.<{size}>}
 */
function getCacheInfo() {
    return ensurePath(baseCacheDir)
        .then(() => collectFilesInfo(baseCacheDir))
        .then(cache => {
            const files = _.flattenDeep(cache);
            const size = _.sumBy(files, 'size');
            return {
                files,
                size
            };
        });
}

module.exports = {
    isCacheable,
    getCachedImageFilePath,
    getCachedImagePath,
    cacheImage,
    deleteCachedImage,
    cacheMultipleImages,
    deleteMultipleCachedImages,
    clearCache,
    seedCache,
    getCacheInfo
};
<commit_msg>Update ImageCacheProvider.js<commit_after>'use strict';

const _ = require('lodash');

const RNFetchBlob = require('react-native-fetch-blob').default;

const {
    fs
} = RNFetchBlob;

const baseCacheDir = fs.dirs.CacheDir + '/imagesCacheDir';

const SHA1 = require("crypto-js/sha1");
const URL = require('url-parse');

const defaultHeaders = {};
const defaultImageTypes = ['png', 'jpeg', 'jpg', 'gif', 'bmp', 'tiff', 'tif'];
const defaultResolveHeaders = _.constant(defaultHeaders);

const defaultOptions = {
    useQueryParamsInCacheKey: false
};

const activeDownloads = {};

function serializeObjectKeys(obj) {
    return _(obj)
        .toPairs()
        .sortBy(a => a[0])
        .map(a => a[1])
        .value();
}

function getQueryForCacheKey(url, useQueryParamsInCacheKey) {
    if (_.isArray(useQueryParamsInCacheKey)) {
        return serializeObjectKeys(_.pick(url.query, useQueryParamsInCacheKey));
    }
    if (useQueryParamsInCacheKey) {
        return serializeObjectKeys(url.query);
    }
    return '';
}

function generateCacheKey(url, options) {
    const parsedUrl = new URL(url, null, true);

    const pathParts = parsedUrl.pathname.split('/');

    // last path part is the file name
    const fileName = pathParts.pop();
    const filePath = pathParts.join('/');

    const parts = fileName.split('.');
    const fileType = parts.length > 1 ? _.toLower(parts.pop()) : '';
    const type = defaultImageTypes.includes(fileType) ? fileType : 'jpg';

    const cacheable = filePath + fileName + type + getQueryForCacheKey(parsedUrl, options.useQueryParamsInCacheKey);
    return SHA1(cacheable) + '.' + type;
}

function getCachePath(url, options) {
    if (options.cacheGroup) {
        return options.cacheGroup;
    }
    const {
        host
    } = new URL(url);
    return host.replace(/[^a-z0-9]/gi, '').toLowerCase();
}

function getCachedImageFilePath(url, options) {
    const cachePath = getCachePath(url, options);
    const cacheKey = generateCacheKey(url, options);

    return `${baseCacheDir}/${cachePath}/${cacheKey}`;
}

function deleteFile(filePath) {
    return fs.stat(filePath)
        .then(res => res && res.type === 'file')
        .then(exists => exists && fs.unlink(filePath))
        .catch((err) => {
            // swallow error to always resolve
        });
}

function getDirPath(filePath) {
    return _.initial(filePath.split('/')).join('/');
}

function ensurePath(dirPath) {
    return fs.isDir(dirPath)
        .then(exists =>
            !exists && fs.mkdir(dirPath)
        )
        .catch(err => {
            // swallow folder already exists errors
            if (err.message.includes('folder already exists')) {
                return;
            }
            throw err;
        });
}

/**
 * returns a promise that is resolved when the download of the requested file
 * is complete and the file is saved.
 * if the download fails, or was stopped the partial file is deleted, and the
 * promise is rejected
 * @param fromUrl   String source url
 * @param toFile    String destination path
 * @param headers   Object headers to use when downloading the file
 * @returns {Promise}
 */
function downloadImage(fromUrl, toFile, headers = {}) {
    // use toFile as the key as is was created using the cacheKey
    if (!_.has(activeDownloads, toFile)) {
        //Using a temporary file, if the download is accidentally interrupted, it will not produce a disabled file
        const tmpFile = toFile + '.tmp';
        // create an active download for this file
        activeDownloads[toFile] = new Promise((resolve, reject) => {
            RNFetchBlob
                .config({path: tmpFile})
                .fetch('GET', fromUrl, headers)
                .then(res => {
                    if (Math.floor(res.respInfo.status / 100) !== 2) {
                        throw new Error('Failed to successfully download image');
                    }
                    //The download is complete and rename the temporary file
                    return fs.mv(tmpFile, toFile);
                })
                .then(() => resolve(toFile))
                .catch(err => {
                    return deleteFile(tmpFile)
                        .then(() => reject(err));
                })
                .finally(() => {
                    // cleanup
                    delete activeDownloads[toFile];
                });
        });
    }
    return activeDownloads[toFile];
}

function createPrefetcer(list) {
    const urls = _.clone(list);
    return {
        next() {
            return urls.shift();
        }
    };
}

function runPrefetchTask(prefetcher, options) {
    const url = prefetcher.next();
    if (!url) {
        return Promise.resolve();
    }
    // if url is cacheable - cache it
    if (isCacheable(url)) {
        // check cache
        return getCachedImagePath(url, options)
        // if not found download
            .catch(() => cacheImage(url, options))
            // allow prefetch task to fail without terminating other prefetch tasks
            .catch(_.noop)
            // then run next task
            .then(() => runPrefetchTask(prefetcher, options));
    }
    // else get next
    return runPrefetchTask(prefetcher, options);
}

function collectFilesInfo(basePath) {
    return fs.stat(basePath)
        .then((info) => {
            if (info.type === 'file') {
                return [info];
            }
            return fs.ls(basePath)
                .then(files => {
                    const promises = _.map(files, file => {
                        return collectFilesInfo(`${basePath}/${file}`);
                    });
                    return Promise.all(promises);
                });
        })
        .catch(err => {
            return [];
        });
}

// API

/**
 * Check whether a url is cacheable.
 * Takes an image source and if it's a valid url return `true`
 * @param url
 * @returns {boolean}
 */
function isCacheable(url) {
    return _.isString(url) && (_.startsWith(url, 'http://') || _.startsWith(url, 'https://'));
}

/**
 * Get the local path corresponding to the given url and options.
 * @param url
 * @param options
 * @returns {Promise.<String>}
 */
function getCachedImagePath(url, options = defaultOptions) {
    const filePath = getCachedImageFilePath(url, options);
    return fs.stat(filePath)
        .then(res => {
            if (res.type !== 'file') {
                // reject the promise if res is not a file
                throw new Error('Failed to get image from cache');
            }
            if (!res.size) {
                // something went wrong with the download, file size is 0, remove it
                return deleteFile(filePath)
                    .then(() => {
                        throw new Error('Failed to get image from cache');
                    });
            }
            return filePath;
        })
        .catch(err => {
            throw err;
        })
}

/**
 * Download the image to the cache and return the local file path.
 * @param url
 * @param options
 * @param resolveHeaders
 * @returns {Promise.<String>}
 */
function cacheImage(url, options = defaultOptions, resolveHeaders = defaultResolveHeaders) {
    const filePath = getCachedImageFilePath(url, options);
    const dirPath = getDirPath(filePath);
    return ensurePath(dirPath)
        .then(() => resolveHeaders())
        .then(headers => downloadImage(url, filePath, headers));
}

/**
 * Delete the cached image corresponding to the given url and options.
 * @param url
 * @param options
 * @returns {Promise}
 */
function deleteCachedImage(url, options = defaultOptions) {
    const filePath = getCachedImageFilePath(url, options);
    return deleteFile(filePath);
}

/**
 * Cache an array of urls.
 * Usually used to prefetch images.
 * @param urls
 * @param options
 * @returns {Promise}
 */
function cacheMultipleImages(urls, options = defaultOptions) {
    const prefetcher = createPrefetcer(urls);
    const numberOfWorkers = urls.length;
    const promises = _.times(numberOfWorkers, () =>
        runPrefetchTask(prefetcher, options)
    );
    return Promise.all(promises);
}

/**
 * Delete an array of cached images by their urls.
 * Usually used to clear the prefetched images.
 * @param urls
 * @param options
 * @returns {Promise}
 */
function deleteMultipleCachedImages(urls, options = defaultOptions) {
    return _.reduce(urls, (p, url) =>
            p.then(() => deleteCachedImage(url, options)),
        Promise.resolve()
    );
}

/**
* Seed the cache of a specified url with a local image
* Handy if you have a local copy of a remote image, e.g. you just uploaded local to url.
* @param local
* @param url
* @param options
* @returns {Promise}
*/
function seedCache(local, url, options = defaultOptions) {
  const filePath = getCachedImageFilePath(url, options);
  const dirPath = getDirPath(filePath);
  return ensurePath(dirPath)
    .then(() => fs.cp(local, filePath))
}

/**
 * Clear the entire cache.
 * @returns {Promise}
 */
function clearCache() {
    return fs.unlink(baseCacheDir)
        .catch(() => {
            // swallow exceptions if path doesn't exist
        })
        .then(() => ensurePath(baseCacheDir));
}

/**
 * Return info about the cache, list of files and the total size of the cache.
 * @returns {Promise.<{size}>}
 */
function getCacheInfo() {
    return ensurePath(baseCacheDir)
        .then(() => collectFilesInfo(baseCacheDir))
        .then(cache => {
            const files = _.flattenDeep(cache);
            const size = _.sumBy(files, 'size');
            return {
                files,
                size
            };
        });
}

module.exports = {
    isCacheable,
    getCachedImageFilePath,
    getCachedImagePath,
    cacheImage,
    deleteCachedImage,
    cacheMultipleImages,
    deleteMultipleCachedImages,
    clearCache,
    seedCache,
    getCacheInfo
};
<|endoftext|>


<commit_before>"use strict";

const pack = require("./package.json");

// Load TypeScript from our dependencies
try {
	var typescript = require("typescript");
} catch(e) {
	console.error("Couldn't load some dependencies; try running 'npm install'");
	process.exit(1);
}

// Compiler options on the server
// typescript goes to gulp-typescript
const server = {
	typescript: {
		module: "commonjs",
		target: "ES5",
		moduleResolution: "node",
		typescript: typescript,
		noEmitOnError: true,
		experimentalDecorators: true,
		noLib: true
	}
};

const tests = {
	tyepscript: Object.assign({}, server.typescript, {
		allowJs: true
	})
}

const config = {
	browsersync: false,

	// Default preset
	preset: "default",

	// Collection of presets
	presets: {
		default: {
			watch: true,
			sourcemaps: true,
			minify: false,
			out: "es5"
		}
	},

	// List of pipelines to build and use
	pipelines: [
		{
			id: "lib",
			name: "Library (CommonJS)",
			config: server,
			type: "server",

			input: "src/**/*.ts",
			output: "",

			extraEntries: ["node_modules/typescript/lib/lib.es6.d.ts"],

			typingsOutput: "",
			typingsOutputType: "module",
			moduleName: pack.name,
			moduleEntryPoint: "index.ts"
		},
		{
			id: "bundle",
			name: "Browser (Browserify)",
			config: server,
			type: "browser",

			input: "src/index.ts",
			output: "bundle.js",

			extraEntries: ["node_modules/typescript/lib/lib.es6.d.ts"]
		},
		{
			id: "tests",
			name: "Tests (Bundle)",
			config: tests,
			type: "browser",

			input: "tests/main.js",
			output: "test.js",

			extraEntries: ["node_modules/typescript/lib/lib.es6.d.ts", "typings/index.d.ts"]
		},
	]
};

module.exports = config;<commit_msg>Browserify bundle is now 'standalone'<commit_after>"use strict";

const pack = require("./package.json");

// Load TypeScript from our dependencies
try {
	var typescript = require("typescript");
} catch(e) {
	console.error("Couldn't load some dependencies; try running 'npm install'");
	process.exit(1);
}

// Compiler options on the server
// typescript goes to gulp-typescript
const server = {
	typescript: {
		module: "commonjs",
		target: "ES5",
		moduleResolution: "node",
		typescript: typescript,
		noEmitOnError: true,
		experimentalDecorators: true,
		noLib: true
	},
	browserify: {
		standalone: "armature",
		bare: true
	}
};

const tests = {
	tyepscript: Object.assign({}, server.typescript, {
		allowJs: true
	})
}

const config = {
	browsersync: false,

	// Default preset
	preset: "default",

	// Collection of presets
	presets: {
		default: {
			watch: true,
			sourcemaps: true,
			minify: false,
			out: "es5"
		}
	},

	// List of pipelines to build and use
	pipelines: [
		{
			id: "lib",
			name: "Library (CommonJS)",
			config: server,
			type: "server",

			input: "src/**/*.ts",
			output: "",

			extraEntries: ["node_modules/typescript/lib/lib.es6.d.ts"],

			typingsOutput: "",
			typingsOutputType: "module",
			moduleName: pack.name,
			moduleEntryPoint: "index.ts"
		},
		{
			id: "bundle",
			name: "Browser (Browserify)",
			config: server,
			type: "browser",

			input: "src/index.ts",
			output: "bundle.js",

			extraEntries: ["node_modules/typescript/lib/lib.es6.d.ts"]
		},
		{
			id: "tests",
			name: "Tests (Bundle)",
			config: tests,
			type: "browser",

			input: "tests/main.js",
			output: "test.js",

			extraEntries: ["node_modules/typescript/lib/lib.es6.d.ts", "typings/index.d.ts"]
		},
	]
};

module.exports = config;<|endoftext|>


<commit_before>define(['js/svg/Svg', 'js/svg/SvgElement', 'sprd/model/Product', 'underscore', 'sprd/data/ImageService', 'sprd/view/svg/PrintAreaViewer', 'sprd/view/svg/ProductTypeViewViewer'],
    function (Svg, SvgElement, Product, _, ImageService, PrintAreaViewer, ProductTypeViewViewer) {

        return Svg.inherit('sprd.view.ProductViewer', {
            defaults: {

                height: 300,
                width: 300,

                // the view to show
                view: null,

                // the product which is rendered
                product: null,

                // private defaults
                _productType: "{product.productType}",
                _appearance: null,
                _view: null,
                selectedConfiguration: null,

                componentClass: "product-viewer",

                editable: true
            },

            $classAttributes: ["product", "view", "editable", "selectedConfiguration"],

            inject: {
                imageService: ImageService
            },

            ctor: function () {

                this.$productTypeViewViewerCache = {};

                this.callBase();

                this.bind("on:click", this._clickHandler, this);
            },

            initialize: function () {

                this.bind('product.productType', 'change:views', this._onViewsChanged, this);

                this.callBase();
            },

            _removeProductTypeViewViewers: function () {
                // remove all views
                for (var key in this.$productTypeViewViewerCache) {
                    if (this.$productTypeViewViewerCache.hasOwnProperty(key)) {
                        this.$productTypeViewViewerCache[key].remove();
                        this.$productTypeViewViewerCache[key].destroy();
                    }
                }

                this.$productTypeViewViewerCache = {};
            },

            _onViewsChanged: function () {
                this._determinateInternalView();
            },

            _commitView: function () {
                this._determinateInternalView();
            },

            _clickHandler: function(e) {
                if (this.$.editable) {
                    this.set('selectedConfiguration', null);
                }
            },

            _determinateInternalView: function () {
                var view = this.$.view,
                    productType = this.$._productType;

                if (productType) {
                    if (view) {
                        // check if view is compatible
                        this.set('_view', productType.getViewById(view.$.id));
                    } else {
                        this.set('_view', productType.getDefaultView());
                    }
                }

            },

            _render_productType: function (productType, oldProductType) {

                oldProductType && this._removeProductTypeViewViewers();

                if (productType) {
                    this._determinateInternalView();
                    this._renderProductTypeView(productType, this.$._view);
                }

            },

            _render_view: function (view) {

                view && this.setViewBox(0, 0, view.get('size.width'), view.get('size.height'));

                this._renderProductTypeView(this.$._productType, view);
            },

            _commitProduct: function(product) {
                var productTypeViewViewerCache = this.$productTypeViewViewerCache;
                for (var key in productTypeViewViewerCache) {
                    if (productTypeViewViewerCache.hasOwnProperty(key)) {
                        productTypeViewViewerCache[key].set('product', product);
                    }
                }
            },

            _renderProductTypeView: function (productType, view) {
                if (productType && view && productType.containsView(view)) {
                    var cacheId = productType.$.id + "_" + view.$.id;

                    if (!this.$productTypeViewViewerCache[cacheId]) {
                        this.$productTypeViewViewerCache[cacheId] = this.createComponent(ProductTypeViewViewer, {
                            product: this.$.product,
                            productViewer: this,

                            _view: view,
                            _productType: productType
                        });
                    }

                    if (this.$currentProductTypeViewViewer) {
                        this.$currentProductTypeViewViewer.remove();
                    }

                    this.$currentProductTypeViewViewer = this.$productTypeViewViewerCache[cacheId];
                    this.addChild(this.$currentProductTypeViewViewer);

                }
            },

            destroy: function () {
                this._removeProductTypeViewViewers();
                this.callBase();
            }

        });

    });<commit_msg>added backspace and delete key to remove selected configuration<commit_after>define(['js/svg/Svg', 'js/svg/SvgElement', 'sprd/model/Product', 'underscore', 'sprd/data/ImageService', 'sprd/view/svg/PrintAreaViewer', 'sprd/view/svg/ProductTypeViewViewer'],
    function (Svg, SvgElement, Product, _, ImageService, PrintAreaViewer, ProductTypeViewViewer) {

        return Svg.inherit('sprd.view.ProductViewer', {
            defaults: {

                height: 300,
                width: 300,

                // the view to show
                view: null,

                // the product which is rendered
                product: null,

                // private defaults
                _productType: "{product.productType}",
                _appearance: null,
                _view: null,
                selectedConfiguration: null,

                componentClass: "product-viewer",

                editable: true
            },

            $classAttributes: ["product", "view", "editable", "selectedConfiguration"],

            inject: {
                imageService: ImageService
            },

            ctor: function () {

                this.$productTypeViewViewerCache = {};

                this.callBase();

                this.bind("on:click", this._clickHandler, this);
            },

            _bindDomEvents: function() {
                if (this.runsInBrowser() && this.$.editable) {
                    var window = this.dom(this.$stage.$window),
                        self = this;
                    window.bindDomEvent("keydown", function(e) {
                        var product = self.$.product;

                        if ((e.keyCode === 8 || e.keyCode === 46) && self.$.selectedConfiguration && product) {
                            // backspace || delete --> remove selected configuration

                            product.$.configurations.remove(self.$.selectedConfiguration);
                            self.set('selectedConfiguration', null);

                            e.preventDefault();
                        }
                    });
                }

                this.callBase();
            },

            initialize: function () {

                this.bind('product.productType', 'change:views', this._onViewsChanged, this);

                this.callBase();
            },

            _removeProductTypeViewViewers: function () {
                // remove all views
                for (var key in this.$productTypeViewViewerCache) {
                    if (this.$productTypeViewViewerCache.hasOwnProperty(key)) {
                        this.$productTypeViewViewerCache[key].remove();
                        this.$productTypeViewViewerCache[key].destroy();
                    }
                }

                this.$productTypeViewViewerCache = {};
            },

            _onViewsChanged: function () {
                this._determinateInternalView();
            },

            _commitView: function () {
                this._determinateInternalView();
            },

            _clickHandler: function(e) {
                if (this.$.editable) {
                    this.set('selectedConfiguration', null);
                }
            },

            _keyDownHandler: function(e) {
                if (this.$.editable) {
                                   console.log(e);
                }
            },

            _determinateInternalView: function () {
                var view = this.$.view,
                    productType = this.$._productType;

                if (productType) {
                    if (view) {
                        // check if view is compatible
                        this.set('_view', productType.getViewById(view.$.id));
                    } else {
                        this.set('_view', productType.getDefaultView());
                    }
                }

            },

            _render_productType: function (productType, oldProductType) {

                oldProductType && this._removeProductTypeViewViewers();

                if (productType) {
                    this._determinateInternalView();
                    this._renderProductTypeView(productType, this.$._view);
                }

            },

            _render_view: function (view) {

                view && this.setViewBox(0, 0, view.get('size.width'), view.get('size.height'));

                this._renderProductTypeView(this.$._productType, view);
            },

            _commitProduct: function(product) {
                var productTypeViewViewerCache = this.$productTypeViewViewerCache;
                for (var key in productTypeViewViewerCache) {
                    if (productTypeViewViewerCache.hasOwnProperty(key)) {
                        productTypeViewViewerCache[key].set('product', product);
                    }
                }
            },

            _renderProductTypeView: function (productType, view) {
                if (productType && view && productType.containsView(view)) {
                    var cacheId = productType.$.id + "_" + view.$.id;

                    if (!this.$productTypeViewViewerCache[cacheId]) {
                        this.$productTypeViewViewerCache[cacheId] = this.createComponent(ProductTypeViewViewer, {
                            product: this.$.product,
                            productViewer: this,

                            _view: view,
                            _productType: productType
                        });
                    }

                    if (this.$currentProductTypeViewViewer) {
                        this.$currentProductTypeViewViewer.remove();
                    }

                    this.$currentProductTypeViewViewer = this.$productTypeViewViewerCache[cacheId];
                    this.addChild(this.$currentProductTypeViewViewer);

                }
            },

            destroy: function () {
                this._removeProductTypeViewViewers();
                this.callBase();
            }

        });

    });<|endoftext|>


<commit_before>// +----------------------------------------------------------------------+
// | Bitflux Editor                                                       |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | This software is published under the terms of the Apache Software    |
// | License a copy of which has been included with this distribution in  |
// | the LICENSE file and is available through the web at                 |
// | http://bitflux.ch/editor/license.html                                |
// +----------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                        |
// +----------------------------------------------------------------------+
//
// $Id: bxeLoader.js,v 1.192 2004/01/15 02:30:05 chregu Exp $

const BXE_VERSION = "0.2";
const BXE_BUILD = "200401150330"

const E_FATAL = 1;

if (window.location.protocol == "file:" || window.location.host.match(/localhost.*/)) {
	var DebugOutput = false;
} else {
	var DebugOutput = false;
}

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;
var bxe_editable_page = true;

var startTimer = new Date();

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	defaultContainerName = "p";

	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG " + bxe_config.validationfile + " ");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	bxe_history_snapshot();
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("appendChildNode",bxe_appendChildNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("DeleteLink",bxe_DeleteLink,false);
	document.eDOMaddEventListener("CleanInline",bxe_CleanInline,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertObject,false);
	document.eDOMaddEventListener("InsertAsset",bxe_InsertAsset,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_history_undo()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_history_redo()}, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (!vali) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
		bxe_disableEditablePage();
	}
	else {
		bxe_about_box.addText("<br/>Document is valid.");

	}
	var endTimer = new Date();
	debug ("startTime: " + startTimer);
	debug ("endTime  : " + endTimer);
	dump ("Total Start Time: " + (endTimer - startTimer)/1000 + " sec\n");
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}

function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<commit_msg>automatic BuildDate Update<commit_after>// +----------------------------------------------------------------------+
// | Bitflux Editor                                                       |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | This software is published under the terms of the Apache Software    |
// | License a copy of which has been included with this distribution in  |
// | the LICENSE file and is available through the web at                 |
// | http://bitflux.ch/editor/license.html                                |
// +----------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                        |
// +----------------------------------------------------------------------+
//
// $Id: bxeLoader.js,v 1.193 2004/01/16 02:30:05 chregu Exp $

const BXE_VERSION = "0.2";
const BXE_BUILD = "200401160330"

const E_FATAL = 1;

if (window.location.protocol == "file:" || window.location.host.match(/localhost.*/)) {
	var DebugOutput = false;
} else {
	var DebugOutput = false;
}

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;
var bxe_editable_page = true;

var startTimer = new Date();

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	defaultContainerName = "p";

	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG " + bxe_config.validationfile + " ");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	bxe_history_snapshot();
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("appendChildNode",bxe_appendChildNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("DeleteLink",bxe_DeleteLink,false);
	document.eDOMaddEventListener("CleanInline",bxe_CleanInline,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertObject,false);
	document.eDOMaddEventListener("InsertAsset",bxe_InsertAsset,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_history_undo()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_history_redo()}, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (!vali) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
		bxe_disableEditablePage();
	}
	else {
		bxe_about_box.addText("<br/>Document is valid.");

	}
	var endTimer = new Date();
	debug ("startTime: " + startTimer);
	debug ("endTime  : " + endTimer);
	dump ("Total Start Time: " + (endTimer - startTimer)/1000 + " sec\n");
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}

function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<|endoftext|>