<commit_before>const azure = require("azure-storage")
const util = require("util")
const path = require("path")
const fs = require("fs")
const os = require("os")

const AZURE_STORAGE_NAME = process.env["AZURE_STORAGE_NAME"]
const AZURE_STORAGE_KEY = process.env["AZURE_STORAGE_KEY"]

const COMMIT_ID = process.env["TRAVIS_COMMIT"] || process.env["APPVEYOR_REPO_COMMIT"]

if (!COMMIT_ID || !AZURE_STORAGE_NAME || !AZURE_STORAGE_KEY) {
    console.log("Skipping upload since this is a PR")
    process.exit(0)
}

const blobService = azure.createBlobService(AZURE_STORAGE_NAME, AZURE_STORAGE_KEY)

const getBranch = () => process.env["APPVEYOR_REPO_BRANCH"] || process.env["TRAVIS_BRANCH"]

const branchName = getBranch()

if (branchName !== "master") {
    console.log("Skipping upload since this is not the master branch")
    process.exit(0)
}

const getDistFolder = () => path.join(__dirname, "..", "..", "dist")

const getVersion = () => {
    const packageJsonPath = path.join(getDistFolder(), "..", "package.json")
    const packageInfo = JSON.parse(fs.readFileSync(packageJsonPath))
    const version = packageInfo.version
    return version
}

const getBuildsForPlatform = version => {
    const platform = os.platform()

    switch (platform) {
        case "win32":
            return [`Oni-${version}-ia32-win.exe`, `Oni-${version}-ia32-win.zip`]
        case "darwin":
            return [`Oni-${version}-osx.dmg`]
        case "linux":
            return [
                `Oni-${version}-amd64-linux.deb`,
                `Oni-${version}-x86_64-linux.rpm`,
                `Oni-${version}-x64-linux.tar.gz`,
            ]
        default:
            return []
    }
}

const createContainerIfNotExists = containerName => {
    return new Promise((resolve, reject) => {
        blobService.createContainerIfNotExists(containerName, (err1, res1, response1) => {
            if (err1) {
                reject(err)
                return
            }

            resolve(res1)
        })
    })
}

const createBlockBlobFromFile = (containerName, blobName, filePath) => {
    console.log(
        `Uploading file - containerName: ${containerName} blobName: ${blobName} filePath: ${filePath}`,
    )

    return new Promise((resolve, reject) => {
        blobService.createBlockBlobFromLocalFile(
            containerName,
            blobName,
            filePath,
            (err, result) => {
                console.log("createBlockBlobFromLocalFile complete")
                if (err) {
                    reject(err)
                    return
                }

                resolve(result)
            },
        )
    })
}

const start = async () => {
    console.log("Creating download meta container...")
    await createContainerIfNotExists("downloadmeta")

    console.log("Creating container for commit: " + COMMIT_ID)
    await createContainerIfNotExists(COMMIT_ID)

    const version = getVersion()
    console.log("Version: " + version)

    const builds = getBuildsForPlatform(version)

    const distFolder = getDistFolder()
    console.log("Dist folder: " + distFolder)

    const allPromises = builds.map(build => {
        console.log("Uploading build: " + build)
        return createBlockBlobFromFile(COMMIT_ID, build, path.join(distFolder, build))
    })

    await Promise.all([allPromises])
}

start()
<commit_msg>Build - Package Uploader: Add manifest file if build is successful (#1939)<commit_after>const azure = require("azure-storage")
const util = require("util")
const path = require("path")
const fs = require("fs")
const os = require("os")

const AZURE_STORAGE_NAME = process.env["AZURE_STORAGE_NAME"]
const AZURE_STORAGE_KEY = process.env["AZURE_STORAGE_KEY"]

const COMMIT_ID = process.env["TRAVIS_COMMIT"] || process.env["APPVEYOR_REPO_COMMIT"]

if (!COMMIT_ID || !AZURE_STORAGE_NAME || !AZURE_STORAGE_KEY) {
    console.log("Skipping upload since this is a PR")
    process.exit(0)
}

const blobService = azure.createBlobService(AZURE_STORAGE_NAME, AZURE_STORAGE_KEY)

const getBranch = () => process.env["APPVEYOR_REPO_BRANCH"] || process.env["TRAVIS_BRANCH"]

const branchName = getBranch()

if (branchName !== "master") {
    console.log("Skipping upload since this is not the master branch")
    process.exit(0)
}

const getDistFolder = () => path.join(__dirname, "..", "..", "dist")

const getVersion = () => {
    const packageJsonPath = path.join(getDistFolder(), "..", "package.json")
    const packageInfo = JSON.parse(fs.readFileSync(packageJsonPath))
    const version = packageInfo.version
    return version
}

const getBuildsForPlatform = version => {
    const platform = os.platform()

    switch (platform) {
        case "win32":
            return [`Oni-${version}-ia32-win.exe`, `Oni-${version}-ia32-win.zip`]
        case "darwin":
            return [`Oni-${version}-osx.dmg`]
        case "linux":
            return [
                `Oni-${version}-amd64-linux.deb`,
                `Oni-${version}-x86_64-linux.rpm`,
                `Oni-${version}-x64-linux.tar.gz`,
            ]
        default:
            return []
    }
}

const createContainerIfNotExists = containerName => {
    return new Promise((resolve, reject) => {
        blobService.createContainerIfNotExists(containerName, (err1, res1, response1) => {
            if (err1) {
                reject(err)
                return
            }

            resolve(res1)
        })
    })
}

const createBlockBlobFromFile = (containerName, blobName, filePath) => {
    console.log(
        `Uploading file - containerName: ${containerName} blobName: ${blobName} filePath: ${filePath}`,
    )

    return new Promise((resolve, reject) => {
        blobService.createBlockBlobFromLocalFile(
            containerName,
            blobName,
            filePath,
            (err, result) => {
                console.log("createBlockBlobFromLocalFile complete")
                if (err) {
                    reject(err)
                } else {
                    resolve(result)
                }
            },
        )
    })
}

const createBlockBlobFromText = (containerName, blobName, text) => {
    console.log(`Uploading text - containerName: ${containerName} blobName: ${blobName}`)

    return new Promise((resolve, reject) => {
        blobService.createBlockBlobFromText(containerName, blobName, text, (err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(result)
            }
        })
    })
}

const getBlobsInContainer = containerName => {
    return new Promise((resolve, reject) => {
        blobService.listBlobsSegmented(containerName, null, (err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(result)
            }
        })
    })
}

const generateBuildMetadata = (branch, version) => {
    return {
        branch,
        version,
        releaseNotesUrl: "https://github.com/onivim/oni/wiki/Whats-New-in-Oni",
        releaseDate: new Date().getTime(),
        containerName: getContainerName(branch, version, COMMIT_ID),
    }
}

const getContainerName = (branch, version, commit) => {
    return branch + "-" + version.split(".").join("-") + "-" + commit
}

const start = async () => {
    console.log("Creating download meta container...")
    await createContainerIfNotExists("downloadmeta")

    const containerName = getContainerName(getBranch(), getVersion(), COMMIT_ID)

    console.log("Creating container for commit  " + COMMIT_ID + ":" + containerName)
    await createContainerIfNotExists(containerName)

    const version = getVersion()
    console.log("Version: " + version)

    const builds = getBuildsForPlatform(version)

    const distFolder = getDistFolder()
    console.log("Dist folder: " + distFolder)

    const allPromises = builds.map(build => {
        console.log("Uploading build: " + build)
        return createBlockBlobFromFile(containerName, build, path.join(distFolder, build))
    })

    await Promise.all(allPromises)

    console.log("Reading blobs for commit...")
    const currentBlobs = await getBlobsInContainer(containerName)
    const blobCount = currentBlobs.entries.length
    console.log("Found " + blobCount + " uploaded.")

    if (blobCount === 6) {
        console.log("All builds are uploaded. Creating metadata...")
        const metadata = generateBuildMetadata(getBranch(), getVersion())
        console.dir(metadata)
        const metadataAsString = JSON.stringify(metadata)
        await createBlockBlobFromText("downloadmeta", getBranch() + ".json", metadataAsString)
        console.log("Metadata uploaded!")
    } else {
        console.log("Not all blobs have been uploaded; skipping metadata")
    }
}

start()
<|endoftext|>


<commit_before>/*
 *
 * (c) Copyright Ascensio System Limited 2010-2018
 *
 * 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 Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * 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
 *
 */

