<commit_before>"use strict";

/**
 * @fileoverview WebSocket implementation
 */

/*global require, java, sync */
var GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
    {Thread} = require('Threads'),
    sha1 = require('support').sha1;

//function sha1 (str) {
//    // http://kevin.vanzonneveld.net
//    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
//    // + namespaced by: Michael White (http://getsprink.com)
//    // +      input by: Brett Zamir (http://brett-zamir.me)
//    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
//    // -    depends on: utf8_encode
//    // *     example 1: sha1('Kevin van Zonneveld');
//    // *     returns 1: '54916d2e62f65b3afa6e192e6a601cdbe5cb5897'
//    var rotate_left = function (n, s) {
//        var t4 = (n << s) | (n >>> (32 - s));
//        return t4;
//    };
//
//    /*var lsb_hex = function (val) { // Not in use; needed?
//     var str="";
//     var i;
//     var vh;
//     var vl;
//
//     for ( i=0; i<=6; i+=2 ) {
//     vh = (val>>>(i*4+4))&0x0f;
//     vl = (val>>>(i*4))&0x0f;
//     str += vh.toString(16) + vl.toString(16);
//     }
//     return str;
//     };*/
//
//    var cvt_hex = function (val) {
//        var str = "";
//        var i;
//        var v;
//
//        for (i = 7; i >= 0; i--) {
//            v = (val >>> (i * 4)) & 0x0f;
//            str += v.toString(16);
//        }
//        return str;
//    };
//
//    var blockstart;
//    var i, j;
//    var W = new Array(80);
//    var H0 = 0x67452301;
//    var H1 = 0xEFCDAB89;
//    var H2 = 0x98BADCFE;
//    var H3 = 0x10325476;
//    var H4 = 0xC3D2E1F0;
//    var A, B, C, D, E;
//    var temp;
//
//    str = utf8_encode(str);
//    var str_len = str.length;
//
//    var word_array = [];
//    for (i = 0; i < str_len - 3; i += 4) {
//        j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 | str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3);
//        word_array.push(j);
//    }
//
//    switch (str_len % 4) {
//        case 0:
//            i = 0x080000000;
//            break;
//        case 1:
//            i = str.charCodeAt(str_len - 1) << 24 | 0x0800000;
//            break;
//        case 2:
//            i = str.charCodeAt(str_len - 2) << 24 | str.charCodeAt(str_len - 1) << 16 | 0x08000;
//            break;
//        case 3:
//            i = str.charCodeAt(str_len - 3) << 24 | str.charCodeAt(str_len - 2) << 16 | str.charCodeAt(str_len - 1) << 8 | 0x80;
//            break;
//    }
//
//    word_array.push(i);
//
//    while ((word_array.length % 16) != 14) {
//        word_array.push(0);
//    }
//
//    word_array.push(str_len >>> 29);
//    word_array.push((str_len << 3) & 0x0ffffffff);
//
//    for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {
//        for (i = 0; i < 16; i++) {
//            W[i] = word_array[blockstart + i];
//        }
//        for (i = 16; i <= 79; i++) {
//            W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
//        }
//
//
//        A = H0;
//        B = H1;
//        C = H2;
//        D = H3;
//        E = H4;
//
//        for (i = 0; i <= 19; i++) {
//            temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
//            E = D;
//            D = C;
//            C = rotate_left(B, 30);
//            B = A;
//            A = temp;
//        }
//
//        for (i = 20; i <= 39; i++) {
//            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
//            E = D;
//            D = C;
//            C = rotate_left(B, 30);
//            B = A;
//            A = temp;
//        }
//
//        for (i = 40; i <= 59; i++) {
//            temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
//            E = D;
//            D = C;
//            C = rotate_left(B, 30);
//            B = A;
//            A = temp;
//        }
//
//        for (i = 60; i <= 79; i++) {
//            temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
//            E = D;
//            D = C;
//            C = rotate_left(B, 30);
//            B = A;
//            A = temp;
//        }
//
//        H0 = (H0 + A) & 0x0ffffffff;
//        H1 = (H1 + B) & 0x0ffffffff;
//        H2 = (H2 + C) & 0x0ffffffff;
//        H3 = (H3 + D) & 0x0ffffffff;
//        H4 = (H4 + E) & 0x0ffffffff;
//    }
//
//    temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
//    return temp.toLowerCase();
//}

function base64_encode (data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Rafał Kukawski (http://kukawski.pl)
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] == 'function') {
    //    return btoa(data);
    //}
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        enc = "",
        tmp_arr = [];

    if (!data) {
        return data;
    }

    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1 << 16 | o2 << 8 | o3;

        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;
        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);

    enc = tmp_arr.join('');

    var r = data.length % 3;

    return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

}

