<commit_before>/*
 * MelonJS Game Engine
 * Copyright (C) 2011 - 2013, Olivier BIOT
 * http://www.melonjs.org
 *
 */
(function () {
    /**
     * video functions
     * There is no constructor function for me.video
     * @namespace me.video
     * @memberOf me
     */
    me.video = (function () {
        // hold public stuff in our apig
        var api = {};

        // internal variables
        var canvas = null;

        var deferResizeId = -1;

        // max display size
        var maxWidth = Infinity;
        var maxHeight = Infinity;

        // default video settings
        var settings = {
            wrapper : undefined,
            renderer : 0, // canvas
            doubleBuffering : false,
            autoScale : false,
            scale : 1.0,
            scaleMethod : "default",
            transparent : false,
            antiAlias : false,
        };

        /**
         * Auto-detect the best renderer to use
         * @ignore
         */
        function autoDetectRenderer(c, width, height, options) {
            try {
                return new me.WebGLRenderer(c, width, height, options);
            }
            catch (e) {
                return new me.CanvasRenderer(c, width, height, options);
            }
        }

        /*
         * PUBLIC STUFF
         */

        /**
         * Base class for Video exception handling.
         * @name Error
         * @class
         * @constructor
         * @memberOf me.video
         * @param {String} msg Error message.
         */
        api.Error = me.Error.extend({
            init : function (msg) {
                this._super(me.Error, "init", [ msg ]);
                this.name = "me.video.Error";
            }
        });

        /**
         * Select the HTML5 Canvas renderer
         * @public
         * @name CANVAS
         * @memberOf me.video
         * @enum {Number}
         */
        api.CANVAS = 0;

        /**
         * Select the WebGL renderer
         * @public
         * @name WEBGL
         * @memberOf me.video
         * @enum {Number}
         */
        api.WEBGL = 1;

        /**
         * Auto-select the renderer (Attempt WebGL first, with fallback to Canvas)
         * @public
         * @name AUTO
         * @memberOf me.video
         * @enum {Number}
         */
        api.AUTO = 2;

        /**
         * init the "video" part

         * return false if initialization failed (canvas not supported)
         * @name init
         * @memberOf me.video
         * @function
         * @param {Number} width the width of the canvas viewport
         * @param {Number} height the height of the canvas viewport
         * @param {Object} [options] The optional video/renderer parameters
         * @param {String} [options.wrapper=document.body] the "div" element name to hold the canvas in the HTML file
         * @param {Number} [options.renderer=me.video.CANVAS] renderer to use.
         * @param {Boolean} [options.doubleBuffering=false] enable/disable double buffering
         * @param {Number|String} [options.scale=1.0] enable scaling of the canvas ('auto' for automatic scaling)
         * @param {Boolean} [options.scaleMethod="default"] ('default','fill','stretch') screen scaling modes
         * @param {Boolean} [options.transparent=false] whether to allow transparent pixels in the front buffer (screen)
         * @param {Boolean} [options.antiAlias=false] whether to enable or not video scaling interpolation
         * @return {Boolean}
         * @example
         * // init the video with a 640x480 canvas
         *   me.video.init(640, 480, {
         *       wrapper: "screen",
         *       renderer: me.video.CANVAS,
         *       scale: 'auto',
         *       scaleMethod: 'default',
         *       doubleBuffering: true
         *   });
         */
        //api.init = function (wrapperid, renderer, game_width, game_height, doublebuffering, scale, aspectRatio) {
        api.init = function (game_width, game_height, options) {
            // ensure melonjs has been properly initialized
            if (!me.initialized) {
                throw new api.Error("me.video.init() called before engine initialization.");
            }

            // revert to default options if not defined
            settings = Object.assign(settings, options || {});

            // sanitize potential given parameters
            settings.doubleBuffering = !!(settings.doubleBuffering);
            settings.autoScale = (settings.scale === "auto") || false;
            settings.scaleMethod = (settings.scaleMethod === "fill" || settings.scaleMethod === "stretch") ? settings.scaleMethod : "default";
            settings.transparent = !!(settings.transparent);

            // override renderer settings if &renderer=webgl or &webgl is defined in the URL
            if (typeof (me.game.HASH.renderer) !== "undefined") {
                settings.renderer = me.game.HASH.renderer.match(/WebGL/i) ? api.WEBGL : api.CANVAS;
            }
            if (me.game.HASH.webgl === true) {
                settings.renderer = api.WEBGL;
            }

            // normalize scale
            settings.scale = (settings.autoScale) ? 1.0 : (+settings.scale || 1.0);
            me.sys.scale = new me.Vector2d(settings.scale, settings.scale);

            // force double buffering if scaling is required
            if (settings.autoScale || (settings.scale !== 1.0)) {
                settings.doubleBuffering = true;
            }

            // default scaled size value
            var game_width_zoom = game_width * me.sys.scale.x;
            var game_height_zoom = game_height * me.sys.scale.y;
            settings.zoomX = game_width_zoom;
            settings.zoomY = game_height_zoom;

            //add a channel for the onresize/onorientationchange event
            window.addEventListener(
                "resize",
                throttle(
                    100,
                    false,
                    function (event) {
                        me.event.publish(me.event.WINDOW_ONRESIZE, [ event ]);
                    }
                ),
                false
            );
            window.addEventListener(
                "orientationchange",
                function (event) {
                    me.event.publish(me.event.WINDOW_ONORIENTATION_CHANGE, [ event ]);
                },
                false
            );

            // register to the channel
            me.event.subscribe(
                me.event.WINDOW_ONRESIZE,
                me.video.onresize.bind(me.video)
            );
            me.event.subscribe(
                me.event.WINDOW_ONORIENTATION_CHANGE,
                me.video.onresize.bind(me.video)
            );

            // create the main screen canvas
            canvas = api.createCanvas(game_width_zoom, game_height_zoom, true);

            // add our canvas
            if (options.wrapper) {
                settings.wrapper = document.getElementById(options.wrapper);
            }
            // if wrapperid is not defined (null)
            if (!settings.wrapper) {
                // add the canvas to document.body
                settings.wrapper = document.body;
            }
            settings.wrapper.appendChild(canvas);

            // stop here if not supported
            if (!canvas.getContext) {
                return false;
            }

            switch (settings.renderer) {
                case api.WEBGL:
                    this.renderer = new me.WebGLRenderer(canvas, game_width, game_height, settings);
                    break;
                case api.AUTO:
                    this.renderer = autoDetectRenderer(canvas, game_width, game_height, settings);
                    break;
                default:
                    this.renderer = new me.CanvasRenderer(canvas, game_width, game_height, settings);
                    break;
            }

            // adjust CSS style for High-DPI devices
            var ratio = me.device.getPixelRatio();
            if (ratio > 1) {
                canvas.style.width = (canvas.width / ratio) + "px";
                canvas.style.height = (canvas.height / ratio) + "px";
            }

            // set max the canvas max size if CSS values are defined
            if (window.getComputedStyle) {
                var style = window.getComputedStyle(canvas, null);
                me.video.setMaxSize(parseInt(style.maxWidth, 10), parseInt(style.maxHeight, 10));
            }

            // trigger an initial resize();
            me.video.onresize();

            me.game.init();

            return true;
        };

        /**
         * return the relative (to the page) position of the specified Canvas
         * @name getPos
         * @memberOf me.video
         * @function
         * @param {Canvas} [canvas] system one if none specified
         * @return {me.Vector2d}
         */
        api.getPos = function (c) {
            c = c || this.renderer.getScreenCanvas();
            return (
                c.getBoundingClientRect ?
                c.getBoundingClientRect() : { left : 0, top : 0 }
            );
        };

        /**
         * set the max canvas display size (when scaling)
         * @name setMaxSize
         * @memberOf me.video
         * @function
         * @param {Number} width width
         * @param {Number} height height
         */
        api.setMaxSize = function (w, h) {
            // max display size
            maxWidth = w || Infinity;
            maxHeight = h || Infinity;
        };

        /**
         * Create and return a new Canvas
         * @name createCanvas
         * @memberOf me.video
         * @function
         * @param {Number} width width
         * @param {Number} height height
         * @param {Boolean} [screencanvas=false] set to true if this canvas renders directly to the screen
         * @return {Canvas}
         */
        api.createCanvas = function (width, height, screencanvas) {
            if (width === 0 || height === 0)  {
                throw new api.Error("width or height was zero, Canvas could not be initialized !");
            }

            var _canvas = document.createElement("canvas");

            if ((screencanvas === true) && (navigator.isCocoonJS) && (me.device.android2 !== true)) {
                // enable ScreenCanvas on cocoonJS
                _canvas.screencanvas = true;
            }

            _canvas.width = width || canvas.width;
            _canvas.height = height || canvas.height;

            return _canvas;
        };

        /**
         * return a reference to the wrapper
         * @name getWrapper
         * @memberOf me.video
         * @function
         * @return {Document}
         */
        api.getWrapper = function () {
            return settings.wrapper;
        };

        /**
         * callback for window resize event
         * @ignore
         */
        api.onresize = function () {
            // default (no scaling)
            var scaleX = 1, scaleY = 1;

            // check for orientation information
            if (typeof window.orientation !== "undefined") {
                me.device.orientation = window.orientation;
            }
            else {
                // is this actually not the best option since default "portrait"
                // orientation might vary between for example an ipad and and android tab
                me.device.orientation = (
                    window.outerWidth > window.outerHeight ?
                    90 : 0
                );
            }

            if (settings.autoScale) {
                // get the parent container max size
                var parent = me.video.renderer.getScreenCanvas().parentNode;
                var _max_width = Math.min(maxWidth, parent.width || window.innerWidth);
                var _max_height = Math.min(maxHeight, parent.height || window.innerHeight);
                var designRatio = me.video.renderer.getWidth() / me.video.renderer.getHeight();
                var screenRatio = _max_width / _max_height;
                var sWidth = me.video.renderer.getHeight() * screenRatio;
                var sHeight = me.video.renderer.getWidth() * (window.innerHeight / window.innerWidth);

                if (settings.scaleMethod === "fill") {
                    if (screenRatio < designRatio) {
                        scaleX = scaleY = _max_width / sWidth;
                    }
                    else {
                        scaleX = scaleY = _max_height / sHeight;
                    }
                }
                else if (settings.scaleMethod === "stretch") {
                    // scale the display canvas to fit with the parent container
                    scaleX = _max_width / me.video.renderer.getWidth();
                    scaleY = _max_height / me.video.renderer.getHeight();
                }
                else {
                    // default screen fitting
                     // make sure we maintain the original aspect ratio
                    if (screenRatio < designRatio) {
                        scaleX = scaleY = _max_width / me.video.renderer.getWidth();
                    }
                    else {
                        scaleX = scaleY = _max_height / me.video.renderer.getHeight();
                    }
                }

                // adjust scaling ratio based on the device pixel ratio
                scaleX *= me.device.getPixelRatio();
                scaleY *= me.device.getPixelRatio();

                // scale if required
                if (scaleX !== 1 || scaleY !== 1) {
                    if (deferResizeId >= 0) {
                        // cancel any previous pending resize
                        clearTimeout(deferResizeId);
                    }
                    deferResizeId = me.video.updateDisplaySize.defer(this, scaleX, scaleY);
                    return;
                }
            }
            // make sure we have the correct relative canvas position cached
            me.input._offset = me.video.getPos();
        };

        /**
         * Modify the "displayed" canvas size
         * @name updateDisplaySize
         * @memberOf me.video
         * @function
         * @param {Number} scaleX X scaling multiplier
         * @param {Number} scaleY Y scaling multiplier
         */
        api.updateDisplaySize = function (scaleX, scaleY) {
            // update the global scale variable
            me.sys.scale.set(scaleX, scaleY);

            // renderer resize logic
            this.renderer.resize(scaleX, scaleY);

            me.input._offset = me.video.getPos();
            // clear the timeout id
            deferResizeId = -1;
        };

        // return our api
        return api;
    })();

})();
<commit_msg>Update video.js<commit_after>/*
 * MelonJS Game Engine
 * Copyright (C) 2011 - 2013, Olivier BIOT
 * http://www.melonjs.org
 *
 */