/**
 *  Links.js
 *
 *  Created by Julia Radzhabova on 22.12.2017
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'core',
    'documenteditor/main/app/view/Links',
    'documenteditor/main/app/view/NoteSettingsDialog',
    'documenteditor/main/app/view/HyperlinkSettingsDialog',
    'documenteditor/main/app/view/TableOfContentsSettings',
    'documenteditor/main/app/view/BookmarksDialog'
], function () {
    'use strict';

    DE.Controllers.Links = Backbone.Controller.extend(_.extend({
        models : [],
        collections : [
        ],
        views : [
            'Links'
        ],
        sdkViewName : '#id_main',

        initialize: function () {

            this.addListeners({
                'Links': {
                    'links:contents': this.onTableContents,
                    'links:update': this.onTableContentsUpdate,
                    'links:notes': this.onNotesClick,
                    'links:hyperlink': this.onHyperlinkClick,
                    'links:bookmarks': this.onBookmarksClick
                },
                'DocumentHolder': {
                    'links:contents': this.onTableContents,
                    'links:update': this.onTableContentsUpdate
                }
            });
        },
        onLaunch: function () {
            this._state = {
                prcontrolsdisable:undefined
            };
        },

        setApi: function (api) {
            if (api) {
                this.api = api;
                this.api.asc_registerCallback('asc_onFocusObject', this.onApiFocusObject.bind(this));
                this.api.asc_registerCallback('asc_onCanAddHyperlink',      _.bind(this.onApiCanAddHyperlink, this));
                this.api.asc_registerCallback('asc_onCoAuthoringDisconnect',_.bind(this.onCoAuthoringDisconnect, this));
                Common.NotificationCenter.on('api:disconnect', _.bind(this.onCoAuthoringDisconnect, this));
                this.api.asc_registerCallback('asc_onShowContentControlsActions',_.bind(this.onShowContentControlsActions, this));
                this.api.asc_registerCallback('asc_onHideContentControlsActions',_.bind(this.onHideContentControlsActions, this));

            }
            return this;
        },

        setConfig: function(config) {
            this.toolbar = config.toolbar;
            this.view = this.createView('Links', {
                toolbar: this.toolbar.toolbar
            });
        },

        SetDisabled: function(state) {
            this.view && this.view.SetDisabled(state);
        },

        getView: function(name) {
            return !name && this.view ?
                this.view : Backbone.Controller.prototype.getView.call(this, name);
        },

        onCoAuthoringDisconnect: function() {
            this.SetDisabled(true);
        },

        onApiFocusObject: function(selectedObjects) {
            if (!this.toolbar.editMode) return;

            var pr, i = -1, type,
                paragraph_locked = false,
                header_locked = false,
                in_header = false,
                in_equation = false,
                in_image = false;

            while (++i < selectedObjects.length) {
                type = selectedObjects[i].get_ObjectType();
                pr   = selectedObjects[i].get_ObjectValue();

                if (type === Asc.c_oAscTypeSelectElement.Paragraph) {
                    paragraph_locked = pr.get_Locked();
                } else if (type === Asc.c_oAscTypeSelectElement.Header) {
                    header_locked = pr.get_Locked();
                    in_header = true;
                } else if (type === Asc.c_oAscTypeSelectElement.Image) {
                    in_image = true;
                } else if (type === Asc.c_oAscTypeSelectElement.Math) {
                    in_equation = true;
                }
            }

            this._state.prcontrolsdisable = paragraph_locked || header_locked;

            var need_disable = paragraph_locked || in_equation || in_image || in_header;
            _.each (this.view.btnsNotes, function(item){
                item.setDisabled(need_disable);
            }, this);
        },

        onApiCanAddHyperlink: function(value) {
            var need_disable = !value || this._state.prcontrolsdisable;

            if ( this.toolbar.editMode ) {
                _.each (this.view.btnsHyperlink, function(item){
                    item.setDisabled(need_disable);
                }, this);
            }
        },

        onHyperlinkClick: function(btn) {
            var me = this,
                win, props, text;

            if (me.api){

                var handlerDlg = function(dlg, result) {
                    if (result == 'ok') {
                        props = dlg.getSettings();
                        (text!==false)
                            ? me.api.add_Hyperlink(props)
                            : me.api.change_Hyperlink(props);
                    }

                    Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                };

                text = me.api.can_AddHyperlink();

                if (text !== false) {
                    win = new DE.Views.HyperlinkSettingsDialog({
                        api: me.api,
                        handler: handlerDlg
                    });

                    props = new Asc.CHyperlinkProperty();
                    props.put_Text(text);

                    win.show();
                    win.setSettings(props);
                } else {
                    var selectedElements = me.api.getSelectedElements();
                    if (selectedElements && _.isArray(selectedElements)){
                        _.each(selectedElements, function(el, i) {
                            if (selectedElements[i].get_ObjectType() == Asc.c_oAscTypeSelectElement.Hyperlink)
                                props = selectedElements[i].get_ObjectValue();
                        });
                    }
                    if (props) {
                        win = new DE.Views.HyperlinkSettingsDialog({
                            api: me.api,
                            handler: handlerDlg
                        });
                        win.show();
                        win.setSettings(props);
                    }
                }
            }

            Common.component.Analytics.trackEvent('ToolBar', 'Add Hyperlink');
        },

        onTableContents: function(type, currentTOC){
            currentTOC = !!currentTOC;
            var props = this.api.asc_GetTableOfContentsPr(currentTOC);
            switch (type) {
                case 0:
                    if (!props) {
                        props = new Asc.CTableOfContentsPr();
                        props.put_OutlineRange(1, 9);
                    }
                    props.put_Hyperlink(true);
                    props.put_ShowPageNumbers(true);
                    props.put_RightAlignTab(true);
                    props.put_TabLeader( Asc.c_oAscTabLeader.Dot);
                    (currentTOC) ? this.api.asc_SetTableOfContentsPr(props) : this.api.asc_AddTableOfContents(null, props);
                    break;
                case 1:
                    if (!props) {
                        props = new Asc.CTableOfContentsPr();
                        props.put_OutlineRange(1, 9);
                    }
                    props.put_Hyperlink(true);
                    props.put_ShowPageNumbers(false);
                    props.put_TabLeader( Asc.c_oAscTabLeader.None);
                    (currentTOC) ? this.api.asc_SetTableOfContentsPr(props) : this.api.asc_AddTableOfContents(null, props);
                    break;
                case 'settings':
                    var me = this,
                        win = new DE.Views.TableOfContentsSettings({
                        api: this.api,
                        props: props,
                        handler: function(result, value) {
                            if (result == 'ok') {
                                (props) ? me.api.asc_SetTableOfContentsPr(value) : me.api.asc_AddTableOfContents(null, value);
                            }
                            Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                        }
                    });
                    win.show();
                    break;
                case 'remove':
                    if (currentTOC)
                        currentTOC = props.get_InternalClass();
                    this.api.asc_RemoveTableOfContents(currentTOC);
                    break;
            }
            Common.NotificationCenter.trigger('edit:complete', this.toolbar);
        },

        onTableContentsUpdate: function(type, currentTOC){
            if (currentTOC)
                currentTOC = this.api.asc_GetTableOfContentsPr(currentTOC).get_InternalClass();
            this.api.asc_UpdateTableOfContents(type == 'pages', currentTOC);
            Common.NotificationCenter.trigger('edit:complete', this.toolbar);
        },

        onNotesClick: function(type) {
            var me = this;
            switch (type) {
                case 'ins_footnote':
                    this.api.asc_AddFootnote();
                    break;
                case 'delele':
                    Common.UI.warning({
                        msg: this.view.confirmDeleteFootnotes,
                        buttons: ['yes', 'no'],
                        primary: 'yes',
                        callback: _.bind(function (btn) {
                            if (btn == 'yes') {
                                this.api.asc_RemoveAllFootnotes();
                            }
                            Common.NotificationCenter.trigger('edit:complete', this.toolbar);
                        }, this)
                    });
                    break;
                case 'settings':
                    (new DE.Views.NoteSettingsDialog({
                        api: me.api,
                        handler: function (result, settings) {
                            if (settings) {
                                me.api.asc_SetFootnoteProps(settings.props, settings.applyToAll);
                                if (result == 'insert')
                                    me.api.asc_AddFootnote(settings.custom);
                            }
                            Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                        },
                        props: me.api.asc_GetFootnoteProps()
                    })).show();
                    break;
                case 'prev':
                    this.api.asc_GotoFootnote(false);
                    setTimeout(function() {
                        Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                    }, 50);
                    break;
                case 'next':
                    this.api.asc_GotoFootnote(true);
                    setTimeout(function() {
                        Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                    }, 50);
                    break;
            }
        },

        onBookmarksClick: function(btn) {
            var me = this;
            (new DE.Views.BookmarksDialog({
                api: me.api,
                props: me.api.asc_GetBookmarksManager(),
                handler: function (result, settings) {
                    if (settings) {
                    }
                    Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                }
            })).show();
        },

        onShowContentControlsActions: function(action, x, y) {
            var menu = (action==1) ? this.view.contentsUpdateMenu : this.view.contentsMenu,
                documentHolderView  = this.getApplication().getController('DocumentHolder').documentHolder,
                menuContainer = documentHolderView.cmpEl.find(Common.Utils.String.format('#menu-container-{0}', menu.id)),
                me = this;

            if (!menu) return;
            this._fromShowContentControls = true;
            Common.UI.Menu.Manager.hideAll();

            if (!menu.rendered) {
                // Prepare menu container
                if (menuContainer.length < 1) {
                    menuContainer = $(Common.Utils.String.format('

', menu.id));
                    documentHolderView.cmpEl.append(menuContainer);
                }

                menu.render(menuContainer);
                menu.cmpEl.attr({tabindex: "-1"});
                menu.on('hide:after', function(){
                    if (!me._fromShowContentControls)
                        me.api.asc_UncheckContentControlButtons();
                });
            }

            menuContainer.css({left: x, top : y});
            menuContainer.attr('data-value', 'prevent-canvas-click');
            documentHolderView._preventClick = true;
            menu.show();

            menu.alignPosition();
            _.delay(function() {
                menu.cmpEl.focus();
            }, 10);
            this._fromShowContentControls = false;
        },

        onHideContentControlsActions: function() {
            this.view.contentsMenu && this.view.contentsMenu.hide();
            this.view.contentsUpdateMenu && this.view.contentsUpdateMenu.hide();
        }

    }, DE.Controllers.Links || {}));
});<commit_msg>[DE] Disable notes and bookmarks for plain text content control<commit_after>/*
 *
 * (c) Copyright Ascensio System Limited 2010-2018
 *
 * 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 Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * 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
 *
 */