function uuid() {
    function s4() {
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    return (s4()+s4()+"-"+s4()+"-"+s4()+"-"+s4()+"-"+s4()+s4()+s4());
}

function makeAccept(key) {
    var hex = sha1(key + GUID);
    var buf = '';

    // convert ASCII sha1 hex to binary
    while (hex.length) {
        buf += String.fromCharCode(parseInt(hex.substr(0, 2), 16));
        hex = hex.substr(2);
    }
    buf = base64_encode(buf);
    return buf;
}

var webSockets = {};

/**
 * Construct a new WebSocket.
 *
 * This constructor is typically not called by applications.  It is instantiated by
 * http.Child when an upgrade request is received.
 *
 * The instantiated WebSocket object may well be manipulated (see member methods below)
 * by application code.
 *
 * @param {Request} req http.Request for the current Child Thread
 * @param {Response} res http.Response for the current Child Thread
 * @constructor
 */
function WebSocket(req, res) {
    res.status = 101;
    decaf.extend(res.headers, {
        'Upgrade'             : 'websocket',
        'Connection'          : 'upgrade',
        'Sec-WebSocket-Accept': makeAccept(req.headers['sec-websocket-key']) // base64_encode(buf)
    });
    res.sendHeaders();
    res.flush();

    this.req = req;
    this.res = res;

    this.handlers = {};
    this.uuid = uuid();

    // this assures only one thread at a time can be in a WebSocket's
    // sendMessage method.
    this.sendMessage = sync(function (s) {
        this.rawSendMessage(s);
    }, this);
    this.ping = sync(function () {
        this.rawSendPing();
    }, this);
    this.pong = sync(function () {
        this.rawSendPong();
    }, this);
}

decaf.extend(WebSocket.prototype, {
    /**
     * Register a handler to be called when an event is fired on this socket.
     *
     * There is one defined event currently, "message" that allows applications
     * to have an event handler called when a message is received over the Socket.
     *
     * Applications can listen on any arbitrary events as well, since the eventName
     * is any string, and there is a fireEvent() method that the applicaiton can call.
     *
     * For example, the application might listen for message events, and when a
     * "quit chat room" message received, fire a "quit chat room" event.
     *
     * @param {string} eventName name of event
     * @param {function} handler function to call when event is fired
     */
    on: function (eventName, handler) {
        this.handlers[eventName] = this.handlers[eventName] || [];
        this.handlers[eventName].push(handler);
    },

    /**
     * Fire an event by name.
     *
     * THe data argument can be any arbitrary thing.  It is passed to the
     * event handler untouched.
     *
     * @param {string} eventName name/kind of event to fire
     * @param {object} data arbitrary data passed to event handlers
     */
    fireEvent: function (eventName, data) {
        var handlers = this.handlers[eventName];
        if (handlers) {
            decaf.each(handlers, function (handler) {
                handler(data);
            });
        }
    },

    /**
     * Broadcast a message to all sockets with the specified path (ws URI)
     *
     * The message sent is a string.  Caller may send JSON encoded objects
     * to the client, and the client should know to decode the object.
     *
     * @param {string} path WebSocket path
     * @param {string} message message to send
     */
    broadcast: function (path, message) {
        var me = this;
        new Thread(function () {
            decaf.each(webSockets, function (ws) {
                if (ws.uuid !== me.uuid && ws.req.uri === path) {
                    ws.sendMessage(message);
                }
            });
        }).start();
    },

    run: function () {
        var is = this.req.is,
            message;

        is.socket.setSoTimeout(0);

        webSockets[this.uuid] = this;

        // child thread blocks reading message
        while ((message = this.getMessage(is)) !== false) {
            this.fireEvent('message', message);
        }
        this.fireEvent('close');
        delete webSockets[this.uuid];
    },

    rawSendMessage: function (s) {
        var os = this.res.os.socket.getOutputStream(),
            len = s.length;

        os.write(0x81);
        if (len < 126) {
            os.write(len);
        }
        else if (len < 65536) {
            os.write(0x7e);
            os.write((len >> 8) & 0xff);
            os.write(len & 0xff);
        }
        else {
            os.write(0x7f);
            os.write((len >> 56) & 0xff);
            os.write((len >> 48) & 0xff);
            os.write((len >> 40) & 0xff);
            os.write((len >> 32) & 0xff);
            os.write((len >> 24) & 0xff);
            os.write((len >> 16) & 0xff);
            os.write((len >> 8) & 0xff);
            os.write((len >> 0) & 0xff);
        }
        os.write(decaf.toJavaByteArray(s));
        os.flush();
    },

    rawSendPing: function () {
        var os = this.res.os.socket.getOutputStream();
        os.write(0x89);
        os.write(0);
    },

    rawSendPong: function () {
        var os = this.res.os.socket.getOutputStream();
        os.write(0x8a);
        os.write(0);
    },

    getMessage: function (is) {
        function next() {
            return is.readByte();
        }

        var message = '',
            fin = false;

        try {
            while (!fin) {
                var opCode = next();

                fin = !!(opCode & 0x80);
                opCode &= 0x7f;
                switch (opCode) {
                    case 0x0:       // continuation frame
                        break;
                    case 0x1:       // text frame
                        break;
                    case 0x2:       // binary frame
                        break;
                    case 0x8:       // close
                        return false;
                    case 0x9:       // ping
                        this.pong();
                        break;
                    case 0xa:       // pong
                        break;
                    default:        // reserved
                        break;
                }

                var len = next(),
                    mask = (len & 0x80) ? [] : null,
                    i,
                    ndx = 0;

                len = len & 0x7f;
                if (len === 0x7e) {
                    len = (next() << 8) | next();
                }
                else if (len === 0x7f) {
                    len = 0;
                    for (i = 0; i < 8; i++) {
                        len = len << 8;
                        len |= next();
                    }
                }
                if (mask) {
                    mask.push(next());
                    mask.push(next());
                    mask.push(next());
                    mask.push(next());
                    for (i = 0; i < len; i++) {
                        message += String.fromCharCode(next() ^ mask[ndx++]);
                        ndx %= 4;
                    }
                }
                else {
                    // should never happen - client MUST mask
                    for (i = 0; i < len; i++) {
                        message += String.fromCharCode(next());
                        ndx %= 4;
                    }
                }
                if (len === 0) {
                    fin = false;
                }
            }
            return message;
        }
        catch (e) {
//                if (e.dumpText()) {
//                    e.dumpText();
//                }
//                else {
//                    console.log(e);
//                }
            return false;
        }
    }

});

decaf.extend(exports, {
    WebSocket: WebSocket
});
<commit_msg>Use uuid, base64_encode from support module<commit_after>"use strict";

/**
 * @fileoverview WebSocket implementation
 */

/*global require, java, sync */
var GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
    {Thread} = require('Threads'),
    {sha1, base64_encode, uuid} = require('support');

function makeAccept(key) {
    var hex = sha1(key + GUID);
    var buf = '';

    // convert ASCII sha1 hex to binary
    while (hex.length) {
        buf += String.fromCharCode(parseInt(hex.substr(0, 2), 16));
        hex = hex.substr(2);
    }
    buf = base64_encode(buf);
    return buf;
}

var webSockets = {};

/**
 * Construct a new WebSocket.
 *
 * This constructor is typically not called by applications.  It is instantiated by
 * http.Child when an upgrade request is received.
 *
 * The instantiated WebSocket object may well be manipulated (see member methods below)
 * by application code.
 *
 * @param {Request} req http.Request for the current Child Thread
 * @param {Response} res http.Response for the current Child Thread
 * @constructor
 */
function WebSocket(req, res) {
    res.status = 101;
    decaf.extend(res.headers, {
        'Upgrade'              : 'websocket',
        'Connection'           : 'upgrade',
        'Sec-WebSocket-Accept' : makeAccept(req.headers['sec-websocket-key']) // base64_encode(buf)
    });
    res.sendHeaders();
    res.flush();

    this.req = req;
    this.res = res;

    this.handlers = {};
    this.uuid = uuid();

    // this assures only one thread at a time can be in a WebSocket's
    // sendMessage method.
    this.sendMessage = sync(function (s) {
        this.rawSendMessage(s);
    }, this);
    this.ping = sync(function () {
        this.rawSendPing();
    }, this);
    this.pong = sync(function () {
        this.rawSendPong();
    }, this);
}

decaf.extend(WebSocket.prototype, {
    /**
     * Register a handler to be called when an event is fired on this socket.
     *
     * There is one defined event currently, "message" that allows applications
     * to have an event handler called when a message is received over the Socket.
     *
     * Applications can listen on any arbitrary events as well, since the eventName
     * is any string, and there is a fireEvent() method that the applicaiton can call.
     *
     * For example, the application might listen for message events, and when a
     * "quit chat room" message received, fire a "quit chat room" event.
     *
     * @param {string} eventName name of event
     * @param {function} handler function to call when event is fired
     */
    on : function (eventName, handler) {
        this.handlers[eventName] = this.handlers[eventName] || [];
        this.handlers[eventName].push(handler);
    },

    /**
     * Fire an event by name.
     *
     * THe data argument can be any arbitrary thing.  It is passed to the
     * event handler untouched.
     *
     * @param {string} eventName name/kind of event to fire
     * @param {object} data arbitrary data passed to event handlers
     */
    fireEvent : function (eventName, data) {
        var handlers = this.handlers[eventName];
        if (handlers) {
            decaf.each(handlers, function (handler) {
                handler(data);
            });
        }
    },

    /**
     * Broadcast a message to all sockets with the specified path (ws URI)
     *
     * The message sent is a string.  Caller may send JSON encoded objects
     * to the client, and the client should know to decode the object.
     *
     * @param {string} path WebSocket path
     * @param {string} message message to send
     */
    broadcast : function (path, message) {
        var me = this;
        new Thread(function () {
            decaf.each(webSockets, function (ws) {
                if (ws.uuid !== me.uuid && ws.req.uri === path) {
                    ws.sendMessage(message);
                }
            });
        }).start();
    },

    run : function () {
        var is = this.req.is,
            message;

        is.socket.setSoTimeout(0);

        webSockets[this.uuid] = this;

        // child thread blocks reading message
        while ((message = this.getMessage(is)) !== false) {
            this.fireEvent('message', message);
        }
        this.fireEvent('close');
        delete webSockets[this.uuid];
    },

    rawSendMessage : function (s) {
        var os = this.res.os.socket.getOutputStream(),
            len = s.length;

        os.write(0x81);
        if (len < 126) {
            os.write(len);
        }
        else if (len < 65536) {
            os.write(0x7e);
            os.write((len >> 8) & 0xff);
            os.write(len & 0xff);
        }
        else {
            os.write(0x7f);
            os.write((len >> 56) & 0xff);
            os.write((len >> 48) & 0xff);
            os.write((len >> 40) & 0xff);
            os.write((len >> 32) & 0xff);
            os.write((len >> 24) & 0xff);
            os.write((len >> 16) & 0xff);
            os.write((len >> 8) & 0xff);
            os.write((len >> 0) & 0xff);
        }
        os.write(decaf.toJavaByteArray(s));
        os.flush();
    },

    rawSendPing : function () {
        var os = this.res.os.socket.getOutputStream();
        os.write(0x89);
        os.write(0);
    },

    rawSendPong : function () {
        var os = this.res.os.socket.getOutputStream();
        os.write(0x8a);
        os.write(0);
    },

    getMessage : function (is) {
        function next() {
            return is.readByte();
        }

        var message = '',
            fin = false;

        try {
            while (!fin) {
                var opCode = next();

                fin = !!(opCode & 0x80);
                opCode &= 0x7f;
                switch (opCode) {
                    case 0x0:       // continuation frame
                        break;
                    case 0x1:       // text frame
                        break;
                    case 0x2:       // binary frame
                        break;
                    case 0x8:       // close
                        return false;
                    case 0x9:       // ping
                        this.pong();
                        break;
                    case 0xa:       // pong
                        break;
                    default:        // reserved
                        break;
                }

                var len = next(),
                    mask = (len & 0x80) ? [] : null,
                    i,
                    ndx = 0;

                len = len & 0x7f;
                if (len === 0x7e) {
                    len = (next() << 8) | next();
                }
                else if (len === 0x7f) {
                    len = 0;
                    for (i = 0; i < 8; i++) {
                        len = len << 8;
                        len |= next();
                    }
                }
                if (mask) {
                    mask.push(next());
                    mask.push(next());
                    mask.push(next());
                    mask.push(next());
                    for (i = 0; i < len; i++) {
                        message += String.fromCharCode(next() ^ mask[ndx++]);
                        ndx %= 4;
                    }
                }
                else {
                    // should never happen - client MUST mask
                    for (i = 0; i < len; i++) {
                        message += String.fromCharCode(next());
                        ndx %= 4;
                    }
                }
                if (len === 0) {
                    fin = false;
                }
            }
            return message;
        }
        catch (e) {
//                if (e.dumpText()) {
//                    e.dumpText();
//                }
//                else {
//                    console.log(e);
//                }
            return false;
        }
    }

});

decaf.extend(exports, {
    WebSocket : WebSocket
});
<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/combine',
        '../Core/defaultValue',
        '../Core/freezeObject',
        '../Core/writeTextToCanvas',
        '../Core/DeveloperError',
        '../Core/Extent',
        './ImageryProvider',
        './WebMercatorTilingScheme',
        './GeographicTilingScheme'
    ], function(
        combine,
        defaultValue,
        freezeObject,
        writeTextToCanvas,
        DeveloperError,
        Extent,
        ImageryProvider,
        WebMercatorTilingScheme,
        GeographicTilingScheme) {
    "use strict";

    /**
     * Provides tiled imagery hosted by a Web Map Service (WMS) server.
     *
     * @alias WebMapServiceImageryProvider
     * @constructor
     *
     * @param {String} description.url The URL of the WMS service.
     * @param {String} description.layers The layers to include, separated by commas.
     * @param {Object} [description.parameters=WebMapServiceImageryProvider.DefaultParameters] Additional parameters to pass to the WMS server in the GetMap URL.
     * @param {Extent} [description.extent=Extent.MAX_VALUE] The extent of the layer.
     * @param {Number} [description.maximumLevel] The maximum level-of-detail supported by the imagery provider.
     *        If not specified, there is no limit.
     * @param {String} [description.credit] A string crediting the data source, which is displayed on the canvas.
     * @param {Object} [description.proxy] A proxy to use for requests. This object is
     *        expected to have a getURL function which returns the proxied URL, if needed.
     *
     * @exception {DeveloperError} description.url is required.
     *
     * @see ArcGisMapServerImageryProvider
     * @see SingleTileImageryProvider
     * @see BingMapsImageryProvider
     * @see OpenStreetMapImageryProvider
     *
     * @see ArcGIS Server REST API
     * @see Cross-Origin Resource Sharing
     *
     * @example
     * var provider = new WebMapServiceImageryProvider({
     *     url: 'http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer',
     *     layerName: '0',
     *     proxy: new Cesium.DefaultProxy('/proxy/')
     * });
     */
    var WebMapServiceImageryProvider = function WebMapServiceImageryProvider(description) {
        description = defaultValue(description, {});

        if (typeof description.url === 'undefined') {
            throw new DeveloperError('description.url is required.');
        }

        if (typeof description.layers === 'undefined') {
            throw new DeveloperError('description.layers is required.');
        }

        this._url = description.url;
        this._tileDiscardPolicy = description.tileDiscardPolicy;
        this._proxy = description.proxy;
        this._layers = description.layers;

        var parameters = defaultValue(description.parameters, {});
        this._parameters = combine([parameters, WebMapServiceImageryProvider.DefaultParameters], false, true);

        this._tileWidth = 256;
        this._tileHeight = 256;
        this._maximumLevel = description.maximumLevel; // undefined means no limit

        var extent = defaultValue(description.extent, Extent.MAX_VALUE);
        this._tilingScheme = new GeographicTilingScheme({
            extent : extent
        });

        // Create the credit message.
        if (typeof description.credit !== 'undefined') {
            // Create the copyright message.
            this._logo = writeTextToCanvas(description.credit, {
                font : '12px sans-serif'
            });
        }

        this._ready = true;
    };

    function buildImageUrl(imageryProvider, x, y, level) {
        var url = imageryProvider._url;
        var indexOfQuestionMark = url.indexOf('?');
        if (indexOfQuestionMark >= 0 && indexOfQuestionMark < url.length - 1) {
            url += '&';
        } else if (indexOfQuestionMark < 0) {
            url += '?';
        }

        var parameters = imageryProvider._parameters;
        for (var parameter in parameters) {
            if (parameters.hasOwnProperty(parameter)) {
                url += parameter + '=' + parameters[parameter] + '&';
            }
        }

        if (typeof parameters.layers === 'undefined') {
            url += 'layers=' + imageryProvider._layers + '&';
        }

        if (typeof parameters.srs === 'undefined') {
            url += 'srs=EPSG:4326&';
        }

        if (typeof parameters.bbox === 'undefined') {
            var nativeExtent = imageryProvider._tilingScheme.tileXYToNativeExtent(x, y, level);
            var bbox = nativeExtent.west + '%2C' + nativeExtent.south + '%2C' + nativeExtent.east + '%2C' + nativeExtent.north;
            url += '&bbox=' + bbox;
        }

        if (typeof parameters.width === 'undefined') {
            url += '&width=256';
        }

        if (typeof parameters.height === 'undefined') {
            url += '&height=256';
        }

        var proxy = imageryProvider._proxy;
        if (typeof proxy !== 'undefined') {
            url = proxy.getURL(url);
        }

        return url;
    }

    /**
     * Gets the URL of the WMS server.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {String} The URL.
     */
    WebMapServiceImageryProvider.prototype.getUrl = function() {
        return this._url;
    };

    /**
     * Gets the names of the WMS layers, separated by commas.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {String} The layer names.
     */
    WebMapServiceImageryProvider.prototype.getLayers = function() {
        return this._layers;
    };

    /**
     * Gets the width of each tile, in pixels.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Number} The width.
     */
    WebMapServiceImageryProvider.prototype.getTileWidth = function() {
        return this._tileWidth;
    };

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Number} The height.
     */
    WebMapServiceImageryProvider.prototype.getTileHeight = function() {
        return this._tileHeight;
    };

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Number} The maximum level.
     */
    WebMapServiceImageryProvider.prototype.getMaximumLevel = function() {
        return this._maximumLevel;
    };

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {TilingScheme} The tiling scheme.
     * @see WebMercatorTilingScheme
     * @see GeographicTilingScheme
     */
    WebMapServiceImageryProvider.prototype.getTilingScheme = function() {
        return this._tilingScheme;
    };

    /**
     * Gets the extent, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Extent} The extent.
     */
    WebMapServiceImageryProvider.prototype.getExtent = function() {
        return this._tilingScheme.getExtent();
    };

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {TileDiscardPolicy} The discard policy.
     *
     * @see DiscardMissingTileImagePolicy
     * @see NeverTileDiscardPolicy
     */
    WebMapServiceImageryProvider.prototype.getTileDiscardPolicy = function() {
        return this._tileDiscardPolicy;
    };

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Boolean} True if the provider is ready to use; otherwise, false.
     */
    WebMapServiceImageryProvider.prototype.isReady = function() {
        return this._ready;
    };

    /**
     * Requests the image for a given tile.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @param {Number} x The tile X coordinate.
     * @param {Number} y The tile Y coordinate.
     * @param {Number} level The tile level.
     *
     * @returns {Promise} A promise for the image that will resolve when the image is available, or
     *          undefined if there are too many active requests to the server, and the request
     *          should be retried later.  The resolved image may be either an
     *          Image or a Canvas DOM object.
     */
    WebMapServiceImageryProvider.prototype.requestImage = function(x, y, level) {
        var url = buildImageUrl(this, x, y, level);
        return ImageryProvider.loadImage(url);
    };

    /**
     * Gets the logo to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Image|Canvas} A canvas or image containing the log to display, or undefined if there is no logo.
     */
    WebMapServiceImageryProvider.prototype.getLogo = function() {
        return this._logo;
    };

    /**
     * The default parameters to include in the WMS URL to obtain images.  The values are as follows:
     *    service=WMS
     *    version=1.1.1
     *    request=GetMap
     *    styles=
     *    format=image/png
     *
     * @memberof WebMapServiceImageryProvider
     */
    WebMapServiceImageryProvider.DefaultParameters = freezeObject({
        service : 'WMS',
        version : '1.1.1',
        request : 'GetMap',
        styles : '',
        format : 'image/jpeg'
    });

    return WebMapServiceImageryProvider;
});<commit_msg>Update documentation of defaults.<commit_after>/*global define*/
define([
        '../Core/combine',
        '../Core/defaultValue',
        '../Core/freezeObject',
        '../Core/writeTextToCanvas',
        '../Core/DeveloperError',
        '../Core/Extent',
        './ImageryProvider',
        './WebMercatorTilingScheme',
        './GeographicTilingScheme'
    ], function(
        combine,
        defaultValue,
        freezeObject,
        writeTextToCanvas,
        DeveloperError,
        Extent,
        ImageryProvider,
        WebMercatorTilingScheme,
        GeographicTilingScheme) {
    "use strict";

    /**
     * Provides tiled imagery hosted by a Web Map Service (WMS) server.
     *
     * @alias WebMapServiceImageryProvider
     * @constructor
     *
     * @param {String} description.url The URL of the WMS service.
     * @param {String} description.layers The layers to include, separated by commas.
     * @param {Object} [description.parameters=WebMapServiceImageryProvider.DefaultParameters] Additional parameters to pass to the WMS server in the GetMap URL.
     * @param {Extent} [description.extent=Extent.MAX_VALUE] The extent of the layer.
     * @param {Number} [description.maximumLevel] The maximum level-of-detail supported by the imagery provider.
     *        If not specified, there is no limit.
     * @param {String} [description.credit] A string crediting the data source, which is displayed on the canvas.
     * @param {Object} [description.proxy] A proxy to use for requests. This object is
     *        expected to have a getURL function which returns the proxied URL, if needed.
     *
     * @exception {DeveloperError} description.url is required.
     *
     * @see ArcGisMapServerImageryProvider
     * @see SingleTileImageryProvider
     * @see BingMapsImageryProvider
     * @see OpenStreetMapImageryProvider
     *
     * @see ArcGIS Server REST API
     * @see Cross-Origin Resource Sharing
     *
     * @example
     * var provider = new WebMapServiceImageryProvider({
     *     url: 'http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer',
     *     layerName: '0',
     *     proxy: new Cesium.DefaultProxy('/proxy/')
     * });
     */
    var WebMapServiceImageryProvider = function WebMapServiceImageryProvider(description) {
        description = defaultValue(description, {});

        if (typeof description.url === 'undefined') {
            throw new DeveloperError('description.url is required.');
        }

        if (typeof description.layers === 'undefined') {
            throw new DeveloperError('description.layers is required.');
        }

        this._url = description.url;
        this._tileDiscardPolicy = description.tileDiscardPolicy;
        this._proxy = description.proxy;
        this._layers = description.layers;

        var parameters = defaultValue(description.parameters, {});
        this._parameters = combine([parameters, WebMapServiceImageryProvider.DefaultParameters], false, true);

        this._tileWidth = 256;
        this._tileHeight = 256;
        this._maximumLevel = description.maximumLevel; // undefined means no limit

        var extent = defaultValue(description.extent, Extent.MAX_VALUE);
        this._tilingScheme = new GeographicTilingScheme({
            extent : extent
        });

        // Create the credit message.
        if (typeof description.credit !== 'undefined') {
            // Create the copyright message.
            this._logo = writeTextToCanvas(description.credit, {
                font : '12px sans-serif'
            });
        }

        this._ready = true;
    };

    function buildImageUrl(imageryProvider, x, y, level) {
        var url = imageryProvider._url;
        var indexOfQuestionMark = url.indexOf('?');
        if (indexOfQuestionMark >= 0 && indexOfQuestionMark < url.length - 1) {
            url += '&';
        } else if (indexOfQuestionMark < 0) {
            url += '?';
        }

        var parameters = imageryProvider._parameters;
        for (var parameter in parameters) {
            if (parameters.hasOwnProperty(parameter)) {
                url += parameter + '=' + parameters[parameter] + '&';
            }
        }

        if (typeof parameters.layers === 'undefined') {
            url += 'layers=' + imageryProvider._layers + '&';
        }

        if (typeof parameters.srs === 'undefined') {
            url += 'srs=EPSG:4326&';
        }

        if (typeof parameters.bbox === 'undefined') {
            var nativeExtent = imageryProvider._tilingScheme.tileXYToNativeExtent(x, y, level);
            var bbox = nativeExtent.west + '%2C' + nativeExtent.south + '%2C' + nativeExtent.east + '%2C' + nativeExtent.north;
            url += '&bbox=' + bbox;
        }

        if (typeof parameters.width === 'undefined') {
            url += '&width=256';
        }

        if (typeof parameters.height === 'undefined') {
            url += '&height=256';
        }

        var proxy = imageryProvider._proxy;
        if (typeof proxy !== 'undefined') {
            url = proxy.getURL(url);
        }

        return url;
    }

    /**
     * Gets the URL of the WMS server.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {String} The URL.
     */
    WebMapServiceImageryProvider.prototype.getUrl = function() {
        return this._url;
    };

    /**
     * Gets the names of the WMS layers, separated by commas.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {String} The layer names.
     */
    WebMapServiceImageryProvider.prototype.getLayers = function() {
        return this._layers;
    };

    /**
     * Gets the width of each tile, in pixels.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Number} The width.
     */
    WebMapServiceImageryProvider.prototype.getTileWidth = function() {
        return this._tileWidth;
    };

    /**
     * Gets the height of each tile, in pixels.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Number} The height.
     */
    WebMapServiceImageryProvider.prototype.getTileHeight = function() {
        return this._tileHeight;
    };

    /**
     * Gets the maximum level-of-detail that can be requested.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Number} The maximum level.
     */
    WebMapServiceImageryProvider.prototype.getMaximumLevel = function() {
        return this._maximumLevel;
    };

    /**
     * Gets the tiling scheme used by this provider.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {TilingScheme} The tiling scheme.
     * @see WebMercatorTilingScheme
     * @see GeographicTilingScheme
     */
    WebMapServiceImageryProvider.prototype.getTilingScheme = function() {
        return this._tilingScheme;
    };

    /**
     * Gets the extent, in radians, of the imagery provided by this instance.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Extent} The extent.
     */
    WebMapServiceImageryProvider.prototype.getExtent = function() {
        return this._tilingScheme.getExtent();
    };

    /**
     * Gets the tile discard policy.  If not undefined, the discard policy is responsible
     * for filtering out "missing" tiles via its shouldDiscardImage function.  If this function
     * returns undefined, no tiles are filtered.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {TileDiscardPolicy} The discard policy.
     *
     * @see DiscardMissingTileImagePolicy
     * @see NeverTileDiscardPolicy
     */
    WebMapServiceImageryProvider.prototype.getTileDiscardPolicy = function() {
        return this._tileDiscardPolicy;
    };

    /**
     * Gets a value indicating whether or not the provider is ready for use.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Boolean} True if the provider is ready to use; otherwise, false.
     */
    WebMapServiceImageryProvider.prototype.isReady = function() {
        return this._ready;
    };

    /**
     * Requests the image for a given tile.  This function should
     * not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @param {Number} x The tile X coordinate.
     * @param {Number} y The tile Y coordinate.
     * @param {Number} level The tile level.
     *
     * @returns {Promise} A promise for the image that will resolve when the image is available, or
     *          undefined if there are too many active requests to the server, and the request
     *          should be retried later.  The resolved image may be either an
     *          Image or a Canvas DOM object.
     */
    WebMapServiceImageryProvider.prototype.requestImage = function(x, y, level) {
        var url = buildImageUrl(this, x, y, level);
        return ImageryProvider.loadImage(url);
    };

    /**
     * Gets the logo to display when this imagery provider is active.  Typically this is used to credit
     * the source of the imagery.  This function should not be called before {@link WebMapServiceImageryProvider#isReady} returns true.
     *
     * @memberof WebMapServiceImageryProvider
     *
     * @returns {Image|Canvas} A canvas or image containing the log to display, or undefined if there is no logo.
     */
    WebMapServiceImageryProvider.prototype.getLogo = function() {
        return this._logo;
    };

    /**
     * The default parameters to include in the WMS URL to obtain images.  The values are as follows:
     *    service=WMS
     *    version=1.1.1
     *    request=GetMap
     *    styles=
     *    format=image/jpeg
     *
     * @memberof WebMapServiceImageryProvider
     */
    WebMapServiceImageryProvider.DefaultParameters = freezeObject({
        service : 'WMS',
        version : '1.1.1',
        request : 'GetMap',
        styles : '',
        format : 'image/jpeg'
    });

    return WebMapServiceImageryProvider;
});<|endoftext|>