(function () {
    /**
     * video functions
     * There is no constructor function for me.video
     * @namespace me.video
     * @memberOf me
     */
    me.video = (function () {
        // hold public stuff in our apig
        var api = {};

        // internal variables
        var canvas = null;

        var deferResizeId = -1;

        // max display size
        var maxWidth = Infinity;
        var maxHeight = Infinity;

        // default video settings
        var settings = {
            wrapper : undefined,
            renderer : 0, // canvas
            doubleBuffering : false,
            autoScale : false,
            scale : 1.0,
            scaleMethod : "default",
            transparent : false,
            antiAlias : false,
        };

        /**
         * Auto-detect the best renderer to use
         * @ignore
         */
        function autoDetectRenderer(c, width, height, options) {
            try {
                return new me.WebGLRenderer(c, width, height, options);
            }
            catch (e) {
                return new me.CanvasRenderer(c, width, height, options);
            }
        }

        /*
         * PUBLIC STUFF
         */

        /**
         * Base class for Video exception handling.
         * @name Error
         * @class
         * @constructor
         * @memberOf me.video
         * @param {String} msg Error message.
         */
        api.Error = me.Error.extend({
            init : function (msg) {
                this._super(me.Error, "init", [ msg ]);
                this.name = "me.video.Error";
            }
        });

        /**
         * Select the HTML5 Canvas renderer
         * @public
         * @name CANVAS
         * @memberOf me.video
         * @enum {Number}
         */
        api.CANVAS = 0;

        /**
         * Select the WebGL renderer
         * @public
         * @name WEBGL
         * @memberOf me.video
         * @enum {Number}
         */
        api.WEBGL = 1;

        /**
         * Auto-select the renderer (Attempt WebGL first, with fallback to Canvas)
         * @public
         * @name AUTO
         * @memberOf me.video
         * @enum {Number}
         */
        api.AUTO = 2;

        /**
         * init the "video" part

         * return false if initialization failed (canvas not supported)
         * @name init
         * @memberOf me.video
         * @function
         * @param {Number} width the width of the canvas viewport
         * @param {Number} height the height of the canvas viewport
         * @param {Object} [options] The optional video/renderer parameters
         * @param {String} [options.wrapper=document.body] the "div" element name to hold the canvas in the HTML file
         * @param {Number} [options.renderer=me.video.CANVAS] renderer to use.
         * @param {Boolean} [options.doubleBuffering=false] enable/disable double buffering
         * @param {Number|String} [options.scale=1.0] enable scaling of the canvas ('auto' for automatic scaling)
         * @param {Boolean} [options.scaleMethod="default"] ('default','fill','stretch') screen scaling modes
         * @param {Boolean} [options.transparent=false] whether to allow transparent pixels in the front buffer (screen)
         * @param {Boolean} [options.antiAlias=false] whether to enable or not video scaling interpolation
         * @return {Boolean}
         * @example
         * // init the video with a 640x480 canvas
         *   me.video.init(640, 480, {
         *       wrapper: "screen",
         *       renderer: me.video.CANVAS,
         *       scale: 'auto',
         *       scaleMethod: 'default',
         *       doubleBuffering: true
         *   });
         */
        //api.init = function (wrapperid, renderer, game_width, game_height, doublebuffering, scale, aspectRatio) {
        api.init = function (game_width, game_height, options) {
            // ensure melonjs has been properly initialized
            if (!me.initialized) {
                throw new api.Error("me.video.init() called before engine initialization.");
            }

            // revert to default options if not defined
            settings = Object.assign(settings, options || {});

            // sanitize potential given parameters
            settings.doubleBuffering = !!(settings.doubleBuffering);
            settings.autoScale = (settings.scale === "auto") || false;
            settings.scaleMethod = [ "fill", "stretch" ].indexOf(settings.scaleMethod) >= 0 ? settings.scaleMethod : "default";
            settings.transparent = !!(settings.transparent);

            // override renderer settings if &renderer=webgl or &webgl is defined in the URL
            if (typeof (me.game.HASH.renderer) !== "undefined") {
                settings.renderer = me.game.HASH.renderer.match(/WebGL/i) ? api.WEBGL : api.CANVAS;
            }
            if (me.game.HASH.webgl === true) {
                settings.renderer = api.WEBGL;
            }

            // normalize scale
            settings.scale = (settings.autoScale) ? 1.0 : (+settings.scale || 1.0);
            me.sys.scale = new me.Vector2d(settings.scale, settings.scale);

            // force double buffering if scaling is required
            if (settings.autoScale || (settings.scale !== 1.0)) {
                settings.doubleBuffering = true;
            }

            // default scaled size value
            var game_width_zoom = game_width * me.sys.scale.x;
            var game_height_zoom = game_height * me.sys.scale.y;
            settings.zoomX = game_width_zoom;
            settings.zoomY = game_height_zoom;

            //add a channel for the onresize/onorientationchange event
            window.addEventListener(
                "resize",
                throttle(
                    100,
                    false,
                    function (event) {
                        me.event.publish(me.event.WINDOW_ONRESIZE, [ event ]);
                    }
                ),
                false
            );
            window.addEventListener(
                "orientationchange",
                function (event) {
                    me.event.publish(me.event.WINDOW_ONORIENTATION_CHANGE, [ event ]);
                },
                false
            );

            // register to the channel
            me.event.subscribe(
                me.event.WINDOW_ONRESIZE,
                me.video.onresize.bind(me.video)
            );
            me.event.subscribe(
                me.event.WINDOW_ONORIENTATION_CHANGE,
                me.video.onresize.bind(me.video)
            );

            // create the main screen canvas
            canvas = api.createCanvas(game_width_zoom, game_height_zoom, true);

            // add our canvas
            if (options.wrapper) {
                settings.wrapper = document.getElementById(options.wrapper);
            }
            // if wrapperid is not defined (null)
            if (!settings.wrapper) {
                // add the canvas to document.body
                settings.wrapper = document.body;
            }
            settings.wrapper.appendChild(canvas);

            // stop here if not supported
            if (!canvas.getContext) {
                return false;
            }

            switch (settings.renderer) {
                case api.WEBGL:
                    this.renderer = new me.WebGLRenderer(canvas, game_width, game_height, settings);
                    break;
                case api.AUTO:
                    this.renderer = autoDetectRenderer(canvas, game_width, game_height, settings);
                    break;
                default:
                    this.renderer = new me.CanvasRenderer(canvas, game_width, game_height, settings);
                    break;
            }

            // adjust CSS style for High-DPI devices
            var ratio = me.device.getPixelRatio();
            if (ratio > 1) {
                canvas.style.width = (canvas.width / ratio) + "px";
                canvas.style.height = (canvas.height / ratio) + "px";
            }

            // set max the canvas max size if CSS values are defined
            if (window.getComputedStyle) {
                var style = window.getComputedStyle(canvas, null);
                me.video.setMaxSize(parseInt(style.maxWidth, 10), parseInt(style.maxHeight, 10));
            }

            // trigger an initial resize();
            me.video.onresize();

            me.game.init();

            return true;
        };

        /**
         * return the relative (to the page) position of the specified Canvas
         * @name getPos
         * @memberOf me.video
         * @function
         * @param {Canvas} [canvas] system one if none specified
         * @return {me.Vector2d}
         */
        api.getPos = function (c) {
            c = c || this.renderer.getScreenCanvas();
            return (
                c.getBoundingClientRect ?
                c.getBoundingClientRect() : { left : 0, top : 0 }
            );
        };

        /**
         * set the max canvas display size (when scaling)
         * @name setMaxSize
         * @memberOf me.video
         * @function
         * @param {Number} width width
         * @param {Number} height height
         */
        api.setMaxSize = function (w, h) {
            // max display size
            maxWidth = w || Infinity;
            maxHeight = h || Infinity;
        };

        /**
         * Create and return a new Canvas
         * @name createCanvas
         * @memberOf me.video
         * @function
         * @param {Number} width width
         * @param {Number} height height
         * @param {Boolean} [screencanvas=false] set to true if this canvas renders directly to the screen
         * @return {Canvas}
         */
        api.createCanvas = function (width, height, screencanvas) {
            if (width === 0 || height === 0)  {
                throw new api.Error("width or height was zero, Canvas could not be initialized !");
            }

            var _canvas = document.createElement("canvas");

            if ((screencanvas === true) && (navigator.isCocoonJS) && (me.device.android2 !== true)) {
                // enable ScreenCanvas on cocoonJS
                _canvas.screencanvas = true;
            }

            _canvas.width = width || canvas.width;
            _canvas.height = height || canvas.height;

            return _canvas;
        };

        /**
         * return a reference to the wrapper
         * @name getWrapper
         * @memberOf me.video
         * @function
         * @return {Document}
         */
        api.getWrapper = function () {
            return settings.wrapper;
        };

        /**
         * callback for window resize event
         * @ignore
         */
        api.onresize = function () {
            // default (no scaling)
            var scaleX = 1, scaleY = 1;

            // check for orientation information
            if (typeof window.orientation !== "undefined") {
                me.device.orientation = window.orientation;
            }
            else {
                // is this actually not the best option since default "portrait"
                // orientation might vary between for example an ipad and and android tab
                me.device.orientation = (
                    window.outerWidth > window.outerHeight ?
                    90 : 0
                );
            }

            if (settings.autoScale) {
                // get the parent container max size
                var parent = me.video.renderer.getScreenCanvas().parentNode;
                var _max_width = Math.min(maxWidth, parent.width || window.innerWidth);
                var _max_height = Math.min(maxHeight, parent.height || window.innerHeight);
                var designRatio = me.video.renderer.getWidth() / me.video.renderer.getHeight();
                var screenRatio = _max_width / _max_height;
                var sWidth = me.video.renderer.getHeight() * screenRatio;
                var sHeight = me.video.renderer.getWidth() * (window.innerHeight / window.innerWidth);

                if (settings.scaleMethod === "fill") {
                    if (screenRatio < designRatio) {
                        scaleX = scaleY = _max_width / sWidth;
                    }
                    else {
                        scaleX = scaleY = _max_height / sHeight;
                    }
                }
                else if (settings.scaleMethod === "stretch") {
                    // scale the display canvas to fit with the parent container
                    scaleX = _max_width / me.video.renderer.getWidth();
                    scaleY = _max_height / me.video.renderer.getHeight();
                }
                else {
                    // default screen fitting
                     // make sure we maintain the original aspect ratio
                    if (screenRatio < designRatio) {
                        scaleX = scaleY = _max_width / me.video.renderer.getWidth();
                    }
                    else {
                        scaleX = scaleY = _max_height / me.video.renderer.getHeight();
                    }
                }

                // adjust scaling ratio based on the device pixel ratio
                scaleX *= me.device.getPixelRatio();
                scaleY *= me.device.getPixelRatio();

                // scale if required
                if (scaleX !== 1 || scaleY !== 1) {
                    if (deferResizeId >= 0) {
                        // cancel any previous pending resize
                        clearTimeout(deferResizeId);
                    }
                    deferResizeId = me.video.updateDisplaySize.defer(this, scaleX, scaleY);
                    return;
                }
            }
            // make sure we have the correct relative canvas position cached
            me.input._offset = me.video.getPos();
        };

        /**
         * Modify the "displayed" canvas size
         * @name updateDisplaySize
         * @memberOf me.video
         * @function
         * @param {Number} scaleX X scaling multiplier
         * @param {Number} scaleY Y scaling multiplier
         */
        api.updateDisplaySize = function (scaleX, scaleY) {
            // update the global scale variable
            me.sys.scale.set(scaleX, scaleY);

            // renderer resize logic
            this.renderer.resize(scaleX, scaleY);

            me.input._offset = me.video.getPos();
            // clear the timeout id
            deferResizeId = -1;
        };

        // return our api
        return api;
    })();

})();
<|endoftext|>