/**
 *  Links.js
 *
 *  Created by Julia Radzhabova on 22.12.2017
 *  Copyright (c) 2018 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'core',
    'documenteditor/main/app/view/Links',
    'documenteditor/main/app/view/NoteSettingsDialog',
    'documenteditor/main/app/view/HyperlinkSettingsDialog',
    'documenteditor/main/app/view/TableOfContentsSettings',
    'documenteditor/main/app/view/BookmarksDialog'
], function () {
    'use strict';

    DE.Controllers.Links = Backbone.Controller.extend(_.extend({
        models : [],
        collections : [
        ],
        views : [
            'Links'
        ],
        sdkViewName : '#id_main',

        initialize: function () {

            this.addListeners({
                'Links': {
                    'links:contents': this.onTableContents,
                    'links:update': this.onTableContentsUpdate,
                    'links:notes': this.onNotesClick,
                    'links:hyperlink': this.onHyperlinkClick,
                    'links:bookmarks': this.onBookmarksClick
                },
                'DocumentHolder': {
                    'links:contents': this.onTableContents,
                    'links:update': this.onTableContentsUpdate
                }
            });
        },
        onLaunch: function () {
            this._state = {
                prcontrolsdisable:undefined
            };
        },

        setApi: function (api) {
            if (api) {
                this.api = api;
                this.api.asc_registerCallback('asc_onFocusObject', this.onApiFocusObject.bind(this));
                this.api.asc_registerCallback('asc_onCanAddHyperlink',      _.bind(this.onApiCanAddHyperlink, this));
                this.api.asc_registerCallback('asc_onCoAuthoringDisconnect',_.bind(this.onCoAuthoringDisconnect, this));
                Common.NotificationCenter.on('api:disconnect', _.bind(this.onCoAuthoringDisconnect, this));
                this.api.asc_registerCallback('asc_onShowContentControlsActions',_.bind(this.onShowContentControlsActions, this));
                this.api.asc_registerCallback('asc_onHideContentControlsActions',_.bind(this.onHideContentControlsActions, this));

            }
            return this;
        },

        setConfig: function(config) {
            this.toolbar = config.toolbar;
            this.view = this.createView('Links', {
                toolbar: this.toolbar.toolbar
            });
        },

        SetDisabled: function(state) {
            this.view && this.view.SetDisabled(state);
        },

        getView: function(name) {
            return !name && this.view ?
                this.view : Backbone.Controller.prototype.getView.call(this, name);
        },

        onCoAuthoringDisconnect: function() {
            this.SetDisabled(true);
        },

        onApiFocusObject: function(selectedObjects) {
            if (!this.toolbar.editMode) return;

            var pr, i = -1, type,
                paragraph_locked = false,
                header_locked = false,
                in_header = false,
                in_equation = false,
                in_image = false;

            while (++i < selectedObjects.length) {
                type = selectedObjects[i].get_ObjectType();
                pr   = selectedObjects[i].get_ObjectValue();

                if (type === Asc.c_oAscTypeSelectElement.Paragraph) {
                    paragraph_locked = pr.get_Locked();
                } else if (type === Asc.c_oAscTypeSelectElement.Header) {
                    header_locked = pr.get_Locked();
                    in_header = true;
                } else if (type === Asc.c_oAscTypeSelectElement.Image) {
                    in_image = true;
                } else if (type === Asc.c_oAscTypeSelectElement.Math) {
                    in_equation = true;
                }
            }

            this._state.prcontrolsdisable = paragraph_locked || header_locked;

            var control_props = this.api.asc_IsContentControl() ? this.api.asc_GetContentControlProperties() : null,
                control_plain = (control_props) ? (control_props.get_ContentControlType()==Asc.c_oAscSdtLevelType.Inline) : false;

            var need_disable = paragraph_locked || in_equation || in_image || in_header || control_plain;
            _.each (this.view.btnsNotes, function(item){
                item.setDisabled(need_disable);
            }, this);

            need_disable = paragraph_locked || header_locked || control_plain;
            this.view.btnBookmarks.setDisabled(need_disable);
        },

        onApiCanAddHyperlink: function(value) {
            var need_disable = !value || this._state.prcontrolsdisable;

            if ( this.toolbar.editMode ) {
                _.each (this.view.btnsHyperlink, function(item){
                    item.setDisabled(need_disable);
                }, this);
            }
        },

        onHyperlinkClick: function(btn) {
            var me = this,
                win, props, text;

            if (me.api){

                var handlerDlg = function(dlg, result) {
                    if (result == 'ok') {
                        props = dlg.getSettings();
                        (text!==false)
                            ? me.api.add_Hyperlink(props)
                            : me.api.change_Hyperlink(props);
                    }

                    Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                };

                text = me.api.can_AddHyperlink();

                if (text !== false) {
                    win = new DE.Views.HyperlinkSettingsDialog({
                        api: me.api,
                        handler: handlerDlg
                    });

                    props = new Asc.CHyperlinkProperty();
                    props.put_Text(text);

                    win.show();
                    win.setSettings(props);
                } else {
                    var selectedElements = me.api.getSelectedElements();
                    if (selectedElements && _.isArray(selectedElements)){
                        _.each(selectedElements, function(el, i) {
                            if (selectedElements[i].get_ObjectType() == Asc.c_oAscTypeSelectElement.Hyperlink)
                                props = selectedElements[i].get_ObjectValue();
                        });
                    }
                    if (props) {
                        win = new DE.Views.HyperlinkSettingsDialog({
                            api: me.api,
                            handler: handlerDlg
                        });
                        win.show();
                        win.setSettings(props);
                    }
                }
            }

            Common.component.Analytics.trackEvent('ToolBar', 'Add Hyperlink');
        },

        onTableContents: function(type, currentTOC){
            currentTOC = !!currentTOC;
            var props = this.api.asc_GetTableOfContentsPr(currentTOC);
            switch (type) {
                case 0:
                    if (!props) {
                        props = new Asc.CTableOfContentsPr();
                        props.put_OutlineRange(1, 9);
                    }
                    props.put_Hyperlink(true);
                    props.put_ShowPageNumbers(true);
                    props.put_RightAlignTab(true);
                    props.put_TabLeader( Asc.c_oAscTabLeader.Dot);
                    (currentTOC) ? this.api.asc_SetTableOfContentsPr(props) : this.api.asc_AddTableOfContents(null, props);
                    break;
                case 1:
                    if (!props) {
                        props = new Asc.CTableOfContentsPr();
                        props.put_OutlineRange(1, 9);
                    }
                    props.put_Hyperlink(true);
                    props.put_ShowPageNumbers(false);
                    props.put_TabLeader( Asc.c_oAscTabLeader.None);
                    (currentTOC) ? this.api.asc_SetTableOfContentsPr(props) : this.api.asc_AddTableOfContents(null, props);
                    break;
                case 'settings':
                    var me = this,
                        win = new DE.Views.TableOfContentsSettings({
                        api: this.api,
                        props: props,
                        handler: function(result, value) {
                            if (result == 'ok') {
                                (props) ? me.api.asc_SetTableOfContentsPr(value) : me.api.asc_AddTableOfContents(null, value);
                            }
                            Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                        }
                    });
                    win.show();
                    break;
                case 'remove':
                    if (currentTOC)
                        currentTOC = props.get_InternalClass();
                    this.api.asc_RemoveTableOfContents(currentTOC);
                    break;
            }
            Common.NotificationCenter.trigger('edit:complete', this.toolbar);
        },

        onTableContentsUpdate: function(type, currentTOC){
            if (currentTOC)
                currentTOC = this.api.asc_GetTableOfContentsPr(currentTOC).get_InternalClass();
            this.api.asc_UpdateTableOfContents(type == 'pages', currentTOC);
            Common.NotificationCenter.trigger('edit:complete', this.toolbar);
        },

        onNotesClick: function(type) {
            var me = this;
            switch (type) {
                case 'ins_footnote':
                    this.api.asc_AddFootnote();
                    break;
                case 'delele':
                    Common.UI.warning({
                        msg: this.view.confirmDeleteFootnotes,
                        buttons: ['yes', 'no'],
                        primary: 'yes',
                        callback: _.bind(function (btn) {
                            if (btn == 'yes') {
                                this.api.asc_RemoveAllFootnotes();
                            }
                            Common.NotificationCenter.trigger('edit:complete', this.toolbar);
                        }, this)
                    });
                    break;
                case 'settings':
                    (new DE.Views.NoteSettingsDialog({
                        api: me.api,
                        handler: function (result, settings) {
                            if (settings) {
                                me.api.asc_SetFootnoteProps(settings.props, settings.applyToAll);
                                if (result == 'insert')
                                    me.api.asc_AddFootnote(settings.custom);
                            }
                            Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                        },
                        props: me.api.asc_GetFootnoteProps()
                    })).show();
                    break;
                case 'prev':
                    this.api.asc_GotoFootnote(false);
                    setTimeout(function() {
                        Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                    }, 50);
                    break;
                case 'next':
                    this.api.asc_GotoFootnote(true);
                    setTimeout(function() {
                        Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                    }, 50);
                    break;
            }
        },

        onBookmarksClick: function(btn) {
            var me = this;
            (new DE.Views.BookmarksDialog({
                api: me.api,
                props: me.api.asc_GetBookmarksManager(),
                handler: function (result, settings) {
                    if (settings) {
                    }
                    Common.NotificationCenter.trigger('edit:complete', me.toolbar);
                }
            })).show();
        },

        onShowContentControlsActions: function(action, x, y) {
            var menu = (action==1) ? this.view.contentsUpdateMenu : this.view.contentsMenu,
                documentHolderView  = this.getApplication().getController('DocumentHolder').documentHolder,
                menuContainer = documentHolderView.cmpEl.find(Common.Utils.String.format('#menu-container-{0}', menu.id)),
                me = this;

            if (!menu) return;
            this._fromShowContentControls = true;
            Common.UI.Menu.Manager.hideAll();

            if (!menu.rendered) {
                // Prepare menu container
                if (menuContainer.length < 1) {
                    menuContainer = $(Common.Utils.String.format('

', menu.id));
                    documentHolderView.cmpEl.append(menuContainer);
                }

                menu.render(menuContainer);
                menu.cmpEl.attr({tabindex: "-1"});
                menu.on('hide:after', function(){
                    if (!me._fromShowContentControls)
                        me.api.asc_UncheckContentControlButtons();
                });
            }

            menuContainer.css({left: x, top : y});
            menuContainer.attr('data-value', 'prevent-canvas-click');
            documentHolderView._preventClick = true;
            menu.show();

            menu.alignPosition();
            _.delay(function() {
                menu.cmpEl.focus();
            }, 10);
            this._fromShowContentControls = false;
        },

        onHideContentControlsActions: function() {
            this.view.contentsMenu && this.view.contentsMenu.hide();
            this.view.contentsUpdateMenu && this.view.contentsUpdateMenu.hide();
        }

    }, DE.Controllers.Links || {}));
});<|endoftext|>


<commit_before>var ChatView = Backbone.View.extend({
    tagName: 'div id="chat-view"',
    chatTemplate: Handlebars.compile( $('#tpl-chat').html() ),
    nameTemplate: Handlebars.compile( $('#tpl-chat-name').html() ),
    events: {
        "click #connect": 'newUser',
        "click #send": 'send'
    },
    initialize: function () {
        _.bindAll(this, 'newUser', 'send', 'render');
        this.collection.cnx.on('change', this.render);
        this.collection.on('add', this.render);
        this.collection.on('connect', this.connect);
        this.collection.on('disconnect', this.disconnect);
    },
    disconnect: function() {
        $('div.bg-success').removeClass('bg-success').addClass('bg-danger').text('disconnected');
    },
    newUser: function () {
        var val = $('#user-name').val();
        if (val) {
            this.collection.cnx.set("user", val);
        }
    },
    send: function () {
       this.collection.send( $('#new-message').val() );
    },
    render: function (e) {
        if (this.collection.cnx.get('user')) {
            $(this.el).html(this.chatTemplate({ color: this.collection.cnx.get('color'), messages: this.collection.toJSON() }));
        } else {
            $(this.el).html(this.nameTemplate());
        }
        return this;
    }
});<commit_msg>fixes View.extend function<commit_after>var ChatView = Backbone.View.extend({
    tagName: 'chat-view',
    chatTemplate: Handlebars.compile( $('#tpl-chat').html() ),
    nameTemplate: Handlebars.compile( $('#tpl-chat-name').html() ),
    events: {
        "click #connect": 'newUser',
        "click #send": 'send'
    },
    initialize: function () {
        _.bindAll(this, 'newUser', 'send', 'render');
        this.collection.cnx.on('change', this.render);
        this.collection.on('add', this.render);
        this.collection.on('connect', this.connect);
        this.collection.on('disconnect', this.disconnect);
    },
    disconnect: function() {
        $('div.bg-success').removeClass('bg-success').addClass('bg-danger').text('disconnected');
    },
    newUser: function () {
        var val = $('#user-name').val();
        if (val) {
            this.collection.cnx.set("user", val);
        }
    },
    send: function () {
       this.collection.send( $('#new-message').val() );
    },
    render: function (e) {
        if (this.collection.cnx.get('user')) {
            $(this.el).html(this.chatTemplate({ color: this.collection.cnx.get('color'), messages: this.collection.toJSON() }));
        } else {
            $(this.el).html(this.nameTemplate());
        }
        return this;
    }
});<|endoftext|>


<commit_before>/*eslint-env mocha */
'use strict';