<commit_before>import { createElement, hydrate, render, __u as _unmount } from 'preact';

class ContextProvider {
	getChildContext() {
		return this.props.context;
	}
	render(props) {
		return props.children;
	}
}

/**
 * Portal component
 * @param {object | null | undefined} props
 */
function Portal(props) {
	let _this = this;
	let container = props.container;
	let wrap = createElement(
		ContextProvider,
		{ context: _this.context },
		props.vnode
	);

	// When we change container we should clear our old container and
	// indicate a new mount.
	if (_this._container && _this._container !== container) {
		if (_this._temp.parentNode) _this._container.removeChild(_this._temp);
		_unmount(_this._wrap);
		_this._hasMounted = false;
	}

	// When props.vnode is undefined/false/null we are dealing with some kind of
	// conditional vnode. This should not trigger a render.
	if (props.vnode) {
		if (!_this._hasMounted) {
			// Create a placeholder that we can use to insert into.
			_this._temp = document.createTextNode('');
			// Hydrate existing nodes to keep the dom intact, when rendering
			// wrap into the container.
			_this._children = container._children;
			hydrate('', container);
			// Append to the container (this matches React's behavior)
			container.appendChild(_this._temp);
			// At this point we have mounted and should set our container.
			_this._hasMounted = true;
			_this._container = container;
			// Render our wrapping element into temp.
			render(wrap, container, _this._temp);
			container._children = _this._children;
			_this._children = _this._temp._children;
		} else {
			// When we have mounted and the vnode is present it means the
			// props have changed or a parent is triggering a rerender.
			// This implies we only need to call render. But we need to keep
			// the old tree around, otherwise will treat the vnodes as new and
			// will wrongly call `componentDidMount` on them
			container._children = _this._children;
			render(wrap, container);
			_this._children = container._children;
		}
	}
	// When we come from a conditional render, on a mounted
	// portal we should clear the DOM.
	else if (_this._hasMounted) {
		if (_this._temp.parentNode) _this._container.removeChild(_this._temp);
		_unmount(_this._wrap);
	}
	// Set the wrapping element for future unmounting.
	_this._wrap = wrap;

	_this.componentWillUnmount = () => {
		if (_this._temp.parentNode) _this._container.removeChild(_this._temp);
		_unmount(_this._wrap);
	};

	return null;
}