<commit_before>const path = require('path');

module.exports = {
    components: {
        src: path.join(process.cwd(), 'src', 'components', '**', '*.less')
    },
    stylesheets: {
        src: [
            path.join(process.cwd(), 'src', 'styles', '**', '*.less'),
            '!' + path.join(process.cwd(), 'src', 'styles', 'hpe-icons.less'),
        ]
    }
};<commit_msg>Ignoring fonts and variables (#596)<commit_after>const path = require('path');

module.exports = {
    components: {
        src: path.join(process.cwd(), 'src', 'components', '**', '*.less')
    },
    stylesheets: {
        src: [
            path.join(process.cwd(), 'src', 'styles', '**', '*.less'),
            '!' + path.join(process.cwd(), 'src', 'styles', 'hpe-icons.less'),
            '!' + path.join(process.cwd(), 'src', 'styles', 'fonts.less'),
            '!' + path.join(process.cwd(), 'src', 'styles', 'variables.less'),
        ]
    }
};<|endoftext|>


<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
 *
 */

"use strict";

// ---------------------------------------------------------------
function CAscSlideTiming()
{
    this.TransitionType     = undefined;
    this.TransitionOption   = undefined;
    this.TransitionDuration = undefined;

    this.SlideAdvanceOnMouseClick   = undefined;
    this.SlideAdvanceAfter          = undefined;
    this.SlideAdvanceDuration       = undefined;
    this.ShowLoop                   = undefined;
}

CAscSlideTiming.prototype.put_TransitionType = function(v) { this.TransitionType = v; };
CAscSlideTiming.prototype.get_TransitionType = function() { return this.TransitionType; };
CAscSlideTiming.prototype.put_TransitionOption = function(v) { this.TransitionOption = v; };
CAscSlideTiming.prototype.get_TransitionOption = function() { return this.TransitionOption; };
CAscSlideTiming.prototype.put_TransitionDuration = function(v) { this.TransitionDuration = v; };
CAscSlideTiming.prototype.get_TransitionDuration = function() { return this.TransitionDuration; };

CAscSlideTiming.prototype.put_SlideAdvanceOnMouseClick = function(v) { this.SlideAdvanceOnMouseClick = v; };
CAscSlideTiming.prototype.get_SlideAdvanceOnMouseClick = function() { return this.SlideAdvanceOnMouseClick; };
CAscSlideTiming.prototype.put_SlideAdvanceAfter = function(v) { this.SlideAdvanceAfter = v; };
CAscSlideTiming.prototype.get_SlideAdvanceAfter = function() { return this.SlideAdvanceAfter; };
CAscSlideTiming.prototype.put_SlideAdvanceDuration = function(v) { this.SlideAdvanceDuration = v; };
CAscSlideTiming.prototype.get_SlideAdvanceDuration = function() { return this.SlideAdvanceDuration; };
CAscSlideTiming.prototype.put_ShowLoop = function(v) { this.ShowLoop = v; };
CAscSlideTiming.prototype.get_ShowLoop = function() { return this.ShowLoop; };

CAscSlideTiming.prototype.applyProps = function(v)
{
    if (undefined !== v.TransitionType && null !== v.TransitionType)
        this.TransitionType = v.TransitionType;
    if (undefined !== v.TransitionOption && null !== v.TransitionOption)
        this.TransitionOption = v.TransitionOption;
    if (undefined !== v.TransitionDuration && null !== v.TransitionDuration)
        this.TransitionDuration = v.TransitionDuration;

    if (undefined !== v.SlideAdvanceOnMouseClick && null !== v.SlideAdvanceOnMouseClick)
        this.SlideAdvanceOnMouseClick = v.SlideAdvanceOnMouseClick;
    if (undefined !== v.SlideAdvanceAfter && null !== v.SlideAdvanceAfter)
        this.SlideAdvanceAfter = v.SlideAdvanceAfter;
    if (undefined !== v.SlideAdvanceDuration && null !== v.SlideAdvanceDuration)
        this.SlideAdvanceDuration = v.SlideAdvanceDuration;
    if (undefined !== v.ShowLoop && null !== v.ShowLoop)
        this.ShowLoop = v.ShowLoop;
};

CAscSlideTiming.prototype.createDuplicate = function(v)
{
    var _slideT = new CAscSlideTiming();

    _slideT.TransitionType     = this.TransitionType;
    _slideT.TransitionOption   = this.TransitionOption;
    _slideT.TransitionDuration = this.TransitionDuration;

    _slideT.SlideAdvanceOnMouseClick   = this.SlideAdvanceOnMouseClick;
    _slideT.SlideAdvanceAfter          = this.SlideAdvanceAfter;
    _slideT.SlideAdvanceDuration       = this.SlideAdvanceDuration;
    _slideT.ShowLoop                   = this.ShowLoop;

    return _slideT;
};

CAscSlideTiming.prototype.makeDuplicate = function(_slideT)
{
    if (!_slideT)
        return;

    _slideT.TransitionType     = this.TransitionType;
    _slideT.TransitionOption   = this.TransitionOption;
    _slideT.TransitionDuration = this.TransitionDuration;

    _slideT.SlideAdvanceOnMouseClick   = this.SlideAdvanceOnMouseClick;
    _slideT.SlideAdvanceAfter          = this.SlideAdvanceAfter;
    _slideT.SlideAdvanceDuration       = this.SlideAdvanceDuration;
    _slideT.ShowLoop                   = this.ShowLoop;
};

CAscSlideTiming.prototype.setUndefinedOptions = function()
{
    this.TransitionType     = undefined;
    this.TransitionOption   = undefined;
    this.TransitionDuration = undefined;

    this.SlideAdvanceOnMouseClick   = undefined;
    this.SlideAdvanceAfter          = undefined;
    this.SlideAdvanceDuration       = undefined;
    this.ShowLoop                   = undefined;
};

CAscSlideTiming.prototype.setDefaultParams = function()
{
    this.TransitionType     = c_oAscSlideTransitionTypes.None;
    this.TransitionOption   = -1;
    this.TransitionDuration = 2000;

    this.SlideAdvanceOnMouseClick   = true;
    this.SlideAdvanceAfter          = false;
    this.SlideAdvanceDuration       = 10000;
    this.ShowLoop                   = true;
};
CAscSlideTiming.prototype.setDefaultParams = function()
{
    this.TransitionType     = c_oAscSlideTransitionTypes.None;
    this.TransitionOption   = -1;
    this.TransitionDuration = 2000;

    this.SlideAdvanceOnMouseClick   = true;
    this.SlideAdvanceAfter          = false;
    this.SlideAdvanceDuration       = 10000;
    this.ShowLoop                   = true;
};

CAscSlideTiming.prototype.Write_ToBinary = function(w)
{
    w.WriteBool(AscFormat.isRealNumber(this.TransitionType));
    if(AscFormat.isRealNumber(this.TransitionType))
        w.WriteLong(this.TransitionType);

    w.WriteBool(AscFormat.isRealNumber(this.TransitionOption));
    if(AscFormat.isRealNumber(this.TransitionOption))
        w.WriteLong(this.TransitionOption);

    w.WriteBool(AscFormat.isRealNumber(this.TransitionDuration));
    if(AscFormat.isRealNumber(this.TransitionDuration))
        w.WriteLong(this.TransitionDuration);

    w.WriteBool(AscFormat.isRealBool(this.SlideAdvanceOnMouseClick));
    if(AscFormat.isRealBool(this.SlideAdvanceOnMouseClick))
        w.WriteBool(this.SlideAdvanceOnMouseClick);

    w.WriteBool(AscFormat.isRealBool(this.SlideAdvanceAfter));
    if(AscFormat.isRealBool(this.SlideAdvanceAfter))
        w.WriteBool(this.SlideAdvanceAfter);

    w.WriteBool(AscFormat.isRealNumber(this.SlideAdvanceDuration));
    if(AscFormat.isRealNumber(this.SlideAdvanceDuration))
        w.WriteLong(this.SlideAdvanceDuration);
    AscFormat.writeBool(w, this.ShowLoop);
};

CAscSlideTiming.prototype.Read_FromBinary = function(r)
{

    if(r.GetBool())
        this.TransitionType = r.GetLong();

    if(r.GetBool())
        this.TransitionOption = r.GetLong();

    if(r.GetBool())
        this.TransitionDuration = r.GetLong();

    if(r.GetBool())
        this.SlideAdvanceOnMouseClick = r.GetBool();

    if(r.GetBool())
        this.SlideAdvanceAfter = r.GetBool();

    if(r.GetBool())
        this.SlideAdvanceDuration = r.GetLong();
    this.ShowLoop = AscFormat.readBool(r);
};

CAscSlideTiming.prototype.ToArray = function()
{
    var _ret = [];
    _ret.push(this.TransitionType);
    _ret.push(this.TransitionOption);
    _ret.push(this.TransitionDuration);

    _ret.push(this.SlideAdvanceOnMouseClick);
    _ret.push(this.SlideAdvanceAfter);
    _ret.push(this.SlideAdvanceDuration);
    _ret.push(this.ShowLoop);
    return _ret;
};

AscDFH.drawingsConstructorsMap[AscDFH.historyitem_SlideSetTiming            ] = CAscSlideTiming;

// информация о темах --------------------------------------------

function CAscThemeInfo(themeInfo)
{
    this.ThemeInfo = themeInfo;
    this.Index = -1000;
}
CAscThemeInfo.prototype.get_Name = function() { return this.ThemeInfo.Name; };
CAscThemeInfo.prototype.get_Url = function() { return this.ThemeInfo.Url; };
CAscThemeInfo.prototype.get_Image = function() { return this.ThemeInfo.Thumbnail; };
CAscThemeInfo.prototype.get_Index = function() { return this.Index; };

function CLayoutThumbnail()
{
    this.Index = 0;
    this.Name = "";
    this.Type = 15;
    this.Image = "";

    this.Width = 0;
    this.Height = 0;
}

CLayoutThumbnail.prototype.getIndex = function() { return this.Index; };
CLayoutThumbnail.prototype.getType = function() { return this.Type; };
CLayoutThumbnail.prototype.get_Image = function() { return this.Image; };
CLayoutThumbnail.prototype.get_Name = function() { return this.Name; };
CLayoutThumbnail.prototype.get_Width = function() { return this.Width; };
CLayoutThumbnail.prototype.get_Height = function() { return this.Height; };

function CompareTiming(timing1, timing2){
    if(!timing1 || !timing2){
        return null;
    }
    var ret = new CAscSlideTiming();
    if(timing1.TransitionType === timing2.TransitionType){
        ret.TransitionType = timing1.TransitionType;
    }
    if(timing1.TransitionOption === timing2.TransitionOption){
        ret.TransitionOption = timing1.TransitionOption;
    }
    if(timing1.TransitionDuration === timing2.TransitionDuration){
        ret.TransitionDuration = timing1.TransitionDuration;
    }
    if(timing1.SlideAdvanceOnMouseClick === timing2.SlideAdvanceOnMouseClick){
        ret.SlideAdvanceOnMouseClick = timing1.SlideAdvanceOnMouseClick;
    }
    if(timing1.SlideAdvanceAfter === timing2.SlideAdvanceAfter){
        ret.SlideAdvanceAfter = timing1.SlideAdvanceAfter;
    }
    if(timing1.SlideAdvanceDuration === timing2.SlideAdvanceDuration){
        ret.SlideAdvanceDuration = timing1.SlideAdvanceDuration;
    }
    if(timing1.ShowLoop === timing2.ShowLoop){
        ret.ShowLoop = timing1.ShowLoop;
    }
    return ret;

}
//------------------------------------------------------------export----------------------------------------------------
window['Asc'] = window['Asc'] || {};
window['AscCommonSlide'] = window['AscCommonSlide'] || {};
window['Asc']['CAscSlideTiming'] = CAscSlideTiming;
window['AscCommonSlide'].CompareTiming = CompareTiming;
CAscSlideTiming.prototype['put_TransitionType'] = CAscSlideTiming.prototype.put_TransitionType;
CAscSlideTiming.prototype['get_TransitionType'] = CAscSlideTiming.prototype.get_TransitionType;
CAscSlideTiming.prototype['put_TransitionOption'] = CAscSlideTiming.prototype.put_TransitionOption;
CAscSlideTiming.prototype['get_TransitionOption'] = CAscSlideTiming.prototype.get_TransitionOption;
CAscSlideTiming.prototype['put_TransitionDuration'] = CAscSlideTiming.prototype.put_TransitionDuration;
CAscSlideTiming.prototype['get_TransitionDuration'] = CAscSlideTiming.prototype.get_TransitionDuration;
CAscSlideTiming.prototype['put_SlideAdvanceOnMouseClick'] = CAscSlideTiming.prototype.put_SlideAdvanceOnMouseClick;
CAscSlideTiming.prototype['get_SlideAdvanceOnMouseClick'] = CAscSlideTiming.prototype.get_SlideAdvanceOnMouseClick;
CAscSlideTiming.prototype['put_SlideAdvanceAfter'] = CAscSlideTiming.prototype.put_SlideAdvanceAfter;
CAscSlideTiming.prototype['get_SlideAdvanceAfter'] = CAscSlideTiming.prototype.get_SlideAdvanceAfter;
CAscSlideTiming.prototype['put_SlideAdvanceDuration'] = CAscSlideTiming.prototype.put_SlideAdvanceDuration;
CAscSlideTiming.prototype['get_SlideAdvanceDuration'] = CAscSlideTiming.prototype.get_SlideAdvanceDuration;
CAscSlideTiming.prototype['put_ShowLoop'] = CAscSlideTiming.prototype.put_ShowLoop;
CAscSlideTiming.prototype['get_ShowLoop'] = CAscSlideTiming.prototype.get_ShowLoop;
CAscSlideTiming.prototype['applyProps'] = CAscSlideTiming.prototype.applyProps;
CAscSlideTiming.prototype['createDuplicate'] = CAscSlideTiming.prototype.createDuplicate;
CAscSlideTiming.prototype['makeDuplicate'] = CAscSlideTiming.prototype.makeDuplicate;
CAscSlideTiming.prototype['setUndefinedOptions'] = CAscSlideTiming.prototype.setUndefinedOptions;
CAscSlideTiming.prototype['setDefaultParams'] = CAscSlideTiming.prototype.setDefaultParams;
CAscSlideTiming.prototype['Write_ToBinary'] = CAscSlideTiming.prototype.Write_ToBinary;
CAscSlideTiming.prototype['Read_FromBinary'] = CAscSlideTiming.prototype.Read_FromBinary;

window['AscCommonSlide'].CAscThemeInfo = CAscThemeInfo;
CAscThemeInfo.prototype['get_Name'] = CAscThemeInfo.prototype.get_Name;
CAscThemeInfo.prototype['get_Url'] = CAscThemeInfo.prototype.get_Url;
CAscThemeInfo.prototype['get_Image'] = CAscThemeInfo.prototype.get_Image;
CAscThemeInfo.prototype['get_Index'] = CAscThemeInfo.prototype.get_Index;

CLayoutThumbnail.prototype['getIndex'] = CLayoutThumbnail.prototype.getIndex;
CLayoutThumbnail.prototype['getType'] = CLayoutThumbnail.prototype.getType;
CLayoutThumbnail.prototype['get_Image'] = CLayoutThumbnail.prototype.get_Image;
CLayoutThumbnail.prototype['get_Name'] = CLayoutThumbnail.prototype.get_Name;
CLayoutThumbnail.prototype['get_Width'] = CLayoutThumbnail.prototype.get_Width;
CLayoutThumbnail.prototype['get_Height'] = CLayoutThumbnail.prototype.get_Height;
<commit_msg>[hf] Header/footer properties<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
 *
 */

"use strict";

// ---------------------------------------------------------------
function CAscSlideTiming()
{
    this.TransitionType     = undefined;
    this.TransitionOption   = undefined;
    this.TransitionDuration = undefined;

    this.SlideAdvanceOnMouseClick   = undefined;
    this.SlideAdvanceAfter          = undefined;
    this.SlideAdvanceDuration       = undefined;
    this.ShowLoop                   = undefined;
}

CAscSlideTiming.prototype.put_TransitionType = function(v) { this.TransitionType = v; };
CAscSlideTiming.prototype.get_TransitionType = function() { return this.TransitionType; };
CAscSlideTiming.prototype.put_TransitionOption = function(v) { this.TransitionOption = v; };
CAscSlideTiming.prototype.get_TransitionOption = function() { return this.TransitionOption; };
CAscSlideTiming.prototype.put_TransitionDuration = function(v) { this.TransitionDuration = v; };
CAscSlideTiming.prototype.get_TransitionDuration = function() { return this.TransitionDuration; };

CAscSlideTiming.prototype.put_SlideAdvanceOnMouseClick = function(v) { this.SlideAdvanceOnMouseClick = v; };
CAscSlideTiming.prototype.get_SlideAdvanceOnMouseClick = function() { return this.SlideAdvanceOnMouseClick; };
CAscSlideTiming.prototype.put_SlideAdvanceAfter = function(v) { this.SlideAdvanceAfter = v; };
CAscSlideTiming.prototype.get_SlideAdvanceAfter = function() { return this.SlideAdvanceAfter; };
CAscSlideTiming.prototype.put_SlideAdvanceDuration = function(v) { this.SlideAdvanceDuration = v; };
CAscSlideTiming.prototype.get_SlideAdvanceDuration = function() { return this.SlideAdvanceDuration; };
CAscSlideTiming.prototype.put_ShowLoop = function(v) { this.ShowLoop = v; };
CAscSlideTiming.prototype.get_ShowLoop = function() { return this.ShowLoop; };

CAscSlideTiming.prototype.applyProps = function(v)
{
    if (undefined !== v.TransitionType && null !== v.TransitionType)
        this.TransitionType = v.TransitionType;
    if (undefined !== v.TransitionOption && null !== v.TransitionOption)
        this.TransitionOption = v.TransitionOption;
    if (undefined !== v.TransitionDuration && null !== v.TransitionDuration)
        this.TransitionDuration = v.TransitionDuration;

    if (undefined !== v.SlideAdvanceOnMouseClick && null !== v.SlideAdvanceOnMouseClick)
        this.SlideAdvanceOnMouseClick = v.SlideAdvanceOnMouseClick;
    if (undefined !== v.SlideAdvanceAfter && null !== v.SlideAdvanceAfter)
        this.SlideAdvanceAfter = v.SlideAdvanceAfter;
    if (undefined !== v.SlideAdvanceDuration && null !== v.SlideAdvanceDuration)
        this.SlideAdvanceDuration = v.SlideAdvanceDuration;
    if (undefined !== v.ShowLoop && null !== v.ShowLoop)
        this.ShowLoop = v.ShowLoop;
};

CAscSlideTiming.prototype.createDuplicate = function(v)
{
    var _slideT = new CAscSlideTiming();

    _slideT.TransitionType     = this.TransitionType;
    _slideT.TransitionOption   = this.TransitionOption;
    _slideT.TransitionDuration = this.TransitionDuration;

    _slideT.SlideAdvanceOnMouseClick   = this.SlideAdvanceOnMouseClick;
    _slideT.SlideAdvanceAfter          = this.SlideAdvanceAfter;
    _slideT.SlideAdvanceDuration       = this.SlideAdvanceDuration;
    _slideT.ShowLoop                   = this.ShowLoop;

    return _slideT;
};

CAscSlideTiming.prototype.makeDuplicate = function(_slideT)
{
    if (!_slideT)
        return;

    _slideT.TransitionType     = this.TransitionType;
    _slideT.TransitionOption   = this.TransitionOption;
    _slideT.TransitionDuration = this.TransitionDuration;

    _slideT.SlideAdvanceOnMouseClick   = this.SlideAdvanceOnMouseClick;
    _slideT.SlideAdvanceAfter          = this.SlideAdvanceAfter;
    _slideT.SlideAdvanceDuration       = this.SlideAdvanceDuration;
    _slideT.ShowLoop                   = this.ShowLoop;
};

CAscSlideTiming.prototype.setUndefinedOptions = function()
{
    this.TransitionType     = undefined;
    this.TransitionOption   = undefined;
    this.TransitionDuration = undefined;

    this.SlideAdvanceOnMouseClick   = undefined;
    this.SlideAdvanceAfter          = undefined;
    this.SlideAdvanceDuration       = undefined;
    this.ShowLoop                   = undefined;
};

CAscSlideTiming.prototype.setDefaultParams = function()
{
    this.TransitionType     = c_oAscSlideTransitionTypes.None;
    this.TransitionOption   = -1;
    this.TransitionDuration = 2000;

    this.SlideAdvanceOnMouseClick   = true;
    this.SlideAdvanceAfter          = false;
    this.SlideAdvanceDuration       = 10000;
    this.ShowLoop                   = true;
};
CAscSlideTiming.prototype.setDefaultParams = function()
{
    this.TransitionType     = c_oAscSlideTransitionTypes.None;
    this.TransitionOption   = -1;
    this.TransitionDuration = 2000;

    this.SlideAdvanceOnMouseClick   = true;
    this.SlideAdvanceAfter          = false;
    this.SlideAdvanceDuration       = 10000;
    this.ShowLoop                   = true;
};

CAscSlideTiming.prototype.Write_ToBinary = function(w)
{
    w.WriteBool(AscFormat.isRealNumber(this.TransitionType));
    if(AscFormat.isRealNumber(this.TransitionType))
        w.WriteLong(this.TransitionType);

    w.WriteBool(AscFormat.isRealNumber(this.TransitionOption));
    if(AscFormat.isRealNumber(this.TransitionOption))
        w.WriteLong(this.TransitionOption);

    w.WriteBool(AscFormat.isRealNumber(this.TransitionDuration));
    if(AscFormat.isRealNumber(this.TransitionDuration))
        w.WriteLong(this.TransitionDuration);

    w.WriteBool(AscFormat.isRealBool(this.SlideAdvanceOnMouseClick));
    if(AscFormat.isRealBool(this.SlideAdvanceOnMouseClick))
        w.WriteBool(this.SlideAdvanceOnMouseClick);

    w.WriteBool(AscFormat.isRealBool(this.SlideAdvanceAfter));
    if(AscFormat.isRealBool(this.SlideAdvanceAfter))
        w.WriteBool(this.SlideAdvanceAfter);

    w.WriteBool(AscFormat.isRealNumber(this.SlideAdvanceDuration));
    if(AscFormat.isRealNumber(this.SlideAdvanceDuration))
        w.WriteLong(this.SlideAdvanceDuration);
    AscFormat.writeBool(w, this.ShowLoop);
};

CAscSlideTiming.prototype.Read_FromBinary = function(r)
{

    if(r.GetBool())
        this.TransitionType = r.GetLong();

    if(r.GetBool())
        this.TransitionOption = r.GetLong();

    if(r.GetBool())
        this.TransitionDuration = r.GetLong();

    if(r.GetBool())
        this.SlideAdvanceOnMouseClick = r.GetBool();

    if(r.GetBool())
        this.SlideAdvanceAfter = r.GetBool();

    if(r.GetBool())
        this.SlideAdvanceDuration = r.GetLong();
    this.ShowLoop = AscFormat.readBool(r);
};

CAscSlideTiming.prototype.ToArray = function()
{
    var _ret = [];
    _ret.push(this.TransitionType);
    _ret.push(this.TransitionOption);
    _ret.push(this.TransitionDuration);

    _ret.push(this.SlideAdvanceOnMouseClick);
    _ret.push(this.SlideAdvanceAfter);
    _ret.push(this.SlideAdvanceDuration);
    _ret.push(this.ShowLoop);
    return _ret;
};

AscDFH.drawingsConstructorsMap[AscDFH.historyitem_SlideSetTiming            ] = CAscSlideTiming;

// информация о темах --------------------------------------------

function CAscThemeInfo(themeInfo)
{
    this.ThemeInfo = themeInfo;
    this.Index = -1000;
}
CAscThemeInfo.prototype.get_Name = function() { return this.ThemeInfo.Name; };
CAscThemeInfo.prototype.get_Url = function() { return this.ThemeInfo.Url; };
CAscThemeInfo.prototype.get_Image = function() { return this.ThemeInfo.Thumbnail; };
CAscThemeInfo.prototype.get_Index = function() { return this.Index; };

function CLayoutThumbnail()
{
    this.Index = 0;
    this.Name = "";
    this.Type = 15;
    this.Image = "";

    this.Width = 0;
    this.Height = 0;
}

CLayoutThumbnail.prototype.getIndex = function() { return this.Index; };
CLayoutThumbnail.prototype.getType = function() { return this.Type; };
CLayoutThumbnail.prototype.get_Image = function() { return this.Image; };
CLayoutThumbnail.prototype.get_Name = function() { return this.Name; };
CLayoutThumbnail.prototype.get_Width = function() { return this.Width; };
CLayoutThumbnail.prototype.get_Height = function() { return this.Height; };

function CompareTiming(timing1, timing2){
    if(!timing1 || !timing2){
        return null;
    }
    var ret = new CAscSlideTiming();
    if(timing1.TransitionType === timing2.TransitionType){
        ret.TransitionType = timing1.TransitionType;
    }
    if(timing1.TransitionOption === timing2.TransitionOption){
        ret.TransitionOption = timing1.TransitionOption;
    }
    if(timing1.TransitionDuration === timing2.TransitionDuration){
        ret.TransitionDuration = timing1.TransitionDuration;
    }
    if(timing1.SlideAdvanceOnMouseClick === timing2.SlideAdvanceOnMouseClick){
        ret.SlideAdvanceOnMouseClick = timing1.SlideAdvanceOnMouseClick;
    }
    if(timing1.SlideAdvanceAfter === timing2.SlideAdvanceAfter){
        ret.SlideAdvanceAfter = timing1.SlideAdvanceAfter;
    }
    if(timing1.SlideAdvanceDuration === timing2.SlideAdvanceDuration){
        ret.SlideAdvanceDuration = timing1.SlideAdvanceDuration;
    }
    if(timing1.ShowLoop === timing2.ShowLoop){
        ret.ShowLoop = timing1.ShowLoop;
    }
    return ret;

}
function CAscHFProps(){
    this.DateTime = null;
    this.CustomDateTime = null;
    this.Footer = null;
    this.Lang = null;

    this.ShowDateTime = null;
    this.ShowSlideNum = null;
    this.ShowFooter = null;
}

CAscHFProps.prototype['get_DateTime'] = CAscHFProps.prototype.get_DateTime = function(){return this.DateTime;};
CAscHFProps.prototype['get_CustomDateTime']  = CAscHFProps.prototype.get_CustomDateTime = function(){return this.CustomDateTime;};
CAscHFProps.prototype['get_Footer'] = CAscHFProps.prototype.get_Footer = function(){return this.Footer;};
CAscHFProps.prototype['get_Lang'] = CAscHFProps.prototype.get_Lang = function(){return this.Lang;};
CAscHFProps.prototype['get_ShowDateTime'] = CAscHFProps.prototype.get_ShowDateTime = function(){return this.ShowDateTime;};
CAscHFProps.prototype['get_ShowSlideNum'] = CAscHFProps.prototype.get_ShowSlideNum = function(){return this.ShowSlideNum;};
CAscHFProps.prototype['get_ShowFooter'] = CAscHFProps.prototype.get_ShowFooter = function(){return this.ShowFooter;};
CAscHFProps.prototype['put_DateTime'] = CAscHFProps.prototype.put_DateTime = function(v){this.DateTime = v;};
CAscHFProps.prototype['put_CustomDateTime']  = CAscHFProps.prototype.put_CustomDateTime = function(v){this.CustomDateTime = v;};
CAscHFProps.prototype['put_Footer'] = CAscHFProps.prototype.put_Footer = function(v){this.Footer = v;};
CAscHFProps.prototype['put_Lang'] = CAscHFProps.prototype.put_Lang = function(v){this.Lang = v;};
CAscHFProps.prototype['put_ShowDateTime'] = CAscHFProps.prototype.put_ShowDateTime = function(v){this.ShowDateTime = v;};
CAscHFProps.prototype['put_ShowSlideNum'] = CAscHFProps.prototype.put_ShowSlideNum = function(v){this.ShowSlideNum = v;};
CAscHFProps.prototype['put_ShowFooter'] = CAscHFProps.prototype.put_ShowFooter = function(v){this.ShowFooter = v;};

//------------------------------------------------------------export----------------------------------------------------
window['Asc'] = window['Asc'] || {};
window['AscCommonSlide'] = window['AscCommonSlide'] || {};

window['AscCommonSlide']['CAscHFProps'] = window['AscCommonSlide'].CAscHFProps = CAscHFProps;

window['Asc']['CAscSlideTiming'] = CAscSlideTiming;
window['AscCommonSlide'].CompareTiming = CompareTiming;
CAscSlideTiming.prototype['put_TransitionType'] = CAscSlideTiming.prototype.put_TransitionType;
CAscSlideTiming.prototype['get_TransitionType'] = CAscSlideTiming.prototype.get_TransitionType;
CAscSlideTiming.prototype['put_TransitionOption'] = CAscSlideTiming.prototype.put_TransitionOption;
CAscSlideTiming.prototype['get_TransitionOption'] = CAscSlideTiming.prototype.get_TransitionOption;
CAscSlideTiming.prototype['put_TransitionDuration'] = CAscSlideTiming.prototype.put_TransitionDuration;
CAscSlideTiming.prototype['get_TransitionDuration'] = CAscSlideTiming.prototype.get_TransitionDuration;
CAscSlideTiming.prototype['put_SlideAdvanceOnMouseClick'] = CAscSlideTiming.prototype.put_SlideAdvanceOnMouseClick;
CAscSlideTiming.prototype['get_SlideAdvanceOnMouseClick'] = CAscSlideTiming.prototype.get_SlideAdvanceOnMouseClick;
CAscSlideTiming.prototype['put_SlideAdvanceAfter'] = CAscSlideTiming.prototype.put_SlideAdvanceAfter;
CAscSlideTiming.prototype['get_SlideAdvanceAfter'] = CAscSlideTiming.prototype.get_SlideAdvanceAfter;
CAscSlideTiming.prototype['put_SlideAdvanceDuration'] = CAscSlideTiming.prototype.put_SlideAdvanceDuration;
CAscSlideTiming.prototype['get_SlideAdvanceDuration'] = CAscSlideTiming.prototype.get_SlideAdvanceDuration;
CAscSlideTiming.prototype['put_ShowLoop'] = CAscSlideTiming.prototype.put_ShowLoop;
CAscSlideTiming.prototype['get_ShowLoop'] = CAscSlideTiming.prototype.get_ShowLoop;
CAscSlideTiming.prototype['applyProps'] = CAscSlideTiming.prototype.applyProps;
CAscSlideTiming.prototype['createDuplicate'] = CAscSlideTiming.prototype.createDuplicate;
CAscSlideTiming.prototype['makeDuplicate'] = CAscSlideTiming.prototype.makeDuplicate;
CAscSlideTiming.prototype['setUndefinedOptions'] = CAscSlideTiming.prototype.setUndefinedOptions;
CAscSlideTiming.prototype['setDefaultParams'] = CAscSlideTiming.prototype.setDefaultParams;
CAscSlideTiming.prototype['Write_ToBinary'] = CAscSlideTiming.prototype.Write_ToBinary;
CAscSlideTiming.prototype['Read_FromBinary'] = CAscSlideTiming.prototype.Read_FromBinary;

window['AscCommonSlide'].CAscThemeInfo = CAscThemeInfo;
CAscThemeInfo.prototype['get_Name'] = CAscThemeInfo.prototype.get_Name;
CAscThemeInfo.prototype['get_Url'] = CAscThemeInfo.prototype.get_Url;
CAscThemeInfo.prototype['get_Image'] = CAscThemeInfo.prototype.get_Image;
CAscThemeInfo.prototype['get_Index'] = CAscThemeInfo.prototype.get_Index;

CLayoutThumbnail.prototype['getIndex'] = CLayoutThumbnail.prototype.getIndex;
CLayoutThumbnail.prototype['getType'] = CLayoutThumbnail.prototype.getType;
CLayoutThumbnail.prototype['get_Image'] = CLayoutThumbnail.prototype.get_Image;
CLayoutThumbnail.prototype['get_Name'] = CLayoutThumbnail.prototype.get_Name;
CLayoutThumbnail.prototype['get_Width'] = CLayoutThumbnail.prototype.get_Width;
CLayoutThumbnail.prototype['get_Height'] = CLayoutThumbnail.prototype.get_Height;
<|endoftext|>


<commit_before>#! /usr/bin/env node

process.title = 'bankai'

require('v8-compile-cache')

var ansi = require('ansi-escape-sequences')
var minimist = require('minimist')
var dedent = require('dedent')
var path = require('path')

var USAGE = `
  $ ${clr('bankai', 'bold')} ${clr('<command> [entry]', 'green')} [options]

  Commands:

    build       compile all files to ${clr('dist/', 'green')}
    inspect     inspect the bundle dependencies
    start       start a development server

  Options:

    -d, --debug       output lots of logs
    -h, --help        print usage
    -q, --quiet       don't output any logs
    -v, --version     print version

  Examples:

    Start a development server
    ${clr('$ bankai start index.js', 'cyan')}

    Visualize all dependencies in your project
    ${clr('$ bankai inspect index.js', 'cyan')}

    Compile all files in the project to disk
    ${clr('$ bankai build index.js', 'cyan')}

  Running into trouble? Feel free to file an issue:
  ${clr('https://github.com/choojs/bankai/issues/new', 'cyan')}

  Do you enjoy using this software? Become a backer:
  ${clr('https://opencollective.com/choo', 'cyan')}
`.replace(/\n$/, '').replace(/^\n/, '')

var NOCOMMAND = `
  Please specify a bankai command:
    ${clr('$ bankai', 'cyan')} ${clr('<command>', 'green')}

  For example:
    ${clr('$ bankai start', 'cyan')} ${clr('index.js', 'green')}

  Run ${clr('bankai --help', 'cyan')} to see all options.
`.replace(/\n$/, '').replace(/^\n/, '')

var argv = minimist(process.argv.slice(2), {
  alias: {
    help: 'h',
    quiet: 'q',
    version: 'v',
    base: 'b'
  },
  boolean: [
    'help',
    'quiet',
    'version'
  ]
})

;(function main (argv) {
  var cmd = argv._[0]
  var entry = argv._[1]

  if (entry) {
    if (!path.isAbsolute(entry)) entry = path.join(process.cwd(), entry)
  } else {
    entry = process.cwd()
  }

  if (argv.help) {
    console.log(USAGE)
  } else if (argv.version) {
    console.log(require('./package.json').version)
  } else if (cmd === 'build') {
    var outdir = argv._[2]
    require('./lib/cmd-build')(path.join(entry), outdir, argv)
  } else if (cmd === 'inspect') {
    require('./lib/cmd-inspect')(path.join(entry), argv)
  } else if (cmd === 'start') {
    if (!argv.q) alternateBuffer()
    require('./lib/cmd-start')(path.join(entry), argv)
  } else {
    console.log(NOCOMMAND)
    process.exit(1)
  }
})(argv)

function clr (text, color) {
  return process.stdout.isTTY ? ansi.format(text, color) : text
}

// Switch to an alternate terminal buffer,
// switch back to the main terminal buffer on exit.
function alternateBuffer () {
  var q = Buffer.from('q')
  var esc = Buffer.from([0x1B])

  process.stdout.write('\x1b[?1049h') // Enter alternate buffer.
  process.stdout.write('\x1b[H')      // Reset screen to top.
  process.stdout.write('\x1b[?25l')   // Hide cursor

  process.on('unhandledRejection', onexit)
  process.on('uncaughtException', onexit)
  process.on('SIGTERM', onexit)
  process.on('SIGINT', onexit)
  process.on('exit', onexit)
  process.stdin.on('data', handleKey)

  function handleKey (buf) {
    if (buf.compare(q) === 0 || buf.compare(esc) === 0) {
      onexit()
    }
  }

  function onexit (statusCode) {
    process.stdout.write('\x1b[?1049l')  // Enter to main buffer.
    process.stdout.write('\x1b[?25h')    // Restore cursor

    if (statusCode instanceof Error) {
      console.error('A critical error occured, forcing Bankai to abort:\n')
      console.error(clr(statusCode.stack, 'red') + '\n')
      console.error(dedent`
        If you think this might be a bug in Bankai, please consider helping
        improve Bankai's stability by submitting an error to:

        ${'  ' + clr('https://github.com/choojs/bankai/issues/new', 'underline')}

        Please include the steps to reproduce this error, the stack trace
        printed above, your version of Node, and your version of npm. Thanks!
        ${clr('— Team Choo', 'italic')}
      ` + '\n')
      statusCode = 1
    }

    process.exit(statusCode)
  }
}
<commit_msg>add configuration usage to cli (#437)<commit_after>#! /usr/bin/env node

process.title = 'bankai'

require('v8-compile-cache')

var ansi = require('ansi-escape-sequences')
var minimist = require('minimist')
var dedent = require('dedent')
var path = require('path')

var USAGE = `
  $ ${clr('bankai', 'bold')} ${clr('<command> [entry]', 'green')} [options]

  Commands:

    build       compile all files to ${clr('dist/', 'green')}
    inspect     inspect the bundle dependencies
    start       start a development server

  Options:

    -d, --debug       output lots of logs
    -h, --help        print usage
    -q, --quiet       don't output any logs
    -v, --version     print version

  Examples:

    Start a development server
    ${clr('$ bankai start index.js', 'cyan')}

    Visualize all dependencies in your project
    ${clr('$ bankai inspect index.js', 'cyan')}

    Compile all files in the project to disk
    ${clr('$ bankai build index.js', 'cyan')}

  For configuration usage, type 'bankai --help config'

  Running into trouble? Feel free to file an issue:
  ${clr('https://github.com/choojs/bankai/issues/new', 'cyan')}

  Do you enjoy using this software? Become a backer:
  ${clr('https://opencollective.com/choo', 'cyan')}
`.replace(/\n$/, '').replace(/^\n/, '')

var NOCOMMAND = `
  Please specify a bankai command:
    ${clr('$ bankai', 'cyan')} ${clr('<command>', 'green')}

  For example:
    ${clr('$ bankai start', 'cyan')} ${clr('index.js', 'green')}

  Run ${clr('bankai --help', 'cyan')} to see all options.
`.replace(/\n$/, '').replace(/^\n/, '')

var CONFIG_USAGE = `

  ${clr('Configuration', 'bold')}

  Bankai is built on top of compilers for scripts, styles and documents.
  Each of them can be configured by adding a field to your project's
  package.json file.

  These three fields are, respectively: ${clr('"browserify"', 'cyan')}, ${clr('"sheetify"', 'cyan')} and
  ${clr('"documentify"', 'cyan')}. Each one should have a configuration object as it's value.

  There is currently one possible configuration field: "transform".

  It can be one of either:

  1. An array of transform names.
       ie:  ${clr('[ "vueify" ]', 'cyan')}
  2. An array of tuples transform name + configuration object.
       ie: ${clr('[[ "vueify", { "sass": { "includePaths": [ "src/assets/css" ] } } ]]', 'cyan')}

  Full example:

  ${clr(`{
    "browserify": {
      "transform": [
        [ "vueify", { "sass": { "includePaths": [ "src/assets/css" ] } } ]
      ]
    },
    "sheetify": {
      "transform": [
        "sheetify-cssnext"
      ]
    },
    "documentify": {
      "transform": [
        [ "posthtmlify", { "use": [ "posthtml-custom-elements" ] } ]
      ]
    }
  }`, 'cyan')}
`.replace(/\n$/, '').replace(/^\n/, '')

var argv = minimist(process.argv.slice(2), {
  alias: {
    help: 'h',
    quiet: 'q',
    version: 'v',
    base: 'b'
  },
  boolean: [
    'help',
    'quiet',
    'version'
  ]
})

;(function main (argv) {
  var cmd = argv._[0]
  var entry = argv._[1]

  if (entry) {
    if (!path.isAbsolute(entry)) entry = path.join(process.cwd(), entry)
  } else {
    entry = process.cwd()
  }

  if (argv.help) {
    if (cmd === 'config') return console.log(CONFIG_USAGE)
    console.log(USAGE)
  } else if (argv.version) {
    console.log(require('./package.json').version)
  } else if (cmd === 'build') {
    var outdir = argv._[2]
    require('./lib/cmd-build')(path.join(entry), outdir, argv)
  } else if (cmd === 'inspect') {
    require('./lib/cmd-inspect')(path.join(entry), argv)
  } else if (cmd === 'start') {
    if (!argv.q) alternateBuffer()
    require('./lib/cmd-start')(path.join(entry), argv)
  } else {
    console.log(NOCOMMAND)
    process.exit(1)
  }
})(argv)

function clr (text, color) {
  return process.stdout.isTTY ? ansi.format(text, color) : text
}

// Switch to an alternate terminal buffer,
// switch back to the main terminal buffer on exit.
function alternateBuffer () {
  var q = Buffer.from('q')
  var esc = Buffer.from([0x1B])

  process.stdout.write('\x1b[?1049h') // Enter alternate buffer.
  process.stdout.write('\x1b[H')      // Reset screen to top.
  process.stdout.write('\x1b[?25l')   // Hide cursor

  process.on('unhandledRejection', onexit)
  process.on('uncaughtException', onexit)
  process.on('SIGTERM', onexit)
  process.on('SIGINT', onexit)
  process.on('exit', onexit)
  process.stdin.on('data', handleKey)

  function handleKey (buf) {
    if (buf.compare(q) === 0 || buf.compare(esc) === 0) {
      onexit()
    }
  }

  function onexit (statusCode) {
    process.stdout.write('\x1b[?1049l')  // Enter to main buffer.
    process.stdout.write('\x1b[?25h')    // Restore cursor

    if (statusCode instanceof Error) {
      console.error('A critical error occured, forcing Bankai to abort:\n')
      console.error(clr(statusCode.stack, 'red') + '\n')
      console.error(dedent`
        If you think this might be a bug in Bankai, please consider helping
        improve Bankai's stability by submitting an error to:

        ${'  ' + clr('https://github.com/choojs/bankai/issues/new', 'underline')}

        Please include the steps to reproduce this error, the stack trace
        printed above, your version of Node, and your version of npm. Thanks!
        ${clr('— Team Choo', 'italic')}
      ` + '\n')
      statusCode = 1
    }

    process.exit(statusCode)
  }
}
<|endoftext|>


<commit_before>/* Environment: Discord -- This environment connects to a Discord server/guild. */

var Environment = require('./Environment.js');
var discord = require('discord.js');

class EnvDiscord extends Environment {

    get requiredParams() { return [
        'token',                //Discord application token
        'servername',           //Server name to operate on (application must have been previously added to server)
        'defaultchannel'        //Default channel to operate on (must be a channel in the above server)
    ]; }

    get optionalParams() { return [
        'senddelay'             //Message queue send delay (ms)
    ]; }

    constructor(name) {
        super('Discord', name);

        this._params['senddelay'] = 500;

        this._client = null;
        this._server = null;
        this._channels = {};
        this._outbox = [];
        this._carrier = null;
    }

    connect() {

        var self = this;
        var params = this.params;

        this.log(`Connecting to ${params.servername}`);

        this._client = new discord.Client({
            api_request_method: 'sequential',
            fetch_all_members: true
        });

        this._client.on("ready", () => {
            this._server = this._client.guilds.find("name", params.servername);

            this._channels[this._server.defaultChannel.name] = this._server.defaultChannel;
            if (params.defaultchannel != this._server.defaultChannel.name) {
                this._channels[params.defaultchannel] = this._server.channels.filter((channel) => (channel.type == "text")).find("name", params.defaultchannel);
            }

            this._carrier = setInterval(() => {
                    self.deliverMsgs.apply(self, null)
                }, params.senddelay);

            this.log("Environment is now ready!");
        });

        this._client.on("message", (message) => {

            if (message.author.username == this._client.user.username) return;

            var type = "regular";
            var channelid = message.channel.id;
            if (message.channel.type == "dm") {
                type = "private";
                channelid = message.author.id;
            }

            for (let callback of this._cbMessage) {
                if (this.invokeRegisteredCallback(callback, [this, type, message.content, message.author.id, channelid, message])) {
                    break;
                }
            }

        });

        this._client.on("guildMemberAdd", (server, member) => {
            var chans = this.findAccessChannels(member);
            if (chans.length) {
                this.triggerJoin(member.id, chans, ["add"]);
            }
        });

        this._client.on("guildMemberRemove", (server, member) => {
            if (member.user.status == "offline") return;

            var chans = this.findAccessChannels(member);
            if (chans.length) {
                this.triggerPart(member.id, chans, ["remove"]);
            }
        });

        this._client.on("guildMemberUpdate", (server, oldMember, newMember) => {
            if (newMember.user.status == "offline") return;

            var had = {};
            for (let chan of this.findAccessChannels(oldMember)) {
                had[chan.id] = chan;
            }

            var tojoin = [];
            var topart = [];

            for (let chan of this.findAccessChannels(newMember)) {
                if (!had[chan.id]) tojoin.push(chan);
                else delete had[chan.id];
            }
            for (let chanid in had) {
                topart.push(had[chanid]);
            }

            if (tojoin.length) {
                this.triggerJoin(newMember.id, tojoin, ["permissions"]);
            }
            if (topart.length) {
                this.triggerPart(oldMember.id, topart, ["permissions"]);
            }
        });

        this._client.on("presenceUpdate", (oldUser, newUser) => {
            var reason = null;
            if (oldUser.status == "offline" && newUser.status != "offline") {
                reason = "join";
            }
            if (oldUser.status != "offline" && newUser.status == "offline") {
                reason = "part";
            }
            if (!reason) return;

            var member = this._server.members.find('id', newUser.id);
            var chans = this.findAccessChannels(member);

            if (reason == "join") {
                this.triggerJoin(member.id, chans, [reason, newUser.status]);
            }
            if (reason == "part") {
                if (member) this.triggerPart(member.id, chans, [reason, oldUser.status]);
            }
        });

        this._client.login(params.token).catch(this.genericErrorHandler);

    }

    disconnect() {
        if (this._carrier) clearInterval(this._carrier);
        if (this._client) this._client.destroy().catch(this.genericErrorHandler);
        this.carrier = null;
        this.client = null;
        this.log(`Disconnected from ${this._name}`);
    }

    msg(targetid, msg) {
        var targetchan = this.getActualChanFromTarget(targetid);

        if (!targetchan) {
            targetchan = this._channels[this.param('defaultchannel')];
        }

        this._outbox.push([targetchan, msg]);
    }

    notice(targetid, msg) {
        this.msg(targetid, msg);
    }

    idToDisplayName(id) {
        var member = this._server.members.find("id", id);
        if (member) return (member.nickname ? member.nickname : member.user.username);
        return id;
    }

    displayNameToId(displayname) {
        var refuser = null;

        var parts = displayname.split("#");
        if (parts[1]) {
            refuser = this._server.members.filter((member) => (member.user.username == parts[0])).find("user.discriminator", parts[1]);
        } else {
            var cache = this._server.members.filter((member) => (member.user.username == displayname)).array();
            if (cache.length == 1) {
                refuser = cache[0];
            } else {
                displayname = displayname.toLowerCase();
                refuser = this._server.members.find((member) => (member.nickname && member.nickname.toLowerCase() == displayname));
            }
        }

        if (refuser) {
            return refuser.id;
        }

        return null;
    }

    idIsSecured(id) {
        var member = this._server.members.find("id", id);
        return !!member;
    }

    idIsAuthenticated(id) {
        var member = this._server.members.find("id", id);
        return !!member;
    }

    listUserIds(channel) {
        var targetchan = this.getActualChanFromTarget(channel);
        if (!targetchan) {
            targetchan = this._channels[this.param('defaultchannel')];
        }

        if (targetchan.type == "dm") return [targetchan.recipient.id];

        var ids = [];
        if (targetchan.type == "group") {
            for (let user of targetchan.recipients.array()) {
                ids.push(user.id);
            }
        }
        if (targetchan.type == "text") {
            for (let member of targetchan.members.array()) {
                ids.push(member.id);
            }
        }

        return ids;
    }

    channelIdToDisplayName(channelid) {
        var channel = this._server.channels.find("id", channelid);
        if (channel) return channel.name;
        return channelid;
    }

    normalizeFormatting(text) {
        text = String(text).replace(/<@&([0-9]+)>/g, (match, id) => {
            let role = this._server.roles.find("id", id);
            if (!role) return "";
            return "@" + role.name;
        });

        text = text.replace(/<@!?([0-9]+)>/g, (match, id) => {
            let user = this._server.members.find("id", id);
            if (!user) return "";
            return "@" + (user.nickname ? user.nickname : user.user.username);
        });

        text = text.replace(/<#([0-9]+)>/g, (match, id) => {
            let chan = this._server.channels.find("id", id);
            if (!chan) return "";
            return "#" + chan.name;
        });

        return text.replace(/~~(.*?)~~/g, "$1").replace(/(^|[^a-z0-9])_(.*?)_([^a-z0-9]|$)/gi, "$1*$2*$3");
    }

    applyFormatting(text) {
        //Normalized formatting is already fully compatible with Discord
        return String(text);
    }

    //Auxiliary methods

    deliverMsgs() {
        var packages = {};
        for (var i = 0; this._outbox && i < this._outbox.length; i++) {
            var rawchannelid = this._outbox[i][0].id;
            if (!packages[rawchannelid]) {
                packages[rawchannelid] = {
                    targetchan: this._outbox[i][0],
                    messages: []
                }
            }
            packages[rawchannelid].messages.push(this._outbox[i][1]);
        }
        for (var rawchannelid in packages) {
            packages[rawchannelid].targetchan.sendMessage(
                packages[rawchannelid].messages.join("\n"),
                {
                    disable_everyone: true,
                    split: {char: "\n"}
                }
            ).catch(this.genericErrorHandler);
        }
        this._outbox = [];
    }

    get server() { return this._server; }

    getActualChanFromTarget(targetid) {
        var targetchan = null;

        if (typeof targetid == "string") {
            if (!this._channels[targetid]) {
                this._channels[targetid] = this._server.channels.filter((channel) => (channel.type == "text")).find("id", targetid);
            }
            if (!this._channels[targetid]) {
                this._channels[targetid] = this._server.members.find("id", targetid);
            }
            if (!this._channels[targetid]) {
                this._channels[targetid] = this._server.channels.filter((channel) => (channel.type == "text")).find("name", targetid);
            }
            if (!this._channels[targetid]) {
                this._channels[targetid] = this._server.members.find("name", targetid);
            }
            if (this._channels[targetid]) {
                targetchan = this._channels[targetid];
            }
        } else {
            targetchan = targetid;
        }

        return targetchan;
    }

    findAccessChannels(member) {
        var channels = [];
        if (!member) return channels;

        var allchannels = member.guild.channels.array();
        for (let channel of allchannels) {
            if (channel.permissionsFor(member).hasPermission("READ_MESSAGES")) {
                channels.push(channel);
            }
        }

        return channels;
    }

    triggerJoin(authorid, channels, info) {
        if (!info) info = {};
        for (let callback of this._cbJoin) {
            for (let channel of channels) {
                if (this.invokeRegisteredCallback(callback, [this, authorid, channel.id, info])) {
                    break;
                }
            }
        }
    }

    triggerPart(authorid, channels, info) {
        if (!info) info = {};
        for (let callback of this._cbPart) {
            for (let channel of channels) {
                if (this.invokeRegisteredCallback(callback, [this, authorid, channel.id, info])) {
                    break;
                }
            }
        }
    }

};

module.exports = EnvDiscord;
<commit_msg>Upgrade to discord.js v10<commit_after>/* Environment: Discord -- This environment connects to a Discord server/guild. */

var Environment = require('./Environment.js');
var discord = require('discord.js');

class EnvDiscord extends Environment {

    get requiredParams() { return [
        'token',                //Discord application token
        'servername',           //Server name to operate on (application must have been previously added to server)
        'defaultchannel'        //Default channel to operate on (must be a channel in the above server)
    ]; }

    get optionalParams() { return [
        'senddelay'             //Message queue send delay (ms)
    ]; }

    constructor(name) {
        super('Discord', name);

        this._params['senddelay'] = 500;

        this._client = null;
        this._server = null;
        this._channels = {};
        this._outbox = [];
        this._carrier = null;
    }

    connect() {

        var self = this;
        var params = this.params;

        this.log(`Connecting to ${params.servername}`);

        this._client = new discord.Client({
            api_request_method: 'sequential',
            fetch_all_members: true
        });

        this._client.on("ready", () => {
            this._server = this._client.guilds.find("name", params.servername);

            this._channels[this._server.defaultChannel.name] = this._server.defaultChannel;
            if (params.defaultchannel != this._server.defaultChannel.name) {
                this._channels[params.defaultchannel] = this._server.channels.filter((channel) => (channel.type == "text")).find("name", params.defaultchannel);
            }

            this._carrier = setInterval(() => {
                    self.deliverMsgs.apply(self, null)
                }, params.senddelay);

            this.log("Environment is now ready!");
        });

        this._client.on("message", (message) => {

            if (message.author.username == this._client.user.username) return;

            var type = "regular";
            var channelid = message.channel.id;
            if (message.channel.type == "dm") {
                type = "private";
                channelid = message.author.id;
            }

            for (let callback of this._cbMessage) {
                if (this.invokeRegisteredCallback(callback, [this, type, message.content, message.author.id, channelid, message])) {
                    break;
                }
            }

        });

        this._client.on("guildMemberAdd", (member) => {
            var chans = this.findAccessChannels(member);
            if (chans.length) {
                this.triggerJoin(member.id, chans, ["add"]);
            }
        });

        this._client.on("guildMemberRemove", (member) => {
            if (member.user.presence.status == "offline") return;

            var chans = this.findAccessChannels(member);
            if (chans.length) {
                this.triggerPart(member.id, chans, ["remove"]);
            }
        });

        this._client.on("guildMemberUpdate", (oldMember, newMember) => {
            if (newMember.user.presence.status == "offline") return;

            var had = {};
            for (let chan of this.findAccessChannels(oldMember)) {
                had[chan.id] = chan;
            }

            var tojoin = [];
            var topart = [];

            for (let chan of this.findAccessChannels(newMember)) {
                if (!had[chan.id]) tojoin.push(chan);
                else delete had[chan.id];
            }
            for (let chanid in had) {
                topart.push(had[chanid]);
            }

            if (tojoin.length) {
                this.triggerJoin(newMember.id, tojoin, ["permissions"]);
            }
            if (topart.length) {
                this.triggerPart(oldMember.id, topart, ["permissions"]);
            }
        });

        this._client.on("presenceUpdate", (oldUser, newUser) => {
            var reason = null;
            if (oldUser.presence.status == "offline" && newUser.presence.status != "offline") {
                reason = "join";
            }
            if (oldUser.presence.status != "offline" && newUser.presence.status == "offline") {
                reason = "part";
            }
            if (!reason) return;

            var member = this._server.members.find('id', newUser.id);
            var chans = this.findAccessChannels(member);

            if (reason == "join") {
                this.triggerJoin(member.id, chans, [reason, newUser.presence.status]);
            }
            if (reason == "part") {
                if (member) this.triggerPart(member.id, chans, [reason, oldUser.presence.status]);
            }
        });

        this._client.login(params.token).catch(this.genericErrorHandler);

    }

    disconnect() {
        if (this._carrier) clearInterval(this._carrier);
        if (this._client) this._client.destroy().catch(this.genericErrorHandler);
        this.carrier = null;
        this.client = null;
        this.log(`Disconnected from ${this._name}`);
    }

    msg(targetid, msg) {
        var targetchan = this.getActualChanFromTarget(targetid);

        if (!targetchan) {
            targetchan = this._channels[this.param('defaultchannel')];
        }

        this._outbox.push([targetchan, msg]);
    }

    notice(targetid, msg) {
        this.msg(targetid, msg);
    }

    idToDisplayName(id) {
        var member = this._server.members.find("id", id);
        if (member) return (member.nickname ? member.nickname : member.user.username);
        return id;
    }

    displayNameToId(displayname) {
        var refuser = null;

        var parts = displayname.split("#");
        if (parts[1]) {
            refuser = this._server.members.filter((member) => (member.user.username == parts[0])).find("user.discriminator", parts[1]);
        } else {
            var cache = this._server.members.filter((member) => (member.user.username == displayname)).array();
            if (cache.length == 1) {
                refuser = cache[0];
            } else {
                displayname = displayname.toLowerCase();
                refuser = this._server.members.find((member) => (member.nickname && member.nickname.toLowerCase() == displayname));
            }
        }

        if (refuser) {
            return refuser.id;
        }

        return null;
    }

    idIsSecured(id) {
        var member = this._server.members.find("id", id);
        return !!member;
    }

    idIsAuthenticated(id) {
        var member = this._server.members.find("id", id);
        return !!member;
    }

    listUserIds(channel) {
        var targetchan = this.getActualChanFromTarget(channel);
        if (!targetchan) {
            targetchan = this._channels[this.param('defaultchannel')];
        }

        if (targetchan.type == "dm") return [targetchan.recipient.id];

        var ids = [];
        if (targetchan.type == "group") {
            for (let user of targetchan.recipients.array()) {
                ids.push(user.id);
            }
        }
        if (targetchan.type == "text") {
            for (let member of targetchan.members.array()) {
                ids.push(member.id);
            }
        }

        return ids;
    }

    channelIdToDisplayName(channelid) {
        var channel = this._server.channels.find("id", channelid);
        if (channel) return channel.name;
        return channelid;
    }

    normalizeFormatting(text) {
        text = String(text).replace(/<@&([0-9]+)>/g, (match, id) => {
            let role = this._server.roles.find("id", id);
            if (!role) return "";
            return "@" + role.name;
        });

        text = text.replace(/<@!?([0-9]+)>/g, (match, id) => {
            let user = this._server.members.find("id", id);
            if (!user) return "";
            return "@" + (user.nickname ? user.nickname : user.user.username);
        });

        text = text.replace(/<#([0-9]+)>/g, (match, id) => {
            let chan = this._server.channels.find("id", id);
            if (!chan) return "";
            return "#" + chan.name;
        });

        return text.replace(/~~(.*?)~~/g, "$1").replace(/(^|[^a-z0-9])_(.*?)_([^a-z0-9]|$)/gi, "$1*$2*$3");
    }

    applyFormatting(text) {
        //Normalized formatting is already fully compatible with Discord
        return String(text);
    }

    //Auxiliary methods

    deliverMsgs() {
        var packages = {};
        for (var i = 0; this._outbox && i < this._outbox.length; i++) {
            var rawchannelid = this._outbox[i][0].id;
            if (!packages[rawchannelid]) {
                packages[rawchannelid] = {
                    targetchan: this._outbox[i][0],
                    messages: []
                }
            }
            packages[rawchannelid].messages.push(this._outbox[i][1]);
        }
        for (var rawchannelid in packages) {
            packages[rawchannelid].targetchan.sendMessage(
                packages[rawchannelid].messages.join("\n"),
                {
                    disable_everyone: true,
                    split: {char: "\n"}
                }
            ).catch(this.genericErrorHandler);
        }
        this._outbox = [];
    }

    get server() { return this._server; }

    getActualChanFromTarget(targetid) {
        var targetchan = null;

        if (typeof targetid == "string") {
            if (!this._channels[targetid]) {
                this._channels[targetid] = this._server.channels.filter((channel) => (channel.type == "text")).find("id", targetid);
            }
            if (!this._channels[targetid]) {
                this._channels[targetid] = this._server.members.find("id", targetid);
            }
            if (!this._channels[targetid]) {
                this._channels[targetid] = this._server.channels.filter((channel) => (channel.type == "text")).find("name", targetid);
            }
            if (!this._channels[targetid]) {
                this._channels[targetid] = this._server.members.find("name", targetid);
            }
            if (this._channels[targetid]) {
                targetchan = this._channels[targetid];
            }
        } else {
            targetchan = targetid;
        }

        return targetchan;
    }

    findAccessChannels(member) {
        var channels = [];
        if (!member) return channels;

        var allchannels = member.guild.channels.array();
        for (let channel of allchannels) {
            if (channel.permissionsFor(member).hasPermission("READ_MESSAGES")) {
                channels.push(channel);
            }
        }

        return channels;
    }

    triggerJoin(authorid, channels, info) {
        if (!info) info = {};
        for (let callback of this._cbJoin) {
            for (let channel of channels) {
                if (this.invokeRegisteredCallback(callback, [this, authorid, channel.id, info])) {
                    break;
                }
            }
        }
    }

    triggerPart(authorid, channels, info) {
        if (!info) info = {};
        for (let callback of this._cbPart) {
            for (let channel of channels) {
                if (this.invokeRegisteredCallback(callback, [this, authorid, channel.id, info])) {
                    break;
                }
            }
        }
    }

};

module.exports = EnvDiscord;
<|endoftext|>