var assert = require('assert');
var grunt = require('grunt');

describe('openui5_concat_core', function() {

	it('should create the concatinated sap-ui-core-dbg.js', function() {

		var coreJsContent = grunt.file.read('target/openui5-sap.ui.core/resources/sap-ui-core-dbg.js');
		assert.ok(coreJsContent.indexOf('sap.ui.requireSync("sap/ui/core/Core"); sap.ui.getCore().boot && sap.ui.getCore().boot();') !== -1, 'Did contain the bootstrap for core');

	});

	it('should create the concatinated sap-ui-core-nojQuery-dbg.js', function() {

		var coreNoQueryJsContent = grunt.file.read('target/openui5-sap.ui.core/resources/sap-ui-core-nojQuery-dbg.js');
		assert.ok(coreNoQueryJsContent.indexOf('sap.ui.requireSync("sap/ui/core/Core"); sap.ui.getCore().boot && sap.ui.getCore().boot();') !== -1, 'Did contain the bootstrap for core');

	});

	it('should create the concatinated sap-ui-core.js', function() {

		var coreJsContent = grunt.file.read('target/openui5-sap.ui.core/resources/sap-ui-core.js');
		assert.ok(coreJsContent.indexOf('sap.ui.getCore().boot&&sap.ui.getCore().boot()') !== -1, 'Did contain the bootstrap for core');

	});

	it('should create the concatinated sap-ui-core-nojQuery.js', function() {

		var coreNoQueryJsContent = grunt.file.read('target/openui5-sap.ui.core/resources/sap-ui-core-nojQuery.js');
		assert.ok(coreNoQueryJsContent.indexOf('sap.ui.getCore().boot&&sap.ui.getCore().boot()') !== -1, 'Did contain the bootstrap for core');

	});

	it('should create the sap-ui-debug.js', function() {

		var sapUiDebugContent = grunt.file.read('target/openui5-sap.ui.core/resources/sap-ui-debug.js');
		assert.ok(sapUiDebugContent.indexOf("raw:sap/ui/debug/ControlTree.js") !== -1, 'Did contain the Control Tree');
		assert.ok(sapUiDebugContent.indexOf('sap.ui.requireSync("sap/ui/core/Core"); sap.ui.getCore().boot && sap.ui.getCore().boot();') === -1, 'Did not contain the bootstrap for core');

	});
});
<commit_msg>[INTERNAL] grunt (test): remove test for sap-ui-debug concatenation<commit_after>/*eslint-env mocha */
'use strict';

var assert = require('assert');
var grunt = require('grunt');

describe('openui5_concat_core', function() {

	it('should create the concatenated sap-ui-core-dbg.js', function() {

		var coreJsContent = grunt.file.read('target/openui5-sap.ui.core/resources/sap-ui-core-dbg.js');
		assert.ok(coreJsContent.indexOf('sap.ui.requireSync("sap/ui/core/Core"); sap.ui.getCore().boot && sap.ui.getCore().boot();') !== -1, 'Did contain the bootstrap for core');

	});

	it('should create the concatenated sap-ui-core-nojQuery-dbg.js', function() {

		var coreNoQueryJsContent = grunt.file.read('target/openui5-sap.ui.core/resources/sap-ui-core-nojQuery-dbg.js');
		assert.ok(coreNoQueryJsContent.indexOf('sap.ui.requireSync("sap/ui/core/Core"); sap.ui.getCore().boot && sap.ui.getCore().boot();') !== -1, 'Did contain the bootstrap for core');

	});

	it('should create the concatenated sap-ui-core.js', function() {

		var coreJsContent = grunt.file.read('target/openui5-sap.ui.core/resources/sap-ui-core.js');
		assert.ok(coreJsContent.indexOf('sap.ui.getCore().boot&&sap.ui.getCore().boot()') !== -1, 'Did contain the bootstrap for core');

	});

	it('should create the concatenated sap-ui-core-nojQuery.js', function() {

		var coreNoQueryJsContent = grunt.file.read('target/openui5-sap.ui.core/resources/sap-ui-core-nojQuery.js');
		assert.ok(coreNoQueryJsContent.indexOf('sap.ui.getCore().boot&&sap.ui.getCore().boot()') !== -1, 'Did contain the bootstrap for core');

	});
});
<|endoftext|>


<commit_before>class MCAttributeDateComponentController {
    /*@ngInject*/
    constructor(experimentsService, toast, $stateParams) {
        this.experimentsService = experimentsService;
        this.toast = toast;
        this.$stateParams = $stateParams;
        this.projectId = $stateParams.project_id;
        this.experimentId = $stateParams.experiment_id;
        this.datePickerOptions = {
            formatYear: 'yy',
            startingDay: 1
        };
        this.date = new Date(this.setting.value);
    }

    openDatePicker($event, prop) {
        $event.preventDefault();
        $event.stopPropagation();
        prop.opened = true;
    }

    updateDateProperty(property) {

        property.value =
            this.experimentsService.convertDateValueForTransport(this.date);

        property.setup_attribute = this.attribute;
        let propertyArgs = {
            template_id: this.templateId,
            properties: [property]
        };

        this.experimentsService.updateProcess(this.projectId, this.experimentId, this.processId, propertyArgs)
            .then(
                () => null,
                () => this.toast.error('Unable to update property')
            );
    }
}