/**
 * Create a `Portal` to continue rendering the vnode tree at a different DOM node
 * @param {import('./internal').VNode} vnode The vnode to render
 * @param {import('./internal').PreactElement} container The DOM node to continue rendering in to.
 */
export function createPortal(vnode, container) {
	return createElement(Portal, { vnode, container });
}
<commit_msg>Add comments<commit_after>import { createElement, hydrate, render, __u as _unmount } from 'preact';

class ContextProvider {
	getChildContext() {
		return this.props.context;
	}
	render(props) {
		return props.children;
	}
}

/**
 * Portal component
 * @param {object | null | undefined} props
 */
function Portal(props) {
	let _this = this;
	let container = props.container;
	let wrap = createElement(
		ContextProvider,
		{ context: _this.context },
		props.vnode
	);

	// When we change container we should clear our old container and
	// indicate a new mount.
	if (_this._container && _this._container !== container) {
		if (_this._temp.parentNode) _this._container.removeChild(_this._temp);
		_unmount(_this._wrap);
		_this._hasMounted = false;
	}

	// When props.vnode is undefined/false/null we are dealing with some kind of
	// conditional vnode. This should not trigger a render.
	if (props.vnode) {
		if (!_this._hasMounted) {
			// Create a placeholder that we can use to insert into.
			_this._temp = document.createTextNode('');
			// temporarily store the current children of the container to restore them after render
			_this._children = container._children;
			// Hydrate existing nodes to keep the dom intact, when rendering
			// wrap into the container.
			hydrate('', container);
			// Append to the container (this matches React's behavior)
			container.appendChild(_this._temp);
			// At this point we have mounted and should set our container.
			_this._hasMounted = true;
			_this._container = container;
			// Render our wrapping element into temp.
			render(wrap, container, _this._temp);
			// restore the previous children of the container
			container._children = _this._children;
			// store the children of the new vnode to be used in subsequent re-renders
			_this._children = _this._temp._children;
		} else {
			// When we have mounted and the vnode is present it means the
			// props have changed or a parent is triggering a rerender.
			// This implies we only need to call render. But we need to keep
			// the old tree around, otherwise will treat the vnodes as new and
			// will wrongly call `componentDidMount` on them
			container._children = _this._children;
			render(wrap, container);
			_this._children = container._children;
		}
	}
	// When we come from a conditional render, on a mounted
	// portal we should clear the DOM.
	else if (_this._hasMounted) {
		if (_this._temp.parentNode) _this._container.removeChild(_this._temp);
		_unmount(_this._wrap);
	}
	// Set the wrapping element for future unmounting.
	_this._wrap = wrap;

	_this.componentWillUnmount = () => {
		if (_this._temp.parentNode) _this._container.removeChild(_this._temp);
		_unmount(_this._wrap);
	};

	return null;
}