angular.module('materialscommons').component('mcAttributeDate', {
    templateUrl: 'app/global.components/attribute/mc-attribute-date.html',
    controller: MCAttributeDateComponentController,
    bindings: {
        setting: '<',
        templateId: '<',
        attribute: '<',
        processId: '<'
    }
});
<commit_msg>Fixed default date on Setup - specificially on Create Sample Manufacture date - see issue #935<commit_after>class MCAttributeDateComponentController {
    /*@ngInject*/
    constructor(experimentsService, toast, $stateParams) {
        this.experimentsService = experimentsService;
        this.toast = toast;
        this.$stateParams = $stateParams;
        this.projectId = $stateParams.project_id;
        this.experimentId = $stateParams.experiment_id;
        this.datePickerOptions = {
            formatYear: 'yy',
            startingDay: 1
        };
        if (this.setting.value) {
            this.date = new Date(this.setting.value);
        } else {
            this.date = new Date();
        }
        console.log(MCAttributeDateComponentController, this.date)
    }

    openDatePicker($event, prop) {
        $event.preventDefault();
        $event.stopPropagation();
        prop.opened = true;
    }

    updateDateProperty(property) {

        property.value =
            this.experimentsService.convertDateValueForTransport(this.date);

        property.setup_attribute = this.attribute;
        let propertyArgs = {
            template_id: this.templateId,
            properties: [property]
        };

        this.experimentsService.updateProcess(this.projectId, this.experimentId, this.processId, propertyArgs)
            .then(
                () => null,
                () => this.toast.error('Unable to update property')
            );
    }
}

angular.module('materialscommons').component('mcAttributeDate', {
    templateUrl: 'app/global.components/attribute/mc-attribute-date.html',
    controller: MCAttributeDateComponentController,
    bindings: {
        setting: '<',
        templateId: '<',
        attribute: '<',
        processId: '<'
    }
});
<|endoftext|>


<commit_before>var EditBox = Utils.createFactory({
	displayName: 'EditBox',

	getInitialState: function() {
		return {value: ''};
	},

	setValue: function(newValue) {
		this.setState({value: newValue});
	},

	render: function() {
		return (
			Div({className: "editBox", style: {left: this.props.left, top: this.props.top}},
				Label({style: {color: this.props.color}}, this.props.label + ":"),
				Input({type: "number", name: this.props.name, value: this.state.value, onChange: this._onChange, onBlur: this._onBlur, style: {font: Styles.LABEL_FONT, width: this._computeWidth() }})
			)
		);
	},

	_onChange: function(e) {
		this.setState({value: e.target.value});
	},

	_onBlur: function(e) {
		this.props.onBlur(e);
	},

	_computeWidth: function() {
		var EXTRA_SPACE = 15; // add extra space to compensate for browser behavior
		var MIN_WIDTH = 30;

		var textWidth = Utils.getTextWidth(this.state.value, Styles.LABEL_FONT);

		return Math.max(MIN_WIDTH, textWidth) + EXTRA_SPACE;
	}
});
<commit_msg>Fixed issue with input boxes.<commit_after>var EditBox = Utils.createFactory({
	displayName: 'EditBox',

	getInitialState: function() {
		return {value: ''};
	},

	setValue: function(newValue) {
		this.setState({value: newValue});
	},

	render: function() {
		return (
			Div({className: "editBox", style: {left: this.props.left, top: this.props.top}},
				Label({style: {color: this.props.color}}, this.props.label + ":"),
				Input({type: "text", name: this.props.name, value: this.state.value, onChange: this._onChange, onBlur: this._onBlur, style: {font: Styles.LABEL_FONT, width: this._computeWidth() }})
			)
		);
	},

	_onChange: function(e) {
		this.setState({value: e.target.value});
	},

	_onBlur: function(e) {
		this.props.onBlur(e);
	},

	_computeWidth: function() {
		var EXTRA_SPACE = 10; // add extra space to compensate for browser behavior
		var MIN_WIDTH = 30;

		var textWidth = Utils.getTextWidth(this.state.value, Styles.LABEL_FONT);

		return Math.max(MIN_WIDTH, textWidth) + EXTRA_SPACE;
	}
});
<|endoftext|>


<commit_before>'use strict'

define([
    'file-saver',
    'src/util/api',
    'src/util/ui',
    './libs'
] , function (fileSaver, API, UI, libs) {

    var SD=libs.SD;
    var CCE=libs.CCE;

    class Nmr1dManager {
        constructor() {

        }

        handleAction(action) {
            switch (action.name) {
                case 'updateRanges':
                    var ppOptions = API.getData("nmr1hOptions").resurrect();
                    var currentRanges = API.getData("currentNmrRanges");
                    SD.formatter.updateRanges(currentRanges, {sum: ppOptions.integral});
                    currentRanges.triggerChange();
                    break;
                case 'downloadSVG':
                    var blob = new Blob([action.value+""], {type: "application/jcamp-dx;charset=utf-8"});
                    fileSaver(blob, 'spectra.svg');
                    break;
                case 'toggleNMR1hAdvancedOptions':
                    var advancedOptions1H = ! API.cache("nmr1hAdvancedOptions");
                    API.cache("nmr1hAdvancedOptions", advancedOptions1H);
                    if (advancedOptions1H) {
                        API.createData("nmr1hOndeTemplate", API.getData("nmr1hOndeTemplates").full);
                    } else {
                        API.createData("nmr1hOndeTemplate", API.getData("nmr1hOndeTemplates").short);
                    }

                    break;
                case 'resetNMR1d':
                case 'resetNMR1d':
                    var type = action.name.replace(/[^0-9]/g,'');

                    type = type + 'd';
                    API.createData('blackNMR' + type, null);
                    API.createData('annotationNMR' + type, null);
                    API.createData('acsNMR' + type, null);
                    break;
                case 'executePeakPicking':
                    // the action may be generated by clicking on a line or clicking on the button to
                    // recalculate the peak picking.
                    console.log('executePeakPicking);')
                    var currentNmr;
                    // if we click on a line, the action will be throw with the current NMR
                    if (action.value.dimension) {
                        currentNmr = action.value;
                        if (currentNmr.dimension>1) {
                            if (this.blackNMR2d !== currentNmr.jcamp) {
                                API.createData('blackNMR2d', currentNmr.jcamp.data);
                                this.blackNMR2d = currentNmr.jcamp;
                            }
                            // No peak picking currently for 2D
                            API.switchToLayer('nmr2D');
                            return;
                        } else {
                            if (this.blackNMR1d !== currentNmr.jcamp) {
                                API.createData('blackNMR1d', currentNmr.jcamp.data);
                                this.blackNMR1d = currentNmr.jcamp;
                            }
                            API.switchToLayer('Default layer');
                        }
                    } else { // we click on the button to redo assignment
                        currentNmr = API.getData('currentNmr');
                        if (currentNmr.dimension>1) {
                            if (typeof UI != "undefined") {
                                UI.showNotification('Peak picking can only be applied on 1D spectra','warning');
                            }
                            return;
                        }
                    }
                    console.log('action.value', action.value)
                    if (action.value.integral){//Fired from button
                        this._doAssignment(currentNmr);
                    } else {
                        console.log('currentNmr', currentNmr);
                        if(!currentNmr.range || ! currentNmr.range.length) {
                            this._doAssignment(currentNmr);
                            // } else {
                            // API.setVariable("editedRange",API.getVariable('currentNmr'),["range"]);
                        } else {
                            this._createNMRannotationsAndACS(currentNmr);
                        }
                    }
                    break;
                default:
                    return false;
            }
            return true;
        }

        _doAssignment(currentNmr) {
            currentNmr.getChild(['jcamp', 'data']).then((jcamp) => {
                jcamp = String(jcamp.get());
                var ppOptions = API.getData("nmr1hOptions").resurrect();
                var spectrum = SD.NMR.fromJcamp(jcamp);
                var intFN = 0;
                if(ppOptions.integralFn=="peaks"){
                    intFN=1;
                }
                var peakPicking = spectrum.nmrPeakDetection({
                    nH:ppOptions.integral,
                    realTop:true,
                    thresholdFactor:ppOptions.noiseFactor,
                    clean:ppOptions.clean,
                    compile:ppOptions.compile,
                    optimize:ppOptions.optimize,
                    integralFn:intFN,
                    idPrefix:spectrum.getNucleus()+"",
                    gsdOptions:{minMaxRatio:0.001, smoothY:false, broadWidth:0},
                    format:"new"
                });
                currentNmr.setChildSync(['range'], peakPicking);
                this._createNMRannotationsAndACS(currentNmr);
            });
        }

        _createNMRannotationsAndACS(currentNmr) {
            console.log('create annoations');
            var peakPicking = JSON.parse(JSON.stringify(API.getData("currentNmrRanges")));

            // TODO : this code hsould not be here !
            //Recompile multiplicity
            for (var i=0; i<peakPicking.length; i++){
                var peak = peakPicking[i];
                for (var j=0; j<peak.signal.length; j++){
                    var signal = peak.signal[j];
                    if (signal.j && ! signal.multiplicity) {
                        signal.multiplicity = "";
                        for (var k=0; k<signal.j.length;k++){
                            signal.multiplicity+=signal.j[k].multiplicity;
                        }
                    }
                }
            }

            API.createData("annotationsNMR1d", SD.GUI.annotations1D(peakPicking, {
                line:1,
                fillColor:"green",
                strokeWidth:0
            }));
            API.createData("acsNMR1d",SD.formatter.toACS(peakPicking, {
                rangeForMultiplet:true,
                nucleus:currentNmr.nucleus[0],
                observe:Math.round(currentNmr.frequency/10)*10
            }));
        }

        updateIntegral() {
            var chemcalc=CCE.analyseMF(API.getData('mf')+'');
            if (chemcalc && chemcalc.atoms && chemcalc.atoms.H) {
                var nmr1hOptions=API.getData('nmr1hOptions');
                if (nmr1hOptions) nmr1hOptions.integral=chemcalc.atoms.H;
                nmr1hOptions.triggerChange();
            }
        }

        initializeNMRAssignment() {
            var promise = Promise.resolve();
            promise = promise.then(() => API.createData('nmr1hOptions', {
                    "noiseFactor": 0.8,
                    "clean": true,
                    "compile": true,
                    "optimize": false,
                    "integralFn": "sum",
                    "integral": 30,
                    "type": "1H"
                })
            );

            promise=promise.then(() => API.createData('nmr1hOndeTemplates', {
                "full": {
                    "type": "object",
                    "properties": {
                        "integral": {
                            "type": "number",
                            "title": "value to fit the spectrum integral",
                            "label": "Integral"
                        },
                        "noiseFactor": {
                            "type": "number",
                            "title": "Mutiplier of the auto-detected noise level",
                            "label": "noiseFactor"
                        },
                        "clean": {
                            "type": "boolean",
                            "title": "Delete signals with integration less than 0.5",
                            "label": "clean"
                        },
                        "compile": {
                            "type": "boolean",
                            "title": "Compile the multiplets",
                            "label": "compile"
                        },
                        "optimize": {
                            "type": "boolean",
                            "title": "Optimize the peaks to fit the spectrum",
                            "label": "optimize"
                        },
                        "integralFn": {
                            "type": "string",
                            "title": "Type of integration",
                            "label": "Integral type",
                            "enum": [
                                "sum",
                                "peaks"
                            ]
                        },
                        "type": {
                            "type": "string",
                            "title": "Nucleus",
                            "label": "Nucleus",
                            "editable": false
                        }
                    }
                },
                "short": {
                    "type": "object",
                    "properties": {
                        "integral": {
                            "type": "number",
                            "title": "value to fit the spectrum integral",
                            "label": "Integral"
                        }
                    }
                }
            }));
            promise=promise.then((nmr1hOndeTemplates) => API.createData('nmr1hOndeTemplate', nmr1hOndeTemplates.short));

            promise=promise.then(() => this.updateIntegral());
            // TODO we should recalculate the integration : updateIntegral

            return promise;
        }
    }

    return Nmr1dManager;
});

<commit_msg>Update Nmr1dManager.js<commit_after>'use strict'

define([
    'file-saver',
    'src/util/api',
    'src/util/ui',
    './libs'
] , function (fileSaver, API, UI, libs) {

    var SD=libs.SD;
    var CCE=libs.CCE;

    class Nmr1dManager {
        constructor() {

        }

        handleAction(action) {
            switch (action.name) {
                case 'updateRanges':
                    var ppOptions = API.getData("nmr1hOptions").resurrect();
                    var currentRanges = API.getData("currentNmrRanges");
                    SD.formatter.updateIntegrals(currentRanges, {sum: ppOptions.integral});
                    currentRanges.triggerChange();
                    break;
                case 'downloadSVG':
                    var blob = new Blob([action.value+""], {type: "application/jcamp-dx;charset=utf-8"});
                    fileSaver(blob, 'spectra.svg');
                    break;
                case 'toggleNMR1hAdvancedOptions':
                    var advancedOptions1H = ! API.cache("nmr1hAdvancedOptions");
                    API.cache("nmr1hAdvancedOptions", advancedOptions1H);
                    if (advancedOptions1H) {
                        API.createData("nmr1hOndeTemplate", API.getData("nmr1hOndeTemplates").full);
                    } else {
                        API.createData("nmr1hOndeTemplate", API.getData("nmr1hOndeTemplates").short);
                    }

                    break;
                case 'resetNMR1d':
                case 'resetNMR1d':
                    var type = action.name.replace(/[^0-9]/g,'');

                    type = type + 'd';
                    API.createData('blackNMR' + type, null);
                    API.createData('annotationNMR' + type, null);
                    API.createData('acsNMR' + type, null);
                    break;
                case 'executePeakPicking':
                    // the action may be generated by clicking on a line or clicking on the button to
                    // recalculate the peak picking.
                    console.log('executePeakPicking);')
                    var currentNmr;
                    // if we click on a line, the action will be throw with the current NMR
                    if (action.value.dimension) {
                        currentNmr = action.value;
                        if (currentNmr.dimension>1) {
                            if (this.blackNMR2d !== currentNmr.jcamp) {
                                API.createData('blackNMR2d', currentNmr.jcamp.data);
                                this.blackNMR2d = currentNmr.jcamp;
                            }
                            // No peak picking currently for 2D
                            API.switchToLayer('nmr2D');
                            return;
                        } else {
                            if (this.blackNMR1d !== currentNmr.jcamp) {
                                API.createData('blackNMR1d', currentNmr.jcamp.data);
                                this.blackNMR1d = currentNmr.jcamp;
                            }
                            API.switchToLayer('Default layer');
                        }
                    } else { // we click on the button to redo assignment
                        currentNmr = API.getData('currentNmr');
                        if (currentNmr.dimension>1) {
                            if (typeof UI != "undefined") {
                                UI.showNotification('Peak picking can only be applied on 1D spectra','warning');
                            }
                            return;
                        }
                    }
                    console.log('action.value', action.value)
                    if (action.value.integral){//Fired from button
                        this._doAssignment(currentNmr);
                    } else {
                        console.log('currentNmr', currentNmr);
                        if(!currentNmr.range || ! currentNmr.range.length) {
                            this._doAssignment(currentNmr);
                            // } else {
                            // API.setVariable("editedRange",API.getVariable('currentNmr'),["range"]);
                        } else {
                            this._createNMRannotationsAndACS(currentNmr);
                        }
                    }
                    break;
                default:
                    return false;
            }
            return true;
        }

        _doAssignment(currentNmr) {
            currentNmr.getChild(['jcamp', 'data']).then((jcamp) => {
                jcamp = String(jcamp.get());
                var ppOptions = API.getData("nmr1hOptions").resurrect();
                var spectrum = SD.NMR.fromJcamp(jcamp);
                var intFN = 0;
                if(ppOptions.integralFn=="peaks"){
                    intFN=1;
                }
                var peakPicking = spectrum.nmrPeakDetection({
                    nH:ppOptions.integral,
                    realTop:true,
                    thresholdFactor:ppOptions.noiseFactor,
                    clean:ppOptions.clean,
                    compile:ppOptions.compile,
                    optimize:ppOptions.optimize,
                    integralFn:intFN,
                    idPrefix:spectrum.getNucleus()+"",
                    gsdOptions:{minMaxRatio:0.001, smoothY:false, broadWidth:0},
                    format:"new"
                });
                currentNmr.setChildSync(['range'], peakPicking);
                this._createNMRannotationsAndACS(currentNmr);
            });
        }

        _createNMRannotationsAndACS(currentNmr) {
            console.log('create annoations');
            var peakPicking = JSON.parse(JSON.stringify(API.getData("currentNmrRanges")));

            // TODO : this code hsould not be here !
            //Recompile multiplicity
            for (var i=0; i<peakPicking.length; i++){
                var peak = peakPicking[i];
                for (var j=0; j<peak.signal.length; j++){
                    var signal = peak.signal[j];
                    if (signal.j && ! signal.multiplicity) {
                        signal.multiplicity = "";
                        for (var k=0; k<signal.j.length;k++){
                            signal.multiplicity+=signal.j[k].multiplicity;
                        }
                    }
                }
            }

            API.createData("annotationsNMR1d", SD.GUI.annotations1D(peakPicking, {
                line:1,
                fillColor:"green",
                strokeWidth:0
            }));
            API.createData("acsNMR1d",SD.formatter.toACS(peakPicking, {
                rangeForMultiplet:true,
                nucleus:currentNmr.nucleus[0],
                observe:Math.round(currentNmr.frequency/10)*10
            }));
        }

        updateIntegral() {
            var chemcalc=CCE.analyseMF(API.getData('mf')+'');
            if (chemcalc && chemcalc.atoms && chemcalc.atoms.H) {
                var nmr1hOptions=API.getData('nmr1hOptions');
                if (nmr1hOptions) nmr1hOptions.integral=chemcalc.atoms.H;
                nmr1hOptions.triggerChange();
            }
        }

        initializeNMRAssignment() {
            var promise = Promise.resolve();
            promise = promise.then(() => API.createData('nmr1hOptions', {
                    "noiseFactor": 0.8,
                    "clean": true,
                    "compile": true,
                    "optimize": false,
                    "integralFn": "sum",
                    "integral": 30,
                    "type": "1H"
                })
            );

            promise=promise.then(() => API.createData('nmr1hOndeTemplates', {
                "full": {
                    "type": "object",
                    "properties": {
                        "integral": {
                            "type": "number",
                            "title": "value to fit the spectrum integral",
                            "label": "Integral"
                        },
                        "noiseFactor": {
                            "type": "number",
                            "title": "Mutiplier of the auto-detected noise level",
                            "label": "noiseFactor"
                        },
                        "clean": {
                            "type": "boolean",
                            "title": "Delete signals with integration less than 0.5",
                            "label": "clean"
                        },
                        "compile": {
                            "type": "boolean",
                            "title": "Compile the multiplets",
                            "label": "compile"
                        },
                        "optimize": {
                            "type": "boolean",
                            "title": "Optimize the peaks to fit the spectrum",
                            "label": "optimize"
                        },
                        "integralFn": {
                            "type": "string",
                            "title": "Type of integration",
                            "label": "Integral type",
                            "enum": [
                                "sum",
                                "peaks"
                            ]
                        },
                        "type": {
                            "type": "string",
                            "title": "Nucleus",
                            "label": "Nucleus",
                            "editable": false
                        }
                    }
                },
                "short": {
                    "type": "object",
                    "properties": {
                        "integral": {
                            "type": "number",
                            "title": "value to fit the spectrum integral",
                            "label": "Integral"
                        }
                    }
                }
            }));
            promise=promise.then((nmr1hOndeTemplates) => API.createData('nmr1hOndeTemplate', nmr1hOndeTemplates.short));

            promise=promise.then(() => this.updateIntegral());
            // TODO we should recalculate the integration : updateIntegral

            return promise;
        }
    }

    return Nmr1dManager;
});