/**
 * Create a `Portal` to continue rendering the vnode tree at a different DOM node
 * @param {import('./internal').VNode} vnode The vnode to render
 * @param {import('./internal').PreactElement} container The DOM node to continue rendering in to.
 */
export function createPortal(vnode, container) {
	return createElement(Portal, { vnode, container });
}
<|endoftext|>


<commit_before>exports.command = 'eval';

const Discord = require('discord.js');
const Config = require('../../config.json');

exports.eval = {
    run: function(bot,suffix,msg) {
        if(msg.author.id != Config.ownerID) {
            const embed = new Discord.RichEmbed()
			msg.channel.sendEmbed(embed.setTimestamp().setTitle('Eval').addField('Error:', 'No Permission!').setColor(0xff0000).setFooter('BaconHawkJS'));
        } else{
            const embed = new Discord.RichEmbed()
                .setTitle('Eval')
                .setDescription( eval(suffix,bot))
                .setFooter('BaconHawkJS')
                 .setColor(0xff0000)
                 .setTimestamp()
            msg.channel.sendEmbed(embed);
        }
    }
}

<commit_msg>Delete eval.js<commit_after><|endoftext|>


<commit_before>/*!
 * VisualEditor UserInterface Dialog class.
 *
 * @copyright 2011-2013 VisualEditor Team and others; see AUTHORS.txt
 * @license The MIT License (MIT); see LICENSE.txt
 */

/**
 * UserInterface dialog.
 *
 * @class
 * @abstract
 * @extends ve.ui.Window
 *
 * @constructor
 * @param {ve.ui.Surface} surface
 * @param {Object} [config] Config options
 */
ve.ui.Dialog = function VeUiDialog( surface, config ) {
	// Parent constructor
	ve.ui.Window.call( this, surface, config );

	// Properties
	this.visible = false;

	// Initialization
	this.$.addClass( 've-ui-dialog' );
	this.$.on( 'mousedown', false );
};

/* Inheritance */

ve.inheritClass( ve.ui.Dialog, ve.ui.Window );

/* Methods */

/**
 * Handle close button click events.
 *
 * @method
 */
ve.ui.Dialog.prototype.onCloseButtonClick = function () {
	this.close( 'cancel' );
};

/**
 * Handle apply button click events.
 *
 * @method
 */
ve.ui.Dialog.prototype.onApplyButtonClick = function () {
	this.close( 'apply' );
};

/**
 * Close dialog.
 *
 * This method overrides the parent close method to allow animation, but still provides the same
 * recursion blocking and eventually calls the parent method.
 *
 * @method
 * @param {boolean} action Action that caused the window to be closed
 * @emits close
 */
ve.ui.Dialog.prototype.close = function ( action ) {
	if ( !this.closing ) {
		this.$.addClass( 've-ui-dialog-closing' );
		setTimeout( ve.bind( function () {
			ve.ui.Window.prototype.close.call( this, action );
			this.$.removeClass( 've-ui-dialog-closing' );
		}, this ), 250 );
	}
};

/**
 * Initialize frame contents.
 *
 * @method
 */