<|endoftext|>


<commit_before>/*
 * jQuery UI flyout menu
 *   - written for jQuery UI 1.9 milestone 2 using the widget factory
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * modified from: http://view.jqueryui.com/menu/tests/visual/menu/nested.html
 * 	by: Michael Lang, http://nexul.com/
 *
 */
(function($) {
$.widget("ui.flyoutmenu", {
	_create: function(){
		var self = this;
		this.active = this.element;
		this.activeItem = this.element.children("li").first();
		// hide submenus and create indicator icons
		this.element.find("ul").addClass("ui-menu-flyout").hide()
			.prev("a").prepend('');

		this.element.find("ul").andSelf().menu({
			// disable built-in key handling
			input: (!this.options.input)? $() : this.options.input,
			select: this.options.select,
			focus: function(event, ui) {
				self.active = ui.item.parent();
				self.activeItem = ui.item;
				ui.item.parent().find("ul").hide();
				var nested = $(">ul", ui.item);
				if (nested.length && /^mouse/.test(event.originalEvent.type)) {
					self._open(nested);
				}
			}
		}).keydown(function(event) {
			if (self.element.is(":hidden"))
				return;
			event.stopPropagation();
			switch (event.keyCode) {
			case $.ui.keyCode.PAGE_UP:
				self.pageup(event);
				break;
			case $.ui.keyCode.PAGE_DOWN:
				self.pagedown(event);
				break;
			case $.ui.keyCode.UP:
				self.up(event);
				break;
			case $.ui.keyCode.LEFT:
				self.left(event);
				break;
			case $.ui.keyCode.RIGHT:
				self.right(event);
				break;
			case $.ui.keyCode.DOWN:
				self.down(event);
				break;
			case $.ui.keyCode.ENTER:
			case $.ui.keyCode.TAB:
				self._select(event);
				event.preventDefault();
				break;
			case $.ui.keyCode.ESCAPE:
				self.hide();
				break;
			default:
				clearTimeout(self.filterTimer);
				var prev = self.previousFilter || "";
				var character = String.fromCharCode(event.keyCode);
				var skip = false;
				if (character == prev) {
					skip = true;
				} else {
					character = prev + character;
				}

				var match = self.activeItem.parent("ul").children("li").filter(function() {
					return new RegExp("^" + character, "i").test($("a", this).text());
				});
				var match = skip && match.index(self.active.next()) != -1 ? match.next() : match;
				if (!match.length) {
					character = String.fromCharCode(event.keyCode);
					match = self.widget().children("li").filter(function() {
						return new RegExp("^" + character, "i").test($(this).text());
					});
				}
				if (match.length) {
					self.activate(event, match);
					if (match.length > 1) {
						self.previousFilter = character;
						self.filterTimer = setTimeout(function() {
							delete self.previousFilter;
						}, 1000);
					} else {
						delete self.previousFilter;
					}
				} else {
					delete self.previousFilter;
				}
			}
		});
	},
	_open: function(submenu) {
		//only one menu can have items open at a time.
		$(document).find(".ui-menu-flyout").not(submenu.parents()).hide();
		submenu.show().css({
			top: 0,
			left: 0
		}).position({
			my: "left top",
			at: "right top",
			of: this.activeItem
		});
		$(document).one("click", function() {
				//clicking outside menu flyouts should close all flyouts
				$(document).find(".ui-menu-flyout").hide();
		});
	},
	_select: function(event){
		this.activeItem.parent().data("menu").select(event);
		$(document).find(".ui-menu-flyout").hide();
		activate(event, self.element.children("li").first());
	},
	left: function(event){
		this.activate(event, this.activeItem.parents("li").first());
	},
	right: function(event){
		this.activate(event, this.activeItem.children("ul").children("li").first());
	},
	up: function(event) {
		if (this.activeItem.prev("li").length > 0){
			this.activate(event, this.activeItem.prev("li"));
		}else{
			this.activate(event, this.activeItem.parent("ul").children("li:last"));
		}
	},
	down: function(event) {
		if (this.activeItem.next("li").length > 0){
			this.activate(event, this.activeItem.next("li"));
		}else{
			this.activate(event, this.activeItem.parent("ul").children("li:first"));
		}
	},
	pageup: function(event){
		if (this.activeItem.prev("li").length > 0){
			this.activate(event, this.activeItem.parent("ul").children("li:first"));
		}else{
			this.activate(event, this.activeItem.parent("ul").children("li:last"));
		}
	},
	pagedown: function(event){
		if (this.activeItem.next("li").length > 0){
			this.activate(event, this.activeItem.parent("ul").children("li:last"));
		}else{
			this.activate(event, this.activeItem.parent("ul").children("li:first"));
		}
	},
	activate: function(event, item){
		if (item){
			item.parent().data("menu").widget().show();
			item.parent().data("menu").activate(event, item);
		}
		this.activeItem = item;
		this.active = item.parent("ul");
	},
	show: function() {
		this.active = this.element;
		this.element.show();
		if (this.element.hasClass("ui-menu-flyout")){
			$(document).one("click", function() {
				//clicking outside menu flyouts should close all flyouts
				$(document).find(".ui-menu-flyout").hide();
			})
		}
	},
	hide: function() {
		this.activeItem = this.element.children("li").first();
		this.element.find("ul").andSelf().menu("deactivate").hide();
	}
});
}(jQuery));<commit_msg>removed jquery flyout menu<commit_after><|endoftext|>


<commit_before>function remove(rows) {
  $.each(rows, function() {
    for (var i in this.value) {
      $(this.value[i]).remove();
    }
  });
  $(query).remove();
}

var pending = [];
var loaded = false;
var port = chrome.extension.connect();

port.onMessage.addListener(function(message) {
  if (loaded) {
    // remove more stuff we found after the document's loaded
    remove(message.rows);
  } else {
    // memorize everything, to be removed later
    pending.push.apply(pending, message.rows);
  }
});
port.postMessage({domain: window.location.host});

// remove everything when the document's loaded
jQuery(function($) {
  loaded = true;
  remove(pending);
  pending = undefined;
});<commit_msg>Whoops.<commit_after>function remove(rows) {
  $.each(rows, function() {
    for (var i in this.value) {
      $(this.value[i]).remove();
    }
  });
}

var pending = [];
var loaded = false;
var port = chrome.extension.connect();

port.onMessage.addListener(function(message) {
  if (loaded) {
    // remove more stuff we found after the document's loaded
    remove(message.rows);
  } else {
    // memorize everything, to be removed later
    pending.push.apply(pending, message.rows);
  }
});
port.postMessage({domain: window.location.host});

// remove everything when the document's loaded
jQuery(function($) {
  loaded = true;
  remove(pending);
  pending = undefined;
});
<|endoftext|>


<commit_before>var twilio = Meteor.npmRequire('twilio');
var phone = Meteor.npmRequire('node-phonenumber');

/*
 * Utility functions
 */

// TODO probably want client-side validation too (or use this to canonicalize
// and confirm). We could use this live as the user is typing in their number,
// and show the canonicalized version below.
var canonicalize = function(number) {
  var phoneUtil = phone.PhoneNumberUtil.getInstance();
  var DEFAULT_REGION = 'US';
  var phoneNumber = phoneUtil.parse(number, DEFAULT_REGION);
  var canonicalized = phoneUtil.format(phoneNumber, phone.PhoneNumberFormat.INTERNATIONAL);
  return canonicalized;
};

var sendResponse = function(response, to, message) {
  var resp = new twilio.TwimlResponse();
  resp.message(message);
  // we must set content-type, otherwise twilio interprets what happens as a
  // 502 (even if the server returns a 200)
  response.writeHead(200, { 'Content-Type': 'text/xml' });
  response.end(resp.toString());
};

/*
 * Parser
 */

var Handler = (function() {
  function Handler(regex, callback) {
    this.regex = regex;
    this.callback = callback;
  }

  return Handler;
})();

var Response = (function() {
  function Response(context, text, match) {
    this.context = context;
    this.text = text;
    this.match = match;
  }

  return Response;
})();