ve.ui.Dialog.prototype.initialize = function () {
	// Call parent method
	ve.ui.Window.prototype.initialize.call( this );

	this.applyButton = new ve.ui.ButtonWidget( {
		'$$': this.$$, 'label': ve.msg( 'visualeditor-dialog-action-apply' ), 'flags': ['primary']
	} );
	// Properties
	this.closeButton = new ve.ui.IconButtonWidget( {
		'$$': this.$$, 'title': ve.msg( 'visualeditor-dialog-action-close' ), 'icon': 'close'
	} );

	// Events
	this.closeButton.connect( this, { 'click': 'onCloseButtonClick' } );
	this.applyButton.connect( this, { 'click': 'onApplyButtonClick' } );

	// Initialization
	this.closeButton.$.addClass( 've-ui-window-closeButton' );
	this.applyButton.$.addClass( 've-ui-window-applyButton' );
	this.$head.append( this.closeButton.$ );
	this.$foot.append( this.applyButton.$ );
};

/* Initialization */

ve.ui.Dialog.static.addLocalStylesheets( [ 've.ui.Dialog.css' ] );
<commit_msg>Prevent scrolling in top-level window while dialog is open<commit_after>/*!
 * VisualEditor UserInterface Dialog class.
 *
 * @copyright 2011-2013 VisualEditor Team and others; see AUTHORS.txt
 * @license The MIT License (MIT); see LICENSE.txt
 */

/**
 * UserInterface dialog.
 *
 * @class
 * @abstract
 * @extends ve.ui.Window
 *
 * @constructor
 * @param {ve.ui.Surface} surface
 * @param {Object} [config] Config options
 */
ve.ui.Dialog = function VeUiDialog( surface, config ) {
	// Parent constructor
	ve.ui.Window.call( this, surface, config );

	// Properties
	this.visible = false;
	this.onWindowMouseWheelHandler = ve.bind( this.onWindowMouseWheel, this );
	this.onDocumentKeyDownHandler = ve.bind( this.onDocumentKeyDown, this );

	// Initialization
	this.$.addClass( 've-ui-dialog' );
	this.$.on( 'mousedown', false );
};

/* Inheritance */

ve.inheritClass( ve.ui.Dialog, ve.ui.Window );

/* Methods */

/**
 * Handle close button click events.
 *
 * @method
 */
ve.ui.Dialog.prototype.onCloseButtonClick = function () {
	this.close( 'cancel' );
};

/**
 * Handle apply button click events.
 *
 * @method
 */
ve.ui.Dialog.prototype.onApplyButtonClick = function () {
	this.close( 'apply' );
};

/**
 * Handle window mouse wheel events.
 *
 * @method
 * @param {jQuery.Event} e Mouse wheel event
 */
ve.ui.Dialog.prototype.onWindowMouseWheel = function () {
	return false;
};

/**
 * Handle document key down events.
 *
 * @method
 * @param {jQuery.Event} e Key down event
 */
ve.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
	switch ( e.which ) {
		case ve.Keys.PAGEUP:
		case ve.Keys.PAGEDOWN:
		case ve.Keys.END:
		case ve.Keys.HOME:
		case ve.Keys.LEFT:
		case ve.Keys.UP:
		case ve.Keys.RIGHT:
		case ve.Keys.DOWN:
			// Prevent any key events that might cause scrolling
			return false;
	}
};

/**
 * Open window.
 *
 * Wraps the parent open method. Disables native top-level window scrolling behavior.
 *
 * @method
 * @emits setup
 * @emits open
 */
ve.ui.Dialog.prototype.open = function () {
	ve.ui.Window.prototype.open.call( this );
	// Prevent scrolling in top-level window
	$( window ).on( 'mousewheel', this.onWindowMouseWheelHandler );
	$( document ).on( 'keydown', this.onDocumentKeyDownHandler );
};

/**
 * Close dialog.
 *
 * Wraps the parent close method. Allows animation by delaying parent close call, while still
 * providing the same recursion blocking. Restores native top-level window scrolling behavior.
 *
 * @method
 * @param {boolean} action Action that caused the window to be closed
 * @emits close
 */
ve.ui.Dialog.prototype.close = function ( action ) {
	if ( !this.closing ) {
		this.$.addClass( 've-ui-dialog-closing' );
		setTimeout( ve.bind( function () {
			ve.ui.Window.prototype.close.call( this, action );
			this.$.removeClass( 've-ui-dialog-closing' );
		}, this ), 250 );
		// Allow scrolling in top-level window
		$( window ).off( 'mousewheel', this.onWindowMouseWheelHandler );
		$( document ).off( 'keydown', this.onDocumentKeyDownHandler );
	}
};

/**
 * Initialize frame contents.
 *
 * @method
 */
ve.ui.Dialog.prototype.initialize = function () {
	// Call parent method
	ve.ui.Window.prototype.initialize.call( this );

	this.applyButton = new ve.ui.ButtonWidget( {
		'$$': this.$$, 'label': ve.msg( 'visualeditor-dialog-action-apply' ), 'flags': ['primary']
	} );
	// Properties
	this.closeButton = new ve.ui.IconButtonWidget( {
		'$$': this.$$, 'title': ve.msg( 'visualeditor-dialog-action-close' ), 'icon': 'close'
	} );

	// Events
	this.closeButton.connect( this, { 'click': 'onCloseButtonClick' } );
	this.applyButton.connect( this, { 'click': 'onApplyButtonClick' } );

	// Initialization
	this.closeButton.$.addClass( 've-ui-window-closeButton' );
	this.applyButton.$.addClass( 've-ui-window-applyButton' );
	this.$head.append( this.closeButton.$ );
	this.$foot.append( this.applyButton.$ );
};

/* Initialization */

ve.ui.Dialog.static.addLocalStylesheets( [ 've.ui.Dialog.css' ] );
<|endoftext|>


<commit_before>/**
 * main.js
 */
+function ( global ) {

	'use strict';

    var MODULE_MAIN = 'z';
    var PATH_LIB = MODULE_MAIN + '/libs/';

	requirejs.config({
	    baseUrl : 'modules',
	    paths : {
            'sprintf': [
                '//cdn.bootcss.com/sprintf/1.0.3/sprintf.min',
                PATH_LIB + 'sprintf/1.0.3/sprintf.min'
            ],
            'require/css': [
                '//cdn.bootcss.com/require-css/0.1.8/css.min',
                PATH_LIB + 'require-css/0.1.8/css.min'
            ],
            'require/json': [
                '//cdn.bootcss.com/requirejs-plugins/1.0.3/json.min',
                PATH_LIB + 'requirejs-plugins/1.0.3/json.min'
            ],
	    	'less'			  : '//cdn.bootcss.com/less.js/2.7.1/less.min',
	        'bootstrap'       : '//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min',
	        'angular'         : '//cdn.bootcss.com/angular.js/1.5.6/angular.min',
	        'angular-route'   : '//cdn.bootcss.com/angular.js/1.5.6/angular-route.min',
            'angular-ui-router' : '//cdn.bootcss.com/angular-ui-router/1.0.0-alpha0/angular-ui-router.min',
            'routes'            : MODULE_MAIN + '/javascripts/routes',
            'jquery': [
                '//cdn.bootcss.com/jquery/1.11.3/jquery.min',
                PATH_LIB + 'jquery/jquery-1.11.3'
            ],
            'jquery.twbsPagination': [
                '//cdn.bootcss.com/twbs-pagination/1.3.1/jquery.twbsPagination.min',
                PATH_LIB + 'jquery/jquery.twbsPagination'
            ],
            'async': [
                '//cdn.bootcss.com/async/2.0.1/async.min',
                PATH_LIB + 'async/2.0.1/async.min'
            ],
            'echarts2': [
                '//cdn.bootcss.com/echarts/2.2.7/echarts-all',
                PATH_LIB + 'echarts2/echarts-all'
            ],
            'echarts3': [
                '//cdn.bootcss.com/echarts/3.2.2/echarts.min',
                PATH_LIB + 'echarts/echarts.min'
            ],
            'angularAMD': [
                '//cdn.jsdelivr.net/angular.amd/0.2/angularAMD.min',
                PATH_LIB + 'angularjs/angularAMD'
            ],
            'angular': [
                '//cdn.bootcss.com/angular.js/1.5.7/angular',
                PATH_LIB + 'angularjs/angular'
            ],
            'angular-messages': [
                '//cdn.bootcss.com/angular-messages/1.5.7/angular-messages',
                PATH_LIB + 'angularjs/angular-messages'
            ],
            'angular-ui-router': [
                '//cdn.bootcss.com/angular-ui-router/0.2.18/angular-ui-router',
                PATH_LIB + 'ui-router/angular-ui-router'
            ],
            'bootstrap': [
                '//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap',
                PATH_LIB + 'bootstrap/js/bootstrap'
            ],
            'bootstrapTable': [
                // '//cdn.bootcss.com/bootstrap-table/1.10.1/bootstrap-table',
                PATH_LIB + 'bootstrap-table/bootstrap-table'
            ],
            'app': MODULE_MAIN + '/javascripts/app',
            'font-awesome':[
                '//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min'

            ]
	    },
	    shim : {
	        bootstrap : {
	            deps : ['jquery'],
	            exports :'bootstrap'
	        },
	        angular: {
              exports: 'angular'
          },
          // 'angular-route': {
          //     deps: ['angular'],
          //     exports: 'angular-route'
          // },
          'angular-ui-router': {
              deps: ['angular'],
              exports: 'angular-ui-router'
          }
	    },
        map: {
            '*': {
                css: 'require/css',
                'less': PATH_LIB + 'require-less/less',
                echarts : 'echarts3'
            }
        },
        deps: [
            'css!font-awesome',
            'app'
        ],
        urlArgs: 'bust=1'// + (new Date()).getTime()
	});
}( window );
<commit_msg>auto commit by zhaotinghai<commit_after>/**
 * z-frame main.js
 * create by zhaotinghai@10161017
 */
+function ( global ) {

	'use strict';

    var MODULE_MAIN = 'z';
    var PATH_LIB = MODULE_MAIN + '/libs/';

	requirejs.config({
	    baseUrl : 'modules',
	    paths : {
            'sprintf': [
                '//cdn.bootcss.com/sprintf/1.0.3/sprintf.min',
                PATH_LIB + 'sprintf/1.0.3/sprintf.min'
            ],
            'require/css': [
                '//cdn.bootcss.com/require-css/0.1.8/css.min',
                PATH_LIB + 'require-css/0.1.8/css.min'
            ],
            'require/json': [
                '//cdn.bootcss.com/requirejs-plugins/1.0.3/json.min',
                PATH_LIB + 'requirejs-plugins/1.0.3/json.min'
            ],
	    	'less'			  : '//cdn.bootcss.com/less.js/2.7.1/less.min',
	        'bootstrap'       : '//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min',
	        'angular'         : '//cdn.bootcss.com/angular.js/1.5.6/angular.min',
	        'angular-route'   : '//cdn.bootcss.com/angular.js/1.5.6/angular-route.min',
            'angular-ui-router' : '//cdn.bootcss.com/angular-ui-router/1.0.0-alpha0/angular-ui-router.min',
            'routes'            : MODULE_MAIN + '/javascripts/routes',
            'jquery': [
                '//cdn.bootcss.com/jquery/1.11.3/jquery.min',
                PATH_LIB + 'jquery/jquery-1.11.3'
            ],
            'jquery.twbsPagination': [
                '//cdn.bootcss.com/twbs-pagination/1.3.1/jquery.twbsPagination.min',
                PATH_LIB + 'jquery/jquery.twbsPagination'
            ],
            'async': [
                '//cdn.bootcss.com/async/2.0.1/async.min',
                PATH_LIB + 'async/2.0.1/async.min'
            ],
            'echarts2': [
                '//cdn.bootcss.com/echarts/2.2.7/echarts-all',
                PATH_LIB + 'echarts2/echarts-all'
            ],
            'echarts3': [
                '//cdn.bootcss.com/echarts/3.2.2/echarts.min',
                PATH_LIB + 'echarts/echarts.min'
            ],
            'angularAMD': [
                '//cdn.jsdelivr.net/angular.amd/0.2/angularAMD.min',
                PATH_LIB + 'angularjs/angularAMD'
            ],
            'angular': [
                '//cdn.bootcss.com/angular.js/1.5.7/angular',
                PATH_LIB + 'angularjs/angular'
            ],
            'angular-messages': [
                '//cdn.bootcss.com/angular-messages/1.5.7/angular-messages',
                PATH_LIB + 'angularjs/angular-messages'
            ],
            'angular-ui-router': [
                '//cdn.bootcss.com/angular-ui-router/0.2.18/angular-ui-router',
                PATH_LIB + 'ui-router/angular-ui-router'
            ],
            'bootstrap': [
                '//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap',
                PATH_LIB + 'bootstrap/js/bootstrap'
            ],
            'bootstrapTable': [
                // '//cdn.bootcss.com/bootstrap-table/1.10.1/bootstrap-table',
                PATH_LIB + 'bootstrap-table/bootstrap-table'
            ],
            'app': MODULE_MAIN + '/javascripts/app',
            'font-awesome':[
                '//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min'

            ]
	    },
	    shim : {
	        bootstrap : {
	            deps : ['jquery'],
	            exports :'bootstrap'
	        },
	        angular: {
              exports: 'angular'
          },
          // 'angular-route': {
          //     deps: ['angular'],
          //     exports: 'angular-route'
          // },
          'angular-ui-router': {
              deps: ['angular'],
              exports: 'angular-ui-router'
          }
	    },
        map: {
            '*': {
                css: 'require/css',
                'less': PATH_LIB + 'require-less/less',
                echarts : 'echarts3'
            }
        },
        deps: [
            'css!font-awesome',
            'app'
        ],
        urlArgs: 'bust=1'// + (new Date()).getTime()
	});
}( window );
<|endoftext|>


<commit_before>var path = require("path");
var fs = require("fs");
var assert = require("assert");
var sinon = require("sinon");