var Parser = (function() {
  function Parser() {
    this.handlers = [];
    this.fallbackFunction = null;
  }

  Parser.prototype.respond = function(regex, callback) {
    this.handlers.push(new Handler(regex, callback));
  };

  Parser.prototype.fallback = function(callback) {
    this.fallbackFunction = callback;
  };

  Parser.prototype.receive = function(context, message) {
    var matched = 0;
    for (var i = 0; i < this.handlers.length; i++) {
      var handler = this.handlers[i];
      var match = message.match(handler.regex);
      if (match !== null) {
        matched++;
        handler.callback(new Response(context, message, match));
      }
    }
    if (matched === 0 && this.fallback !== null) {
      this.fallbackFunction(new Response(context, message, null));
    }
  };

  return Parser;
})();

/*
 * Parsing and message handing
 */

var parser = new Parser();

parser.respond(/^(\d{4})\b/, function(res) {
  console.log('bare number: ' + res.match[1]);
});

parser.respond(/switch\s+(\d{4})\b/, function(res) {
  console.log('switch with num: ' + res.match[1]);
  sendResponse(res.context.response, res.context.from, 'hello ' + res.match[1]);
});

parser.fallback(function(res) {
  var msg = "Sorry, I couldn't understand that command.";
  sendResponse(res.context.response, res.context.from, msg);
});

/*
 * Twilio controller
 */

// GLOBAL
handleTwilio = function() {
  // TODO verify that this message is actually coming from Twilio before doing
  // any processing!
  var body = this.request.body; // already parsed object
  var text = body.Body;
  var from = canonicalize(body.From);
  var context = {
    from: from,
    response: this.response,
  };
  parser.receive(context, text);
};
<commit_msg>Add validator stub<commit_after>var twilio = Meteor.npmRequire('twilio');
var phone = Meteor.npmRequire('node-phonenumber');

/*
 * Utility functions
 */

// TODO probably want client-side validation too (or use this to canonicalize
// and confirm). We could use this live as the user is typing in their number,
// and show the canonicalized version below.
var canonicalize = function(number) {
  var phoneUtil = phone.PhoneNumberUtil.getInstance();
  var DEFAULT_REGION = 'US';
  var phoneNumber = phoneUtil.parse(number, DEFAULT_REGION);
  var canonicalized = phoneUtil.format(phoneNumber, phone.PhoneNumberFormat.INTERNATIONAL);
  return canonicalized;
};

var sendResponse = function(response, to, message) {
  var resp = new twilio.TwimlResponse();
  resp.message(message);
  // we must set content-type, otherwise twilio interprets what happens as a
  // 502 (even if the server returns a 200)
  response.writeHead(200, { 'Content-Type': 'text/xml' });
  response.end(resp.toString());
};

/*
 * Parser
 */

var Handler = (function() {
  function Handler(regex, callback) {
    this.regex = regex;
    this.callback = callback;
  }

  return Handler;
})();

var Response = (function() {
  function Response(context, text, match) {
    this.context = context;
    this.text = text;
    this.match = match;
  }

  return Response;
})();

var Parser = (function() {
  function Parser() {
    this.handlers = [];
    this.fallbackFunction = null;
  }

  Parser.prototype.respond = function(regex, callback) {
    this.handlers.push(new Handler(regex, callback));
  };

  Parser.prototype.fallback = function(callback) {
    this.fallbackFunction = callback;
  };

  Parser.prototype.receive = function(context, message) {
    var matched = 0;
    for (var i = 0; i < this.handlers.length; i++) {
      var handler = this.handlers[i];
      var match = message.match(handler.regex);
      if (match !== null) {
        matched++;
        handler.callback(new Response(context, message, match));
      }
    }
    if (matched === 0 && this.fallback !== null) {
      this.fallbackFunction(new Response(context, message, null));
    }
  };

  return Parser;
})();

/*
 * Parsing and message handing
 */

var parser = new Parser();

// wrapper to make sure that a user is registered and validated
var validating = function(wrapped) {
  var validator = function(res) {
    var user = res.context.from;
    if (false) {
      // TODO check if user is not registered or not approved
      var msg = "Sorry, you are not registered or not approved by your team administrator.";
      sendResponse(res.context.response, res.context.from, msg);
    }
    wrapped(res);
  };
  return validator;
};

parser.respond(/^(\d{4})\b/, validating(function(res) {
  console.log('bare number: ' + res.match[1]);
}));

parser.respond(/switch\s+(\d{4})\b/, validating(function(res) {
  console.log('switch with num: ' + res.match[1]);
  sendResponse(res.context.response, res.context.from, 'hello ' + res.match[1]);
}));

parser.fallback(function(res) {
  var msg = "Sorry, I couldn't understand that command.";
  sendResponse(res.context.response, res.context.from, msg);
});

/*
 * Twilio controller
 */

// GLOBAL
handleTwilio = function() {
  // TODO verify that this message is actually coming from Twilio before doing
  // any processing!
  var body = this.request.body; // already parsed object
  var text = body.Body;
  var from = canonicalize(body.From);
  var context = {
    from: from,
    response: this.response,
  };
  parser.receive(context, text);
};
<|endoftext|>


<commit_before>/* Rewrite the entire file */
ISOFile.prototype.write = function(outstream) {
	for (var i=0; i<this.boxes.length; i++) {
		this.boxes[i].write(outstream);
	}
}

/* Modify the file and create the initialization segment */
ISOFile.prototype.writeInitializationSegment = function(outstream) {
	var i;
	var index;
	var mehd;
	var trex;
	var box;
	Log.debug("ISOFile", "Generating initialization segment");
	/* write the ftyp box as is in the input, may need to be fixed for DASH brands ?*/
	this.ftyp.write(outstream);

	/* The input file may be fragmented and have an mvex box, we just retrieve the duration and delele that box  */
	if (this.moov.mvex) {
		this.initial_duration = this.moov.mvex.mehd.fragment_duration;
		/* find this mvex box in the array of boxes and remove it */
		index = -1;
		for (i = 0; i < this.moov.boxes.length; i++) {
			box = this.moov.boxes[i];
			if (box === this.moov.mvex) {
				index = i;
			}
		}
		if (index > -1) {
			this.moov.boxes.splice(index, 1);
		}
		this.moov.mvex = null;
	}
	/* we can now create the new mvex box */
	this.moov.mvex = new BoxParser.mvexBox();
	this.moov.boxes.push(this.moov.mvex);
	this.moov.mvex.mehd = new BoxParser.mehdBox();
	this.moov.mvex.boxes.push(this.moov.mvex.mehd);
	this.moov.mvex.mehd.fragment_duration = this.initial_duration; // restore the same duration
	for (i = 0; i < this.moov.traks.length; i++) {
		if (this.moov.traks[i].ignore) continue;
		trex = new BoxParser.trexBox();
		this.moov.mvex.boxes.push(trex);
		trex.track_id = this.moov.traks[i].tkhd.track_id;
		trex.default_sample_description_index = 1;
		trex.default_sample_duration = (this.moov.traks[i].samples.length>0 ? this.moov.traks[i].samples[0].duration: 0);
		trex.default_sample_size = 0;
		trex.default_sample_flags = 1<<16;
	}
	this.moov.write(outstream);
}
<commit_msg>fix processing of fragmented files<commit_after>/* Rewrite the entire file */
ISOFile.prototype.write = function(outstream) {
	for (var i=0; i<this.boxes.length; i++) {
		this.boxes[i].write(outstream);
	}
}

/* Modify the file and create the initialization segment */
ISOFile.prototype.writeInitializationSegment = function(outstream) {
	var i;
	var index;
	var mehd;
	var trex;
	var box;
	Log.debug("ISOFile", "Generating initialization segment");
	/* write the ftyp box as is in the input, may need to be fixed for DASH brands ?*/
	this.ftyp.write(outstream);

	/* The input file may be fragmented and have an mvex box, we just retrieve the duration and delele that box  */
	if (this.moov.mvex) {
		this.initial_duration = this.moov.mvex.mehd.fragment_duration;
		/* find this mvex box in the array of boxes and remove it */
		index = -1;
		for (i = 0; i < this.moov.boxes.length; i++) {
			box = this.moov.boxes[i];
			if (box === this.moov.mvex) {
				index = i;
			}
		}
		if (index > -1) {
			this.moov.boxes.splice(index, 1);
		}
		this.moov.mvex = null;
	}
	/* we can now create the new mvex box */
	this.moov.mvex = new BoxParser.mvexBox();
	this.moov.boxes.push(this.moov.mvex);
	this.moov.mvex.mehd = new BoxParser.mehdBox();
	this.moov.mvex.boxes.push(this.moov.mvex.mehd);
	this.moov.mvex.mehd.fragment_duration = this.initial_duration; // restore the same duration
	for (i = 0; i < this.moov.traks.length; i++) {
		if (this.moov.traks[i].ignore) continue;
		trex = new BoxParser.trexBox();
		this.moov.mvex.boxes.push(trex);
		this.moov.mvex.trexs.push(trex);
		trex.track_id = this.moov.traks[i].tkhd.track_id;
		trex.default_sample_description_index = 1;
		trex.default_sample_duration = (this.moov.traks[i].samples.length>0 ? this.moov.traks[i].samples[0].duration: 0);
		trex.default_sample_size = 0;
		trex.default_sample_flags = 1<<16;
	}
	this.moov.write(outstream);
}
<|endoftext|>