var Environment = {
    _stub: null,

    init: function (config) {
        /*
         * config object supports:
         *      user: myuw user object, template in user_state.html
         *      render_id: rendered object container id
         *      scripts: required javascript modules to include
         *      templates: template files used for rendering
         */
        if (!config) {
            config = {};
        }

        // create test document
        var jsdom = require('jsdom');
        const { JSDOM } = jsdom;
        var window = JSDOM().window;

        // pull in supporting tools
        var $ = require('jquery')(window);
        global.$ = $;
        global.window = window;
        global.document = window.prototype.document;
        global.assert = require("assert");
        global.moment = require("moment");
        global.Handlebars = require("../../vendor/js/handlebars-v4.0.5.js");
        var MomentTZ = require("moment-timezone");
        var HandlebarsHelpers = require("../handlebars-helpers.js")

        // set up client environment
        window.user = Environment._get_user(config);

        // default test term
        window.term = {};
        window.term.year = 2013;
        window.term.quarter = 'spring';
        window.term.first_day_quarter = 'Monday, April 1, 2013';
        window.term.last_day_instruction = 'Friday, June 7, 2013';

        if (config.hasOwnProperty('render_id')) {
            $('body').append($('<div/>', { 'id': config.render_id }));
        }

        // stub onload init routines
        window.RenderPage = function () {};
        global.Profile = { add_events: function () {} };
        global.Modal = { add_events: function () {} };
        global.LogUtils = {
            init_logging: function () {},
            cardLoaded: function(name, el) {
                $(window).trigger("myuw:card_load", [ name, el ])
            }
        };

        // pull in scripts
        Environment._load_script('myuw/static/js/myuw_m.js');
        Environment._load_script('myuw/static/js/ws_data.js');
        if (config.hasOwnProperty('scripts')) {
            $.each(config.scripts, function () {
                Environment._load_script(this.toString());
            });
        }

        // pull in templates
        if (config.hasOwnProperty('templates')) {
            $.each(config.templates, function () {
                Environment._load_template(this.toString());
            });
        }
    },
    _get_user: function (config) {
        var user;
        if (config.hasOwnProperty('user')) {
            user = config.user;
        } else {
            user = {
                bothell: false,
                bothell_affil: false,
                email_forward_icon: "",
                email_forward_title: "",
                email_forward_url: "",
                employee: false,
                faculty: false,
                fyp: false,
                grad: false,
                netid: "bill",
                pce: false,
                seattle: true,
                seattle_affil: false,
                stud_employee: false,
                student: true,
                tacoma: false,
                tacoma_affil: false,
                undergrad: false
            };
        }

        return user;
    },
    _abs_path: function (relative_path) {
        return path.join(__dirname, '../../../../', relative_path);
    },
    _json_from_file: function (json_data_file) {
        var json_dir = path.join('myuw/static/js/test/ajax', json_data_file);
        var json_file = Environment._abs_path(json_dir);
        return JSON.parse(fs.readFileSync(json_file));
    },
    ajax_stub: function (json_config) {
        if ($.type(json_config) === 'string') {
            var json_data = Environment._json_from_file(json_config)
            Environment._stub = sinon.stub($, 'ajax');
            Environment._stub.yieldsTo('success', json_data);
        } else {
            Environment._stub = sinon.stub($, 'ajax')
                .callsFake(function (conf) {
                    if (conf.url in json_config) {
                        var json_data = Environment._json_from_file(json_config[conf.url]);
                        conf.success.apply(null, [json_data]);
                    } else {
                        conf.error.apply(null, [{status: 404}, 404, "unknown mock url: " + conf.url]);
                    }
                });
        }
    },
    ajax_stub_restore: function () {
        if (Environment._stub) {
            Environment._stub.restore();
        }
    },
    _load_script: function (script) {
        var r = require(Environment._abs_path(script));
        $.each(r, function(k, v) { global[k] = v;});
    },
    _read_template: function (template_file) {
        var template_path = Environment._abs_path(template_file);
        var raw = fs.readFileSync(template_path).toString();
        var template = raw.replace(/{\%[ ]+load[ ]+templatetag_handlebars[ ]+\%}/, '')
            .replace(/{\%[ ]*tplhandlebars[ ]+["]?([^ \%]+)["]?[ ]*\%}/,
                     '<script id="$1" type="text/x-handlebars-template">')
            .replace(/{\%[ ]*endtplhandlebars[ ]*\%}/,
                     '</script>')
            .replace(/{\%[ ]*(end)?verbatim[ ]*\%}/g, '');

        while (true) {
            // pull in server-side includes
            var m = template.match(/{\%[ ]*include[ ]+["]?([^ \%"]+)["]?[ ]*\%}/);
            if (m) {
                var text = Environment._read_template('myuw/templates/' + m[1]);
                template = template.replace(m[0], text);
            } else {
                break;
            }
        }

        return template;
    },
    _load_template: function(template_file) {
        var template = Environment._read_template(template_file);
        $('body').append(template);
    }
};

describe("Global Test Environment", function () {
    it("loads nested server-side templates", function (){
        var f = 'myuw/templates/handlebars/card/instructor_schedule/course_resource_panel.html';
        var t = Environment._read_template(f);

        assert(t.indexOf('instructor_course_resource_panel') > 0, 'template id');
        assert(t.indexOf('endtplhandlebars') < 0, 'end handlebars block stripped');
        assert(t.indexOf('verbatim') < 0, 'verbatim stripped');
        assert(t.indexOf('endverbatim') < 0, 'endverbatim stripped');
        assert(t.indexOf('show_course_textbook') > 0, 'first inclusion');
        assert(t.indexOf('list_admin_url') > 0, 'second inclusion');
        assert.equal(true, true);
    });
});

/* node.js exports */
if (typeof exports == "undefined") {
    var exports = {};
}
exports.Environment = Environment;
<commit_msg>fix jsdom constructor error<commit_after>var path = require("path");
var fs = require("fs");
var assert = require("assert");
var sinon = require("sinon");

var Environment = {
    _stub: null,

    init: function (config) {
        /*
         * config object supports:
         *      user: myuw user object, template in user_state.html
         *      render_id: rendered object container id
         *      scripts: required javascript modules to include
         *      templates: template files used for rendering
         */
        if (!config) {
            config = {};
        }

        // create test document
        var jsdom = require('jsdom');
        const { JSDOM } = jsdom;
        var window = new JSDOM('');

        // pull in supporting tools
        var $ = require('jquery')(window);
        global.$ = $;
        global.window = window;
        global.document = window.prototype.document;
        global.assert = require("assert");
        global.moment = require("moment");
        global.Handlebars = require("../../vendor/js/handlebars-v4.0.5.js");
        var MomentTZ = require("moment-timezone");
        var HandlebarsHelpers = require("../handlebars-helpers.js")

        // set up client environment
        window.user = Environment._get_user(config);

        // default test term
        window.term = {};
        window.term.year = 2013;
        window.term.quarter = 'spring';
        window.term.first_day_quarter = 'Monday, April 1, 2013';
        window.term.last_day_instruction = 'Friday, June 7, 2013';

        if (config.hasOwnProperty('render_id')) {
            $('body').append($('<div/>', { 'id': config.render_id }));
        }

        // stub onload init routines
        window.RenderPage = function () {};
        global.Profile = { add_events: function () {} };
        global.Modal = { add_events: function () {} };
        global.LogUtils = {
            init_logging: function () {},
            cardLoaded: function(name, el) {
                $(window).trigger("myuw:card_load", [ name, el ])
            }
        };

        // pull in scripts
        Environment._load_script('myuw/static/js/myuw_m.js');
        Environment._load_script('myuw/static/js/ws_data.js');
        if (config.hasOwnProperty('scripts')) {
            $.each(config.scripts, function () {
                Environment._load_script(this.toString());
            });
        }

        // pull in templates
        if (config.hasOwnProperty('templates')) {
            $.each(config.templates, function () {
                Environment._load_template(this.toString());
            });
        }
    },
    _get_user: function (config) {
        var user;
        if (config.hasOwnProperty('user')) {
            user = config.user;
        } else {
            user = {
                bothell: false,
                bothell_affil: false,
                email_forward_icon: "",
                email_forward_title: "",
                email_forward_url: "",
                employee: false,
                faculty: false,
                fyp: false,
                grad: false,
                netid: "bill",
                pce: false,
                seattle: true,
                seattle_affil: false,
                stud_employee: false,
                student: true,
                tacoma: false,
                tacoma_affil: false,
                undergrad: false
            };
        }

        return user;
    },
    _abs_path: function (relative_path) {
        return path.join(__dirname, '../../../../', relative_path);
    },
    _json_from_file: function (json_data_file) {
        var json_dir = path.join('myuw/static/js/test/ajax', json_data_file);
        var json_file = Environment._abs_path(json_dir);
        return JSON.parse(fs.readFileSync(json_file));
    },
    ajax_stub: function (json_config) {
        if ($.type(json_config) === 'string') {
            var json_data = Environment._json_from_file(json_config)
            Environment._stub = sinon.stub($, 'ajax');
            Environment._stub.yieldsTo('success', json_data);
        } else {
            Environment._stub = sinon.stub($, 'ajax')
                .callsFake(function (conf) {
                    if (conf.url in json_config) {
                        var json_data = Environment._json_from_file(json_config[conf.url]);
                        conf.success.apply(null, [json_data]);
                    } else {
                        conf.error.apply(null, [{status: 404}, 404, "unknown mock url: " + conf.url]);
                    }
                });
        }
    },
    ajax_stub_restore: function () {
        if (Environment._stub) {
            Environment._stub.restore();
        }
    },
    _load_script: function (script) {
        var r = require(Environment._abs_path(script));
        $.each(r, function(k, v) { global[k] = v;});
    },
    _read_template: function (template_file) {
        var template_path = Environment._abs_path(template_file);
        var raw = fs.readFileSync(template_path).toString();
        var template = raw.replace(/{\%[ ]+load[ ]+templatetag_handlebars[ ]+\%}/, '')
            .replace(/{\%[ ]*tplhandlebars[ ]+["]?([^ \%]+)["]?[ ]*\%}/,
                     '<script id="$1" type="text/x-handlebars-template">')
            .replace(/{\%[ ]*endtplhandlebars[ ]*\%}/,
                     '</script>')
            .replace(/{\%[ ]*(end)?verbatim[ ]*\%}/g, '');

        while (true) {
            // pull in server-side includes
            var m = template.match(/{\%[ ]*include[ ]+["]?([^ \%"]+)["]?[ ]*\%}/);
            if (m) {
                var text = Environment._read_template('myuw/templates/' + m[1]);
                template = template.replace(m[0], text);
            } else {
                break;
            }
        }

        return template;
    },
    _load_template: function(template_file) {
        var template = Environment._read_template(template_file);
        $('body').append(template);
    }
};

describe("Global Test Environment", function () {
    it("loads nested server-side templates", function (){
        var f = 'myuw/templates/handlebars/card/instructor_schedule/course_resource_panel.html';
        var t = Environment._read_template(f);

        assert(t.indexOf('instructor_course_resource_panel') > 0, 'template id');
        assert(t.indexOf('endtplhandlebars') < 0, 'end handlebars block stripped');
        assert(t.indexOf('verbatim') < 0, 'verbatim stripped');
        assert(t.indexOf('endverbatim') < 0, 'endverbatim stripped');
        assert(t.indexOf('show_course_textbook') > 0, 'first inclusion');
        assert(t.indexOf('list_admin_url') > 0, 'second inclusion');
        assert.equal(true, true);
    });
});

/* node.js exports */
if (typeof exports == "undefined") {
    var exports = {};
}
exports.Environment = Environment;
<|endoftext|>