<commit_before>/**
 * Renders a trend chart in the specified div using ECharts.
 *
 * @param {String} chartDivId - the ID of the div where the chart should be shown in
 * @param {JSON} chartModel - the line chart model
 */
function renderTrendChart(chartDivId, chartModel) {
    var chart = echarts.init(document.getElementById(chartDivId));

    var builds = [];
    var critical = [];
    var high = [];
    var medium = [];
    var low = [];
    var info = [];
    var unassigned = [];
    for (var i=0; i<chartModel.length; i++) {
        builds.unshift("#" + chartModel[i].buildNumber);
        critical.unshift(chartModel[i].critical);
        high.unshift(chartModel[i].high);
        medium.unshift(chartModel[i].medium);
        low.unshift(chartModel[i].low);
        info.unshift(chartModel[i].info);
        unassigned.unshift(chartModel[i].unassigned);
    }

    var options = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['Critical', 'High', 'Medium', 'Low'],
            orient: 'horizontal',
            x: 'center',
            y: 'bottom'
        },
        grid: {
            left: '20',
            right: '10',
            bottom: '20',
            top: '10',
            containLabel: true
        },
        xAxis : [
            {
                type : 'category',
                boundaryGap : false,
                data : builds
            }
        ],
        yAxis : [
            {
                name: 'vulnerabilities',
                nameLocation: 'center',
                boundaryGap : false,
                nameGap: '30',
                nameRotate: '90',
                type: 'value'
            }
        ],
        color: ['#dc0000', '#fd8c00', '#fdc500', '#4cae4c'],
        series : [
            {
                name: 'Critical',
                type: 'line',
                data: critical
            },
            {
                name: 'High',
                type: 'line',
                data: high
            },
            {
                name: 'Medium',
                type: 'line',
                data: medium
            },
            {
                name: 'Low',
                type: 'line',
                data: low
            }
        ]
    };

    chart.setOption(options);
    chart.resize();
    window.onresize = function() {
        chart.resize();
    };
}

/**
 * Renders a ecosystem chart in the specified div using ECharts.
 *
 * @param {String} chartDivId - the ID of the div where the chart should be shown in
 * @param {JSON} chartModel - the line chart model
 */
function renderEcosystemChart(chartDivId, chartModel) {
    var chart = echarts.init(document.getElementById(chartDivId));
    var options = {
        tooltip: {
            trigger: 'item',
            formatter: "{a}
{b}: {c} ({d}%)"
        },
        legend: {
            y: '250px',
            data:['npm','maven']
        },
        series: [
            {
                name:'Vulnerabilities',
                type:'pie',
                radius: ['100%', '0%'],
                avoidLabelOverlap: true,
                label: {
                    normal: {
                        show: false,
                    },
                    emphasis: {
                        show: false,
                    }
                },

                data:[
                    {value:30, name:'npm'},
                    {value:50, name:'maven'},
                ]
            }
        ]
    };

    chart.setOption(options);
    chart.resize();
    window.onresize = function() {
        chart.resize();
    };
}

/**
 * Generates a responsive progress bar consisting of all severities.
 *
 * @param targetId the ID of the element to insert the bar in
 * @param label the label to give the bar
 * @param critical the number of critical severity vulnerabilities
 * @param high the number of high severity vulnerabilities
 * @param medium the number of medium severity vulnerabilities
 * @param low the number of low severity vulnerabilities
 * @param info the number of info-level issues
 * @param unassigned the number of issues with unassigned severity
 */
function generateSeverityDistributionBar(targetId, label, critical, high, medium, low, info, unassigned) {
    var percentCritical = (critical > 0 ? (critical/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentHigh = (high > 0 ? (high/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentMedium = (medium > 0 ? (medium/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentLow = (low > 0 ? (low/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentInfo = (info > 0 ? (info/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentUnassigned = (unassigned > 0 ? (unassigned/(critical+high+medium+low+info+unassigned))*100 : 0);
    var block = '' + label + '
';
    if (critical === 0 && high === 0 && medium === 0 && low === 0 && info === 0 && unassigned === 0) {
        block += '
No Vulnerabilities Found
';
    } else {
        block += '
' + critical + '
';
        block += '
' + high + '
';
        block += '
' + medium + '
';
        block += '
' + low + '
';
        block += '
' + info + '
';
        block += '
' + unassigned + '
';
    }
    block += '
';
    document.getElementById(targetId).innerHTML = block;
    Tipped.create('.odc-tooltip');
}
<commit_msg>Added unassigned severity<commit_after>/**
 * Renders a trend chart in the specified div using ECharts.
 *
 * @param {String} chartDivId - the ID of the div where the chart should be shown in
 * @param {JSON} chartModel - the line chart model
 */
function renderTrendChart(chartDivId, chartModel) {
    var chart = echarts.init(document.getElementById(chartDivId));

    var builds = [];
    var critical = [];
    var high = [];
    var medium = [];
    var low = [];
    var info = [];
    var unassigned = [];
    for (var i=0; i<chartModel.length; i++) {
        builds.unshift("#" + chartModel[i].buildNumber);
        critical.unshift(chartModel[i].critical);
        high.unshift(chartModel[i].high);
        medium.unshift(chartModel[i].medium);
        low.unshift(chartModel[i].low);
        info.unshift(chartModel[i].info);
        unassigned.unshift(chartModel[i].unassigned);
    }

    var options = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['Critical', 'High', 'Medium', 'Low', 'Unassigned'],
            orient: 'horizontal',
            x: 'center',
            y: 'bottom'
        },
        grid: {
            left: '20',
            right: '10',
            bottom: '20',
            top: '10',
            containLabel: true
        },
        xAxis : [
            {
                type : 'category',
                boundaryGap : false,
                data : builds
            }
        ],
        yAxis : [
            {
                name: 'vulnerabilities',
                nameLocation: 'center',
                boundaryGap : false,
                nameGap: '30',
                nameRotate: '90',
                type: 'value'
            }
        ],
        color: ['#dc0000', '#fd8c00', '#fdc500', '#4cae4c', '#c0c0c0'],
        series : [
            {
                name: 'Critical',
                type: 'line',
                data: critical
            },
            {
                name: 'High',
                type: 'line',
                data: high
            },
            {
                name: 'Medium',
                type: 'line',
                data: medium
            },
            {
                name: 'Low',
                type: 'line',
                data: low
            },
            {
                name: 'Unassigned',
                type: 'line',
                data: unassigned
            }
        ]
    };

    chart.setOption(options);
    chart.resize();
    window.onresize = function() {
        chart.resize();
    };
}

/**
 * Renders a ecosystem chart in the specified div using ECharts.
 *
 * @param {String} chartDivId - the ID of the div where the chart should be shown in
 * @param {JSON} chartModel - the line chart model
 */
function renderEcosystemChart(chartDivId, chartModel) {
    var chart = echarts.init(document.getElementById(chartDivId));
    var options = {
        tooltip: {
            trigger: 'item',
            formatter: "{a}
{b}: {c} ({d}%)"
        },
        legend: {
            y: '250px',
            data:['npm','maven']
        },
        series: [
            {
                name:'Vulnerabilities',
                type:'pie',
                radius: ['100%', '0%'],
                avoidLabelOverlap: true,
                label: {
                    normal: {
                        show: false,
                    },
                    emphasis: {
                        show: false,
                    }
                },

                data:[
                    {value:30, name:'npm'},
                    {value:50, name:'maven'},
                ]
            }
        ]
    };

    chart.setOption(options);
    chart.resize();
    window.onresize = function() {
        chart.resize();
    };
}

/**
 * Generates a responsive progress bar consisting of all severities.
 *
 * @param targetId the ID of the element to insert the bar in
 * @param label the label to give the bar
 * @param critical the number of critical severity vulnerabilities
 * @param high the number of high severity vulnerabilities
 * @param medium the number of medium severity vulnerabilities
 * @param low the number of low severity vulnerabilities
 * @param info the number of info-level issues
 * @param unassigned the number of issues with unassigned severity
 */
function generateSeverityDistributionBar(targetId, label, critical, high, medium, low, info, unassigned) {
    var percentCritical = (critical > 0 ? (critical/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentHigh = (high > 0 ? (high/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentMedium = (medium > 0 ? (medium/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentLow = (low > 0 ? (low/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentInfo = (info > 0 ? (info/(critical+high+medium+low+info+unassigned))*100 : 0);
    var percentUnassigned = (unassigned > 0 ? (unassigned/(critical+high+medium+low+info+unassigned))*100 : 0);
    var block = '' + label + '
';
    if (critical === 0 && high === 0 && medium === 0 && low === 0 && info === 0 && unassigned === 0) {
        block += '
No Vulnerabilities Found
';
    } else {
        block += '
' + critical + '
';
        block += '
' + high + '
';
        block += '
' + medium + '
';
        block += '
' + low + '
';
        block += '
' + info + '
';
        block += '
' + unassigned + '
';
    }
    block += '
';
    document.getElementById(targetId).innerHTML = block;
    Tipped.create('.odc-tooltip');
}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2008-2011  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// Kernel
//============================================================================

/**
 * @module IPython
 * @namespace IPython
 * @submodule Kernel
 */

var IPython = (function (IPython) {

    var utils = IPython.utils;

    // Initialization and connection.
    /**
     * A Kernel Class to communicate with the Python kernel
     * @Class Kernel
     */
    var Kernel = function (base_url) {
        this.kernel_id = null;
        this.shell_channel = null;
        this.iopub_channel = null;
        this.base_url = base_url;
        this.running = false;
        this.username = "username";
        this.session_id = utils.uuid();
        this._msg_callbacks = {};

        if (typeof(WebSocket) !== 'undefined') {
            this.WebSocket = WebSocket;
        } else if (typeof(MozWebSocket) !== 'undefined') {
            this.WebSocket = MozWebSocket;
        } else {
            alert('Your browser does not have WebSocket support, please try Chrome, Safari or Firefox ≥ 6. Firefox 4 and 5 are also supported by you have to enable WebSockets in about:config.');
        };
    };

    Kernel.prototype._get_msg = function (msg_type, content) {
        var msg = {
            header : {
                msg_id : utils.uuid(),
                username : this.username,
                session : this.session_id,
                msg_type : msg_type
            },
            metadata : {},
            content : content,
            parent_header : {}
        };
        return msg;
    };

    /**
     * Start the Python kernel
     * @method start
     */
    Kernel.prototype.start = function (notebook_id) {
        var that = this;
        if (!this.running) {
            var qs = $.param({notebook:notebook_id});
            var url = this.base_url + '?' + qs;
            $.post(url,
                $.proxy(that._kernel_started,that),
                'json'
            );
        };
    };

    /**
     * Restart the python kernel.
     *
     * Emit a 'status_restarting.Kernel' event with
     * the current object as parameter
     *
     * @method restart
     */
    Kernel.prototype.restart = function () {
        $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
        var that = this;
        if (this.running) {
            this.stop_channels();
            var url = this.kernel_url + "/restart";
            $.post(url,
                $.proxy(that._kernel_started, that),
                'json'
            );
        };
    };

    Kernel.prototype._kernel_started = function (json) {
        console.log("Kernel started: ", json.kernel_id);
        this.running = true;
        this.kernel_id = json.kernel_id;
        this.ws_url = json.ws_url;
        this.kernel_url = this.base_url + "/" + this.kernel_id;
        this.start_channels();
        $([IPython.events]).trigger('status_started.Kernel', {kernel: this});
    };

    Kernel.prototype._websocket_closed = function(ws_url, early) {
        this.stop_channels();
        $([IPython.events]).trigger('websocket_closed.Kernel',
            {ws_url: ws_url, kernel: this, early: early}
        );
    };

    /**
     * Start the `shell`and `iopub` channels.
     * Will stop and restart them if they already exist.
     *
     * @method start_channels
     */
    Kernel.prototype.start_channels = function () {
        var that = this;
        this.stop_channels();
        var ws_url = this.ws_url + this.kernel_url;
        console.log("Starting WebSockets:", ws_url);
        this.shell_channel = new this.WebSocket(ws_url + "/shell");
        this.iopub_channel = new this.WebSocket(ws_url + "/iopub");
        send_cookie = function(){
            this.send(document.cookie);
        };
        var already_called_onclose = false; // only alert once
        var ws_closed_early = function(evt){
            if (already_called_onclose){
                return;
            }
            already_called_onclose = true;
            if ( ! evt.wasClean ){
                that._websocket_closed(ws_url, true);
            }
        };
        var ws_closed_late = function(evt){
            if (already_called_onclose){
                return;
            }
            already_called_onclose = true;
            if ( ! evt.wasClean ){
                that._websocket_closed(ws_url, false);
            }
        };
        this.shell_channel.onopen = send_cookie;
        this.shell_channel.onclose = ws_closed_early;
        this.iopub_channel.onopen = send_cookie;
        this.iopub_channel.onclose = ws_closed_early;
        // switch from early-close to late-close message after 1s
        setTimeout(function() {
            if (that.shell_channel !== null) {
                that.shell_channel.onclose = ws_closed_late;
            }
            if (that.iopub_channel !== null) {
                that.iopub_channel.onclose = ws_closed_late;
            }
        }, 1000);
        this.shell_channel.onmessage = $.proxy(this._handle_shell_reply,this);
        this.iopub_channel.onmessage = $.proxy(this._handle_iopub_reply,this);
    };

    /**
     * Start the `shell`and `iopub` channels.
     * @method stop_channels
     */
    Kernel.prototype.stop_channels = function () {
        if (this.shell_channel !== null) {
            this.shell_channel.onclose = function (evt) {};
            this.shell_channel.close();
            this.shell_channel = null;
        };
        if (this.iopub_channel !== null) {
            this.iopub_channel.onclose = function (evt) {};
            this.iopub_channel.close();
            this.iopub_channel = null;
        };
    };

    // Main public methods.

    /**
     * Get info on object asynchronoulsy
     *
     * @async
     * @param objname {string}
     * @param callback {dict}
     * @method object_info_request
     *
     * @example
     *
     * When calling this method pass a callbacks structure of the form:
     *
     *     callbacks = {
     *      'object_info_reply': object_info_reply_callback
     *     }
     *
     * The `object_info_reply_callback` will be passed the content object of the
     *
     * `object_into_reply` message documented in
     * [IPython dev documentation](http://ipython.org/ipython-doc/dev/development/messaging.html#object-information)
     */
    Kernel.prototype.object_info_request = function (objname, callbacks) {
        if(typeof(objname)!=null && objname!=null)
        {
            var content = {
                oname : objname.toString(),
            };
            var msg = this._get_msg("object_info_request", content);
            this.shell_channel.send(JSON.stringify(msg));
            this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
            return msg.header.msg_id;
        }
        return;
    }

    /**
     * Execute given code into kernel, and pass result to callback.
     *
     * @async
     * @method execute
     * @param {string} code
     * @param callback {Object} With the following keys
     *      @param callback.'execute_reply' {function}
     *      @param callback.'output' {function}
     *      @param callback.'clear_output' {function}
     *      @param callback.'set_next_input' {function}
     * @param {object} [options]
     *      @param [options.silent=false] {Boolean}
     *      @param [options.user_expressions=empty_dict] {Dict}
     *      @param [options.user_variables=empty_list] {List od Strings}
     *      @param [options.allow_stdin=false] {Boolean} true|false
     *
     * @example
     *
     * The options object should contain the options for the execute call. Its default
     * values are:
     *
     *      options = {
     *        silent : true,
     *        user_variables : [],
     *        user_expressions : {},
     *        allow_stdin : false
     *      }
     *
     * When calling this method pass a callbacks structure of the form:
     *
     *      callbacks = {
     *       'execute_reply': execute_reply_callback,
     *       'output': output_callback,
     *       'clear_output': clear_output_callback,
     *       'set_next_input': set_next_input_callback
     *      }
     *
     * The `execute_reply_callback` will be passed the content and metadata
     * objects of the `execute_reply` message documented
     * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#execute)
     *
     * The `output_callback` will be passed `msg_type` ('stream','display_data','pyout','pyerr')
     * of the output and the content and metadata objects of the PUB/SUB channel that contains the
     * output:
     *
     * http://ipython.org/ipython-doc/dev/development/messaging.html#messages-on-the-pub-sub-socket
     *
     * The `clear_output_callback` will be passed a content object that contains
     * stdout, stderr and other fields that are booleans, as well as the metadata object.
     *
     * The `set_next_input_callback` will be passed the text that should become the next
     * input cell.
     */
    Kernel.prototype.execute = function (code, callbacks, options) {

        var content = {
            code : code,
            silent : true,
            user_variables : [],
            user_expressions : {},
            allow_stdin : false
        };
        $.extend(true, content, options)
        $([IPython.events]).trigger('execution_request.Kernel', {kernel: this, content:content});
        var msg = this._get_msg("execute_request", content);
        this.shell_channel.send(JSON.stringify(msg));
        this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
        return msg.header.msg_id;
    };

    /**
     * When calling this method pass a callbacks structure of the form:
     *
     *      callbacks = {
     *       'complete_reply': complete_reply_callback
     *      }
     *
     * The `complete_reply_callback` will be passed the content object of the
     * `complete_reply` message documented
     * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#complete)
     *
     * @method complete
     * @param line {integer}
     * @param cursor_pos {integer}
     * @param {dict} callbacks
     *      @param callbacks.complete_reply {function} `complete_reply_callback`
     *
     */
    Kernel.prototype.complete = function (line, cursor_pos, callbacks) {
        callbacks = callbacks || {};
        var content = {
            text : '',
            line : line,
            cursor_pos : cursor_pos
        };
        var msg = this._get_msg("complete_request", content);
        this.shell_channel.send(JSON.stringify(msg));
        this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
        return msg.header.msg_id;
    };

    Kernel.prototype.interrupt = function () {
        if (this.running) {
            $([IPython.events]).trigger('status_interrupting.Kernel', {kernel: this});
            $.post(this.kernel_url + "/interrupt");
        };
    };

    Kernel.prototype.kill = function () {
        if (this.running) {
            this.running = false;
            var settings = {
                cache : false,
                type : "DELETE"
            };
            $.ajax(this.kernel_url, settings);
        };
    };

    // Reply handlers.

    Kernel.prototype.get_callbacks_for_msg = function (msg_id) {
        var callbacks = this._msg_callbacks[msg_id];
        return callbacks;
    };

    Kernel.prototype.set_callbacks_for_msg = function (msg_id, callbacks) {
        this._msg_callbacks[msg_id] = callbacks || {};
    }

    Kernel.prototype._handle_shell_reply = function (e) {
        var reply = $.parseJSON(e.data);
        $([IPython.events]).trigger('shell_reply.Kernel', {kernel: this, reply:reply});
        var header = reply.header;
        var content = reply.content;
        var metadata = reply.metadata;
        var msg_type = header.msg_type;
        var callbacks = this.get_callbacks_for_msg(reply.parent_header.msg_id);
        if (callbacks !== undefined) {
            var cb = callbacks[msg_type];
            if (cb !== undefined) {
                cb(content, metadata);
            }
        };

        if (content.payload !== undefined) {
            var payload = content.payload || [];
            this._handle_payload(callbacks, payload);
        }
    };

    Kernel.prototype._handle_payload = function (callbacks, payload) {
        var l = payload.length;
        // Payloads are handled by triggering events because we don't want the Kernel
        // to depend on the Notebook or Pager classes.
        for (var i=0; i<l; i++) {
            if (payload[i].source === 'IPython.kernel.zmq.page.page') {
                var data = {'text':payload[i].text}
                $([IPython.events]).trigger('open_with_text.Pager', data);
            } else if (payload[i].source === 'IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.set_next_input') {
                if (callbacks.set_next_input !== undefined) {
                    callbacks.set_next_input(payload[i].text)
                }
            }
        };
    };

    Kernel.prototype._handle_iopub_reply = function (e) {
        var reply = $.parseJSON(e.data);
        var content = reply.content;
        var msg_type = reply.header.msg_type;
        var metadata = reply.metadata;
        var callbacks = this.get_callbacks_for_msg(reply.parent_header.msg_id);
        if (msg_type !== 'status' && callbacks === undefined) {
            // Message not from one of this notebook's cells and there are no
            // callbacks to handle it.
            return;
        }
        var output_types = ['stream','display_data','pyout','pyerr'];
        if (output_types.indexOf(msg_type) >= 0) {
            var cb = callbacks['output'];
            if (cb !== undefined) {
                cb(msg_type, content, metadata);
            }
        } else if (msg_type === 'status') {
            if (content.execution_state === 'busy') {
                $([IPython.events]).trigger('status_busy.Kernel', {kernel: this});
            } else if (content.execution_state === 'idle') {
                $([IPython.events]).trigger('status_idle.Kernel', {kernel: this});
            } else if (content.execution_state === 'restarting') {
                // restart channels if kernel restarts
                // avoids unlikely corrupted connection
                setTimeout($.proxy(this.start_channels, this), 500);
                $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
            } else if (content.execution_state === 'dead') {
                this.stop_channels();
                $([IPython.events]).trigger('status_dead.Kernel', {kernel: this});
            };
        } else if (msg_type === 'clear_output') {
            var cb = callbacks['clear_output'];
            if (cb !== undefined) {
                cb(content, metadata);
            }
        };
    };

    IPython.Kernel = Kernel;

    return IPython;

}(IPython));

<commit_msg>don't restart channels on kernel restart<commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2008-2011  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// Kernel
//============================================================================

/**
 * @module IPython
 * @namespace IPython
 * @submodule Kernel
 */

var IPython = (function (IPython) {

    var utils = IPython.utils;

    // Initialization and connection.
    /**
     * A Kernel Class to communicate with the Python kernel
     * @Class Kernel
     */
    var Kernel = function (base_url) {
        this.kernel_id = null;
        this.shell_channel = null;
        this.iopub_channel = null;
        this.base_url = base_url;
        this.running = false;
        this.username = "username";
        this.session_id = utils.uuid();
        this._msg_callbacks = {};

        if (typeof(WebSocket) !== 'undefined') {
            this.WebSocket = WebSocket;
        } else if (typeof(MozWebSocket) !== 'undefined') {
            this.WebSocket = MozWebSocket;
        } else {
            alert('Your browser does not have WebSocket support, please try Chrome, Safari or Firefox ≥ 6. Firefox 4 and 5 are also supported by you have to enable WebSockets in about:config.');
        };
    };

    Kernel.prototype._get_msg = function (msg_type, content) {
        var msg = {
            header : {
                msg_id : utils.uuid(),
                username : this.username,
                session : this.session_id,
                msg_type : msg_type
            },
            metadata : {},
            content : content,
            parent_header : {}
        };
        return msg;
    };

    /**
     * Start the Python kernel
     * @method start
     */
    Kernel.prototype.start = function (notebook_id) {
        var that = this;
        if (!this.running) {
            var qs = $.param({notebook:notebook_id});
            var url = this.base_url + '?' + qs;
            $.post(url,
                $.proxy(that._kernel_started,that),
                'json'
            );
        };
    };

    /**
     * Restart the python kernel.
     *
     * Emit a 'status_restarting.Kernel' event with
     * the current object as parameter
     *
     * @method restart
     */
    Kernel.prototype.restart = function () {
        $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
        var that = this;
        if (this.running) {
            this.stop_channels();
            var url = this.kernel_url + "/restart";
            $.post(url,
                $.proxy(that._kernel_started, that),
                'json'
            );
        };
    };

    Kernel.prototype._kernel_started = function (json) {
        console.log("Kernel started: ", json.kernel_id);
        this.running = true;
        this.kernel_id = json.kernel_id;
        this.ws_url = json.ws_url;
        this.kernel_url = this.base_url + "/" + this.kernel_id;
        this.start_channels();
        $([IPython.events]).trigger('status_started.Kernel', {kernel: this});
    };

    Kernel.prototype._websocket_closed = function(ws_url, early) {
        this.stop_channels();
        $([IPython.events]).trigger('websocket_closed.Kernel',
            {ws_url: ws_url, kernel: this, early: early}
        );
    };

    /**
     * Start the `shell`and `iopub` channels.
     * Will stop and restart them if they already exist.
     *
     * @method start_channels
     */
    Kernel.prototype.start_channels = function () {
        var that = this;
        this.stop_channels();
        var ws_url = this.ws_url + this.kernel_url;
        console.log("Starting WebSockets:", ws_url);
        this.shell_channel = new this.WebSocket(ws_url + "/shell");
        this.iopub_channel = new this.WebSocket(ws_url + "/iopub");
        send_cookie = function(){
            this.send(document.cookie);
        };
        var already_called_onclose = false; // only alert once
        var ws_closed_early = function(evt){
            if (already_called_onclose){
                return;
            }
            already_called_onclose = true;
            if ( ! evt.wasClean ){
                that._websocket_closed(ws_url, true);
            }
        };
        var ws_closed_late = function(evt){
            if (already_called_onclose){
                return;
            }
            already_called_onclose = true;
            if ( ! evt.wasClean ){
                that._websocket_closed(ws_url, false);
            }
        };
        this.shell_channel.onopen = send_cookie;
        this.shell_channel.onclose = ws_closed_early;
        this.iopub_channel.onopen = send_cookie;
        this.iopub_channel.onclose = ws_closed_early;
        // switch from early-close to late-close message after 1s
        setTimeout(function() {
            if (that.shell_channel !== null) {
                that.shell_channel.onclose = ws_closed_late;
            }
            if (that.iopub_channel !== null) {
                that.iopub_channel.onclose = ws_closed_late;
            }
        }, 1000);
        this.shell_channel.onmessage = $.proxy(this._handle_shell_reply,this);
        this.iopub_channel.onmessage = $.proxy(this._handle_iopub_reply,this);
    };

    /**
     * Start the `shell`and `iopub` channels.
     * @method stop_channels
     */
    Kernel.prototype.stop_channels = function () {
        if (this.shell_channel !== null) {
            this.shell_channel.onclose = function (evt) {};
            this.shell_channel.close();
            this.shell_channel = null;
        };
        if (this.iopub_channel !== null) {
            this.iopub_channel.onclose = function (evt) {};
            this.iopub_channel.close();
            this.iopub_channel = null;
        };
    };

    // Main public methods.

    /**
     * Get info on object asynchronoulsy
     *
     * @async
     * @param objname {string}
     * @param callback {dict}
     * @method object_info_request
     *
     * @example
     *
     * When calling this method pass a callbacks structure of the form:
     *
     *     callbacks = {
     *      'object_info_reply': object_info_reply_callback
     *     }
     *
     * The `object_info_reply_callback` will be passed the content object of the
     *
     * `object_into_reply` message documented in
     * [IPython dev documentation](http://ipython.org/ipython-doc/dev/development/messaging.html#object-information)
     */
    Kernel.prototype.object_info_request = function (objname, callbacks) {
        if(typeof(objname)!=null && objname!=null)
        {
            var content = {
                oname : objname.toString(),
            };
            var msg = this._get_msg("object_info_request", content);
            this.shell_channel.send(JSON.stringify(msg));
            this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
            return msg.header.msg_id;
        }
        return;
    }

    /**
     * Execute given code into kernel, and pass result to callback.
     *
     * @async
     * @method execute
     * @param {string} code
     * @param callback {Object} With the following keys
     *      @param callback.'execute_reply' {function}
     *      @param callback.'output' {function}
     *      @param callback.'clear_output' {function}
     *      @param callback.'set_next_input' {function}
     * @param {object} [options]
     *      @param [options.silent=false] {Boolean}
     *      @param [options.user_expressions=empty_dict] {Dict}
     *      @param [options.user_variables=empty_list] {List od Strings}
     *      @param [options.allow_stdin=false] {Boolean} true|false
     *
     * @example
     *
     * The options object should contain the options for the execute call. Its default
     * values are:
     *
     *      options = {
     *        silent : true,
     *        user_variables : [],
     *        user_expressions : {},
     *        allow_stdin : false
     *      }
     *
     * When calling this method pass a callbacks structure of the form:
     *
     *      callbacks = {
     *       'execute_reply': execute_reply_callback,
     *       'output': output_callback,
     *       'clear_output': clear_output_callback,
     *       'set_next_input': set_next_input_callback
     *      }
     *
     * The `execute_reply_callback` will be passed the content and metadata
     * objects of the `execute_reply` message documented
     * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#execute)
     *
     * The `output_callback` will be passed `msg_type` ('stream','display_data','pyout','pyerr')
     * of the output and the content and metadata objects of the PUB/SUB channel that contains the
     * output:
     *
     * http://ipython.org/ipython-doc/dev/development/messaging.html#messages-on-the-pub-sub-socket
     *
     * The `clear_output_callback` will be passed a content object that contains
     * stdout, stderr and other fields that are booleans, as well as the metadata object.
     *
     * The `set_next_input_callback` will be passed the text that should become the next
     * input cell.
     */
    Kernel.prototype.execute = function (code, callbacks, options) {

        var content = {
            code : code,
            silent : true,
            user_variables : [],
            user_expressions : {},
            allow_stdin : false
        };
        $.extend(true, content, options)
        $([IPython.events]).trigger('execution_request.Kernel', {kernel: this, content:content});
        var msg = this._get_msg("execute_request", content);
        this.shell_channel.send(JSON.stringify(msg));
        this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
        return msg.header.msg_id;
    };

    /**
     * When calling this method pass a callbacks structure of the form:
     *
     *      callbacks = {
     *       'complete_reply': complete_reply_callback
     *      }
     *
     * The `complete_reply_callback` will be passed the content object of the
     * `complete_reply` message documented
     * [here](http://ipython.org/ipython-doc/dev/development/messaging.html#complete)
     *
     * @method complete
     * @param line {integer}
     * @param cursor_pos {integer}
     * @param {dict} callbacks
     *      @param callbacks.complete_reply {function} `complete_reply_callback`
     *
     */
    Kernel.prototype.complete = function (line, cursor_pos, callbacks) {
        callbacks = callbacks || {};
        var content = {
            text : '',
            line : line,
            cursor_pos : cursor_pos
        };
        var msg = this._get_msg("complete_request", content);
        this.shell_channel.send(JSON.stringify(msg));
        this.set_callbacks_for_msg(msg.header.msg_id, callbacks);
        return msg.header.msg_id;
    };

    Kernel.prototype.interrupt = function () {
        if (this.running) {
            $([IPython.events]).trigger('status_interrupting.Kernel', {kernel: this});
            $.post(this.kernel_url + "/interrupt");
        };
    };

    Kernel.prototype.kill = function () {
        if (this.running) {
            this.running = false;
            var settings = {
                cache : false,
                type : "DELETE"
            };
            $.ajax(this.kernel_url, settings);
        };
    };

    // Reply handlers.

    Kernel.prototype.get_callbacks_for_msg = function (msg_id) {
        var callbacks = this._msg_callbacks[msg_id];
        return callbacks;
    };

    Kernel.prototype.set_callbacks_for_msg = function (msg_id, callbacks) {
        this._msg_callbacks[msg_id] = callbacks || {};
    }

    Kernel.prototype._handle_shell_reply = function (e) {
        var reply = $.parseJSON(e.data);
        $([IPython.events]).trigger('shell_reply.Kernel', {kernel: this, reply:reply});
        var header = reply.header;
        var content = reply.content;
        var metadata = reply.metadata;
        var msg_type = header.msg_type;
        var callbacks = this.get_callbacks_for_msg(reply.parent_header.msg_id);
        if (callbacks !== undefined) {
            var cb = callbacks[msg_type];
            if (cb !== undefined) {
                cb(content, metadata);
            }
        };

        if (content.payload !== undefined) {
            var payload = content.payload || [];
            this._handle_payload(callbacks, payload);
        }
    };

    Kernel.prototype._handle_payload = function (callbacks, payload) {
        var l = payload.length;
        // Payloads are handled by triggering events because we don't want the Kernel
        // to depend on the Notebook or Pager classes.
        for (var i=0; i<l; i++) {
            if (payload[i].source === 'IPython.kernel.zmq.page.page') {
                var data = {'text':payload[i].text}
                $([IPython.events]).trigger('open_with_text.Pager', data);
            } else if (payload[i].source === 'IPython.kernel.zmq.zmqshell.ZMQInteractiveShell.set_next_input') {
                if (callbacks.set_next_input !== undefined) {
                    callbacks.set_next_input(payload[i].text)
                }
            }
        };
    };

    Kernel.prototype._handle_iopub_reply = function (e) {
        var reply = $.parseJSON(e.data);
        var content = reply.content;
        var msg_type = reply.header.msg_type;
        var metadata = reply.metadata;
        var callbacks = this.get_callbacks_for_msg(reply.parent_header.msg_id);
        if (msg_type !== 'status' && callbacks === undefined) {
            // Message not from one of this notebook's cells and there are no
            // callbacks to handle it.
            return;
        }
        var output_types = ['stream','display_data','pyout','pyerr'];
        if (output_types.indexOf(msg_type) >= 0) {
            var cb = callbacks['output'];
            if (cb !== undefined) {
                cb(msg_type, content, metadata);
            }
        } else if (msg_type === 'status') {
            if (content.execution_state === 'busy') {
                $([IPython.events]).trigger('status_busy.Kernel', {kernel: this});
            } else if (content.execution_state === 'idle') {
                $([IPython.events]).trigger('status_idle.Kernel', {kernel: this});
            } else if (content.execution_state === 'restarting') {
                $([IPython.events]).trigger('status_restarting.Kernel', {kernel: this});
            } else if (content.execution_state === 'dead') {
                this.stop_channels();
                $([IPython.events]).trigger('status_dead.Kernel', {kernel: this});
            };
        } else if (msg_type === 'clear_output') {
            var cb = callbacks['clear_output'];
            if (cb !== undefined) {
                cb(content, metadata);
            }
        };
    };

    IPython.Kernel = Kernel;

    return IPython;

}(IPython));

<|endoftext|>


<commit_before>var ExamplesMenu = function(ide) {
    var container = new UI.Panel();
    container.setClass('menu');

    var title = new UI.Panel();
    title.setClass('title');
    title.setTextContent('Examples');
    container.add(title);

    var items = new UI.Panel();
    items.setClass('menuitems');
    container.add(items);

    var itemProps = [
        {title: 'SICP ch1', file: 'ch1.scm'},
        {title: 'SICP ch2', file: 'ch2.scm'},
        {title: 'SICP ch2 support', file: 'ch2support.scm'},
        {title: 'SICP ch2 test', file: 'ch2test.scm'},
        {title: 'SICP ch3', file: 'ch3.scm'},
        {title: 'SICP ch3 support', file: 'ch3support.scm'},
    ];
    for(var i = 0; i < itemProps.length; i++) {
        (function() {
            var itemProp = itemProps[i];
            var item = new UI.Row();
            item.setClass('menuitem');
            item.setTextContent(itemProp.title);
            item.onClick(function() {
                if(confirm('Any unsaved data will be lost. Are you sure?')) {
                    var req = new XMLHttpRequest();
                    req.open('GET', '../tests/SICP/' + itemProp.file, true);
                    req.addEventListener('load', function(event){
                        var content = event.target.responseText;
                        ide.editor.setValue(content);
                    }, false);
                    req.send(null);
                }
            });
            items.add(item);
        })();

    }

    return container;
}<commit_msg>Update<commit_after>var ExamplesMenu = function(ide) {
    var container = new UI.Panel();
    container.setClass('menu');

    var title = new UI.Panel();
    title.setClass('title');
    title.setTextContent('Examples');
    container.add(title);

    var items = new UI.Panel();
    items.setClass('menuitems');
    container.add(items);

    var itemProps = [
        {title: 'SICP ch1', file: 'ch1.scm'},
        {title: 'SICP ch2 support', file: 'ch2support.scm'},
        {title: 'SICP ch2', file: 'ch2.scm'},
        {title: 'SICP ch2 test', file: 'ch2tests.scm'},
        {title: 'SICP ch3 support', file: 'ch3support.scm'},
        {title: 'SICP ch3', file: 'ch3.scm'},
    ];
    for(var i = 0; i < itemProps.length; i++) {
        (function() {
            var itemProp = itemProps[i];
            var item = new UI.Row();
            item.setClass('menuitem');
            item.setTextContent(itemProp.title);
            item.onClick(function() {
                if(confirm('Any unsaved data will be lost. Are you sure?')) {
                    var req = new XMLHttpRequest();
                    req.open('GET', '../tests/SICP/' + itemProp.file, true);
                    req.addEventListener('load', function(event){
                        var content = event.target.responseText;
                        ide.editor.setValue(content);
                    }, false);
                    req.send(null);
                }
            });
            items.add(item);
        })();

    }

    return container;
}<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Gregory McGee

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

angular.module('gm.datepickerMultiSelect', ['ui.bootstrap'])
.config(['$provide', function($provide) {
	$provide.decorator('daypickerDirective', ['$delegate', function($delegate) {
		var directive = $delegate[0];

		/* Override compile */
		var link = directive.link;

		directive.compile = function() {
			return function(scope, element, attrs, ctrl) {
				link.apply(this, arguments);

				var selectedDates = [];

				/* Called when multiSelect model is updated */
				scope.$on('update', function(event, newDates) {
					selectedDates = newDates;
					update();
				});

				/* Get dates pushed into multiSelect array before Datepicker is ready */
				scope.$emit('requestSelectedDates');

				/* Fires when date is selected or when month is changed. */
				scope.$watch(function () {
					return ctrl.activeDate.getTime();
				}, update);

				function update() {
					angular.forEach(scope.rows, function(row) {
						angular.forEach(row, function(day) {
							day.selected = selectedDates.indexOf(day.date.setHours(0, 0, 0, 0)) > -1
						});
					});
				}
			}
		}

		return $delegate;
	}]);
}])
.directive('multiSelect', function() {
	return {
		require: ['datepicker', 'ngModel'],
		link: function(scope, elem, attrs, ctrls) {
			var selectedDates;

			/* Called when directive is compiled */
			scope.$on('requestSelectedDates', function() {
				scope.$broadcast('update', selectedDates);
			});

			scope.$watchCollection(attrs.multiSelect, function(newVal) {
				selectedDates = newVal || [];
				scope.$broadcast('update', selectedDates);
			});

			scope.$watch(attrs.ngModel, function(newVal, oldVal) {
				if(!newVal) return;

				var dateVal = newVal.getTime();

				if(selectedDates.indexOf(dateVal) < 0) {
					selectedDates.push(dateVal);
				} else {
					selectedDates.splice(selectedDates.indexOf(dateVal), 1);
				}
			});
		}
	}
});
<commit_msg>Remove 'datepicker' requirement<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Gregory McGee

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

angular.module('gm.datepickerMultiSelect', ['ui.bootstrap'])
.config(['$provide', function($provide) {
	$provide.decorator('daypickerDirective', ['$delegate', function($delegate) {
		var directive = $delegate[0];

		/* Override compile */
		var link = directive.link;

		directive.compile = function() {
			return function(scope, element, attrs, ctrl) {
				link.apply(this, arguments);

				var selectedDates = [];

				/* Called when multiSelect model is updated */
				scope.$on('update', function(event, newDates) {
					selectedDates = newDates;
					update();
				});

				/* Get dates pushed into multiSelect array before Datepicker is ready */
				scope.$emit('requestSelectedDates');

				/* Fires when date is selected or when month is changed. */
				scope.$watch(function () {
					return ctrl.activeDate.getTime();
				}, update);

				function update() {
					angular.forEach(scope.rows, function(row) {
						angular.forEach(row, function(day) {
							day.selected = selectedDates.indexOf(day.date.setHours(0, 0, 0, 0)) > -1
						});
					});
				}
			}
		}

		return $delegate;
	}]);
}])
.directive('multiSelect', function() {
	return {
		require: ['ngModel'],
		link: function(scope, elem, attrs, ctrls) {
			var selectedDates;

			/* Called when directive is compiled */
			scope.$on('requestSelectedDates', function() {
				scope.$broadcast('update', selectedDates);
			});

			scope.$watchCollection(attrs.multiSelect, function(newVal) {
				selectedDates = newVal || [];
				scope.$broadcast('update', selectedDates);
			});

			scope.$watch(attrs.ngModel, function(newVal, oldVal) {
				if(!newVal) return;

				var dateVal = newVal.getTime();

				if(selectedDates.indexOf(dateVal) < 0) {
					selectedDates.push(dateVal);
				} else {
					selectedDates.splice(selectedDates.indexOf(dateVal), 1);
				}
			});
		}
	}
});
<|endoftext|>


<commit_before>/*
Copyright 2015-2019 The OmniDB Team
This file is part of OmniDB.
OmniDB is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
OmniDB is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with OmniDB. If not, see http://www.gnu.org/licenses/.
*/

function composedPath(el) {
    var path = [];
    while (el) {
        path.push(el);
        if (el.tagName === 'HTML') {
            path.push(document);
            path.push(window);
            return path;
       }
       el = el.parentElement;
    }
}

function createTabControl({ p_div, p_hierarchy }) {

	// Get an element's exact position
	function getPosition(el) {
		var xPos = 0;
		var yPos = 0;

		while (el) {
			if (el.tagName == "BODY") {
				var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
				var yScroll = el.scrollTop || document.documentElement.scrollTop;

				xPos += (el.offsetLeft - xScroll + el.clientLeft);
				yPos += (el.offsetTop - yScroll + el.clientTop);
			}
			else {
				xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
				yPos += (el.offsetTop - el.scrollTop + el.clientTop);
			}

			el = el.offsetParent;
		}

		return {
			x: xPos,
			y: yPos
		};
	}

  // Initializing HTML elements
	var v_div = document.getElementById(p_div);
  v_div.innerHTML = '';

  var v_nav = document.createElement('nav');
  var v_div_tab_list = document.createElement('div');
  v_div_tab_list.className = 'nav nav-tabs';
  v_nav.appendChild(v_div_tab_list);
  var v_div_tab_content_list = document.createElement('div');
  v_div_tab_content_list.className = 'omnidb__tab-content omnidb__tab-content--primary tab-content';

  var v_tab_menu = document.createElement('div');
  v_tab_menu.className = 'omnidb__tab-menu';

  if (p_hierarchy != undefined) {
    let css_tab_menu_variations = [
      'omnidb__tab-menu--',
      'omnidb__theme-bg--menu-'
    ];
    for (let i = 0; i < css_tab_menu_variations.length; i++) {
      v_tab_menu.classList.add(css_tab_menu_variations[i] + p_hierarchy);
    }
  }

  v_tab_menu.appendChild(v_nav);
  v_div.appendChild(v_tab_menu);
  v_div.appendChild(v_div_tab_content_list);

	var v_tabControl = {
		id: p_div,
		tabColor: null,
		selectedTab: null,
		selectedDiv: null,
		selectedA: null,
		tabListContentDiv: v_div_tab_content_list,
		tabList : [],
		tabListDiv : v_div_tab_list,
		tabCounter : 0,
		tag: new Object(),
    selectTabIndex : function(p_index) {

			if (this.tabList[p_index].selectable) {

				if (this.selectedTab!=null)
					this.selectedTab.selected = false;

				this.tabList[p_index].selected = true;

				this.selectedTab = this.tabList[p_index];

        //$(this.tabList[p_index].elementA).tab('show');

				if (this.selectedDiv!=null) {
          this.selectedDiv.classList.remove('active');
          this.selectedA.classList.remove('active');
				}

				this.tabList[p_index].elementA.classList.add('active');
				this.tabList[p_index].elementDiv.classList.add('active');

				this.selectedA = this.tabList[p_index].elementA;
				this.selectedDiv = this.tabList[p_index].elementDiv;

				if(this.tabList[p_index].selectFunction != null) {
					this.tabList[p_index].selectFunction();
				}
			}

		},
    disableTabIndex : function(p_index) {
      this.tabList[p_index].elementA.classList.add('disabled');
		},
    enableTabIndex : function(p_index) {
      console.log(this.tabList[p_index].elementA.classList)
      this.tabList[p_index].elementA.classList.remove('disabled');
      console.log(this.tabList[p_index].elementA.classList)
      console.log(this.tabList[p_index].elementA)
		},
    disableSelectableTabIndex : function(p_index) {
      this.tabList[p_index].selectable = false;
		},
    enableSelectableTabIndex : function(p_index) {
      this.tabList[p_index].selectable = true;
		},
		selectTab : function(p_tab) {

			if (this.selectedTab!=p_tab) {
				if (p_tab.selectable) {

					if (this.selectedTab!=null)
						this.selectedTab.selected = false;

					p_tab.selected = true;

					this.selectedTab = p_tab;

					if (this.selectedDiv!=null) {
						this.selectedDiv.classList.remove('active');
						this.selectedA.classList.remove('active');
					}

					p_tab.elementA.classList.add('active');
					p_tab.elementDiv.classList.add('active');

					this.selectedA = p_tab.elementA;
					this.selectedDiv = p_tab.elementDiv;

					if(p_tab.selectFunction != null) {
						p_tab.selectFunction();
					}
				}
			}
		},
    disableTab : function(p_tab) {
      p_tab.elementA.classList.add('disabled');
		},
    enableTab : function(p_tab) {
      p_tab.elementA.classList.remove('disabled');
		},
    disableSelectableTab : function(p_tab) {
      p_tab.selectable = false;
		},
    enableSelectableTab : function(p_tab) {
      p_tab.selectable = true;
		},
		disableClose : function(p_tab) {
			if (p_tab.elementClose!=null) {
				p_tab.elementClose.style.display = 'none';
			}
		},
		enableClose : function(p_tab) {
			if (p_tab.elementClose!=null) {
				p_tab.elementClose.style.display = '';
			}
		},
		removeTabIndex : function(p_index) {
			var v_tab = this.tabList[p_index];

			v_tab.elementDiv.parentNode.removeChild(v_tab.elementDiv);
			v_tab.elementA.parentNode.removeChild(v_tab.elementA);

			this.tabList.splice(p_index, 1);
		},
    removeLastTab : function() {
      this.removeTabIndex(this.tabList.length-1);
		},
		removeTab : function(p_tab) {

			var v_tab = p_tab;

			v_tab.elementDiv.parentNode.removeChild(v_tab.elementDiv);
			v_tab.elementA.parentNode.removeChild(v_tab.elementA);

			var v_index = this.tabList.indexOf(p_tab);

      var v_current_index = this.tabList.indexOf(this.selectedTab);

      if (v_index == v_current_index) {
  			if (v_index > 0)
  				this.selectTabIndex(v_index-1);
  			else if (this.tabList[v_index+1]!=null)
  				this.selectTabIndex(v_index+1);
      }

			this.tabList.splice(this.tabList.indexOf(p_tab), 1);

		},
		renameTab : function(p_tab,p_name) {

			var v_span = p_tab.elementA.childNodes[0];
			v_span.innerHTML = p_name;

			p_tab.text = p_name;

		},
		createTab : function({
      p_clickFunction = null,
      p_close = true,
      p_closeFunction = null,
      p_dblClickFunction = null,
      p_disabled = false,
      p_icon = false,
      p_isDraggable = true,
      p_name = '',
      p_selectFunction = null,
      p_selectable = true
    }) {
			var v_control = this;
			var v_index = this.tabCounter;

			this.tabCounter++;

			var v_tab = {
				id : p_div + '_tab' + v_index,
				seq: v_index,
				text: p_name,
				selected : false,
				elementA : null,
				elementDiv : null,
				elementClose: null,
				tag: null,
				clickFunction: p_clickFunction,
				dblClickFunction : p_dblClickFunction,
				closeFunction: p_closeFunction,
				selectFunction: p_selectFunction,
				selectable: p_selectable,
        disabled: p_disabled,
				removeTab: function() { v_control.removeTab(this); },
				renameTab: function(p_name) { v_control.renameTab(this,p_name); },
				disableClose: function() { v_control.disableClose(this) },
				enableClose: function() { v_control.enableClose(this) },
				isDraggable: p_isDraggable
			};

			var v_a = document.createElement('a');
      v_a.setAttribute('id','a_' + p_div + '_tab' + v_index);
      v_a.setAttribute('data-toggle','tab');
      v_a.setAttribute('role','tab');
      v_a.setAttribute('aria-selected','false');
      v_a.setAttribute('aria-selected','false');
      v_a.setAttribute('href','#' + 'div_' + p_div + '_tab' + v_index);
      v_a.setAttribute('aria-controls','div_' + p_div + '_tab' + v_index);

      if (p_disabled)
        v_a.className = 'omnidb__tab-menu__link nav-item nav-link disabled';
      else
        v_a.className = 'omnidb__tab-menu__link nav-item nav-link';

      var v_close = document.createElement('i');
      v_close.className = 'fas fa-times tab-icon icon-close omnidb__tab-menu__link-close';

			v_tab.elementClose = v_close;

			v_close.onclick = function(e) {
        e.stopPropagation();
        e.preventDefault();
        if (v_tab.closeFunction!=null) {
          v_tab.closeFunction(e,v_tab);
        }
			};
			v_a.innerHTML = '' +
                        ((p_icon !== false) ? '' + p_icon + '' : '') +
                        '' + p_name + '' +
                      '';
      if (p_close) {
  			v_a.appendChild(v_close);
      }

			v_a.ondblclick = function(e) {

				if (v_tab.dblClickFunction!=null)
					v_tab.dblClickFunction(v_tab);
			};

			var v_div = document.createElement('div');
      v_div.className = 'tab-pane';
      v_div.setAttribute('id','div_' + p_div + '_tab' + v_index);
      v_div.setAttribute('role','tabpanel');
      v_div.setAttribute('aria-labelledby','a_' + p_div + '_tab' + v_index);

			v_tab.elementA = v_a;
			v_tab.elementDiv = v_div;

			v_a.onclick = function(e) {

        e.stopPropagation();
        e.preventDefault();
        if (v_tab.selectable)
				    v_control.selectTab(v_tab);

				if (v_tab.clickFunction!=null)
					v_tab.clickFunction(e);
			};

			this.tabListDiv.appendChild(v_a);
			this.tabListContentDiv.appendChild(v_div);

			this.tabList.push(v_tab);

			return v_tab;
		},
	};

	return v_tabControl;

}

//Create a HTML element specified by parameter 'p_type'
function createSimpleElement(p_type,p_id,p_class) {
	element = document.createElement(p_type);
	if (p_id!=undefined)
		element.id = p_id;
	if (p_class!=undefined)
		element.className = p_class;
	return element;
}

//Create img element
function createImgElement(p_id,p_class,p_src) {
	element = document.createElement('img');
	if (p_id!=undefined)
		element.id = p_id;
	if (p_class!=undefined)
		element.className = p_class;
	if (p_src!=undefined)
		element.src = p_src;
	return element;
}
<commit_msg>Fixed tab-link-content class for hierarchy attr<commit_after>/*
Copyright 2015-2019 The OmniDB Team
This file is part of OmniDB.
OmniDB is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
OmniDB is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with OmniDB. If not, see http://www.gnu.org/licenses/.
*/

function composedPath(el) {
    var path = [];
    while (el) {
        path.push(el);
        if (el.tagName === 'HTML') {
            path.push(document);
            path.push(window);
            return path;
       }
       el = el.parentElement;
    }
}

function createTabControl({ p_div, p_hierarchy }) {

	// Get an element's exact position
	function getPosition(el) {
		var xPos = 0;
		var yPos = 0;

		while (el) {
			if (el.tagName == "BODY") {
				var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
				var yScroll = el.scrollTop || document.documentElement.scrollTop;

				xPos += (el.offsetLeft - xScroll + el.clientLeft);
				yPos += (el.offsetTop - yScroll + el.clientTop);
			}
			else {
				xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
				yPos += (el.offsetTop - el.scrollTop + el.clientTop);
			}

			el = el.offsetParent;
		}

		return {
			x: xPos,
			y: yPos
		};
	}

  // Initializing HTML elements
	var v_div = document.getElementById(p_div);
  v_div.innerHTML = '';

  var v_nav = document.createElement('nav');
  var v_div_tab_list = document.createElement('div');
  v_div_tab_list.className = 'nav nav-tabs';
  v_nav.appendChild(v_div_tab_list);
  var v_div_tab_content_list = document.createElement('div');
  v_div_tab_content_list.className = 'tab-content omnidb__tab-content';

  var v_tab_menu = document.createElement('div');
  v_tab_menu.className = 'omnidb__tab-menu';

  if (p_hierarchy != undefined) {
    let css_tab_menu_variations = [
      'omnidb__tab-menu--',
      'omnidb__theme-bg--menu-'
    ];
    for (let i = 0; i < css_tab_menu_variations.length; i++) {
      v_tab_menu.classList.add(css_tab_menu_variations[i] + p_hierarchy);
    }
    v_div_tab_content_list.classList.add('omnidb__tab-content--' + p_hierarchy);
  }

  v_tab_menu.appendChild(v_nav);
  v_div.appendChild(v_tab_menu);
  v_div.appendChild(v_div_tab_content_list);

	var v_tabControl = {
		id: p_div,
		tabColor: null,
		selectedTab: null,
		selectedDiv: null,
		selectedA: null,
		tabListContentDiv: v_div_tab_content_list,
		tabList : [],
		tabListDiv : v_div_tab_list,
		tabCounter : 0,
		tag: new Object(),
    selectTabIndex : function(p_index) {

			if (this.tabList[p_index].selectable) {

				if (this.selectedTab!=null)
					this.selectedTab.selected = false;

				this.tabList[p_index].selected = true;

				this.selectedTab = this.tabList[p_index];

        //$(this.tabList[p_index].elementA).tab('show');

				if (this.selectedDiv!=null) {
          this.selectedDiv.classList.remove('active');
          this.selectedA.classList.remove('active');
				}

				this.tabList[p_index].elementA.classList.add('active');
				this.tabList[p_index].elementDiv.classList.add('active');

				this.selectedA = this.tabList[p_index].elementA;
				this.selectedDiv = this.tabList[p_index].elementDiv;

				if(this.tabList[p_index].selectFunction != null) {
					this.tabList[p_index].selectFunction();
				}
			}

		},
    disableTabIndex : function(p_index) {
      this.tabList[p_index].elementA.classList.add('disabled');
		},
    enableTabIndex : function(p_index) {
      console.log(this.tabList[p_index].elementA.classList)
      this.tabList[p_index].elementA.classList.remove('disabled');
      console.log(this.tabList[p_index].elementA.classList)
      console.log(this.tabList[p_index].elementA)
		},
    disableSelectableTabIndex : function(p_index) {
      this.tabList[p_index].selectable = false;
		},
    enableSelectableTabIndex : function(p_index) {
      this.tabList[p_index].selectable = true;
		},
		selectTab : function(p_tab) {

			if (this.selectedTab!=p_tab) {
				if (p_tab.selectable) {

					if (this.selectedTab!=null)
						this.selectedTab.selected = false;

					p_tab.selected = true;

					this.selectedTab = p_tab;

					if (this.selectedDiv!=null) {
						this.selectedDiv.classList.remove('active');
						this.selectedA.classList.remove('active');
					}

					p_tab.elementA.classList.add('active');
					p_tab.elementDiv.classList.add('active');

					this.selectedA = p_tab.elementA;
					this.selectedDiv = p_tab.elementDiv;

					if(p_tab.selectFunction != null) {
						p_tab.selectFunction();
					}
				}
			}
		},
    disableTab : function(p_tab) {
      p_tab.elementA.classList.add('disabled');
		},
    enableTab : function(p_tab) {
      p_tab.elementA.classList.remove('disabled');
		},
    disableSelectableTab : function(p_tab) {
      p_tab.selectable = false;
		},
    enableSelectableTab : function(p_tab) {
      p_tab.selectable = true;
		},
		disableClose : function(p_tab) {
			if (p_tab.elementClose!=null) {
				p_tab.elementClose.style.display = 'none';
			}
		},
		enableClose : function(p_tab) {
			if (p_tab.elementClose!=null) {
				p_tab.elementClose.style.display = '';
			}
		},
		removeTabIndex : function(p_index) {
			var v_tab = this.tabList[p_index];

			v_tab.elementDiv.parentNode.removeChild(v_tab.elementDiv);
			v_tab.elementA.parentNode.removeChild(v_tab.elementA);

			this.tabList.splice(p_index, 1);
		},
    removeLastTab : function() {
      this.removeTabIndex(this.tabList.length-1);
		},
		removeTab : function(p_tab) {

			var v_tab = p_tab;

			v_tab.elementDiv.parentNode.removeChild(v_tab.elementDiv);
			v_tab.elementA.parentNode.removeChild(v_tab.elementA);

			var v_index = this.tabList.indexOf(p_tab);

      var v_current_index = this.tabList.indexOf(this.selectedTab);

      if (v_index == v_current_index) {
  			if (v_index > 0)
  				this.selectTabIndex(v_index-1);
  			else if (this.tabList[v_index+1]!=null)
  				this.selectTabIndex(v_index+1);
      }

			this.tabList.splice(this.tabList.indexOf(p_tab), 1);

		},
		renameTab : function(p_tab,p_name) {

			var v_span = p_tab.elementA.childNodes[0];
			v_span.innerHTML = p_name;

			p_tab.text = p_name;

		},
		createTab : function({
      p_clickFunction = null,
      p_close = true,
      p_closeFunction = null,
      p_dblClickFunction = null,
      p_disabled = false,
      p_icon = false,
      p_isDraggable = true,
      p_name = '',
      p_selectFunction = null,
      p_selectable = true
    }) {
			var v_control = this;
			var v_index = this.tabCounter;

			this.tabCounter++;

			var v_tab = {
				id : p_div + '_tab' + v_index,
				seq: v_index,
				text: p_name,
				selected : false,
				elementA : null,
				elementDiv : null,
				elementClose: null,
				tag: null,
				clickFunction: p_clickFunction,
				dblClickFunction : p_dblClickFunction,
				closeFunction: p_closeFunction,
				selectFunction: p_selectFunction,
				selectable: p_selectable,
        disabled: p_disabled,
				removeTab: function() { v_control.removeTab(this); },
				renameTab: function(p_name) { v_control.renameTab(this,p_name); },
				disableClose: function() { v_control.disableClose(this) },
				enableClose: function() { v_control.enableClose(this) },
				isDraggable: p_isDraggable
			};

			var v_a = document.createElement('a');
      v_a.setAttribute('id','a_' + p_div + '_tab' + v_index);
      v_a.setAttribute('data-toggle','tab');
      v_a.setAttribute('role','tab');
      v_a.setAttribute('aria-selected','false');
      v_a.setAttribute('aria-selected','false');
      v_a.setAttribute('href','#' + 'div_' + p_div + '_tab' + v_index);
      v_a.setAttribute('aria-controls','div_' + p_div + '_tab' + v_index);

      if (p_disabled)
        v_a.className = 'omnidb__tab-menu__link nav-item nav-link disabled';
      else
        v_a.className = 'omnidb__tab-menu__link nav-item nav-link';

      var v_close = document.createElement('i');
      v_close.className = 'fas fa-times tab-icon icon-close omnidb__tab-menu__link-close';

			v_tab.elementClose = v_close;

			v_close.onclick = function(e) {
        e.stopPropagation();
        e.preventDefault();
        if (v_tab.closeFunction!=null) {
          v_tab.closeFunction(e,v_tab);
        }
			};
			v_a.innerHTML = '' +
                        ((p_icon !== false) ? '' + p_icon + '' : '') +
                        '' + p_name + '' +
                      '';
      if (p_close) {
  			v_a.appendChild(v_close);
      }

			v_a.ondblclick = function(e) {

				if (v_tab.dblClickFunction!=null)
					v_tab.dblClickFunction(v_tab);
			};

			var v_div = document.createElement('div');
      v_div.className = 'tab-pane';
      v_div.setAttribute('id','div_' + p_div + '_tab' + v_index);
      v_div.setAttribute('role','tabpanel');
      v_div.setAttribute('aria-labelledby','a_' + p_div + '_tab' + v_index);

			v_tab.elementA = v_a;
			v_tab.elementDiv = v_div;

			v_a.onclick = function(e) {

        e.stopPropagation();
        e.preventDefault();
        if (v_tab.selectable)
				    v_control.selectTab(v_tab);

				if (v_tab.clickFunction!=null)
					v_tab.clickFunction(e);
			};

			this.tabListDiv.appendChild(v_a);
			this.tabListContentDiv.appendChild(v_div);

			this.tabList.push(v_tab);

			return v_tab;
		},
	};

	return v_tabControl;

}

//Create a HTML element specified by parameter 'p_type'
function createSimpleElement(p_type,p_id,p_class) {
	element = document.createElement(p_type);
	if (p_id!=undefined)
		element.id = p_id;
	if (p_class!=undefined)
		element.className = p_class;
	return element;
}

//Create img element
function createImgElement(p_id,p_class,p_src) {
	element = document.createElement('img');
	if (p_id!=undefined)
		element.id = p_id;
	if (p_class!=undefined)
		element.className = p_class;
	if (p_src!=undefined)
		element.src = p_src;
	return element;
}
<|endoftext|>


<commit_before>import { OHIF } from 'meteor/ohif:core';

var activeTool = 'wwwc';
var defaultTool = 'wwwc';

var tools = {};

var toolDefaultStates = {
    activate: [],
    deactivate: ['length', 'angle', 'annotate', 'ellipticalRoi', 'rectangleRoi'],
    enable: [],
    disable: [],
    disabledToolButtons: []
};

var initialized = false;

function configureTools() {

    // Get Cornerstone Tools
    const { panMultiTouch, textStyle, toolStyle, toolColors, length,
            bidirectional, arrowAnnotate, zoom, ellipticalRoi, nonTarget } = cornerstoneTools;

    // Set the configuration for the multitouch pan tool
    const multiTouchPanConfig = {
        testPointers: function(eventData) {
            return (eventData.numPointers >= 3);
        }
    };
    panMultiTouch.setConfiguration(multiTouchPanConfig);

    // Set text box background color
    textStyle.setBackgroundColor('transparent');

    // Set the tool font and font size
    // context.font = "[style] [variant] [weight] [size]/[line height] [font family]";
    const fontFamily = 'Roboto, OpenSans, HelveticaNeue-Light, Helvetica Neue Light, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif';
    textStyle.setFont('15px ' + fontFamily);

    // Set the tool width
    toolStyle.setToolWidth(2);

    // Set color for inactive tools
    toolColors.setToolColor('rgb(255, 255, 0)');

    // Set color for active tools
    toolColors.setActiveColor('rgb(0, 255, 0)');

    // Set shadow configuration for length and bidirectional text boxes
    const shadowConfig = {
        shadow: false,
        shadowColor: '#000000',
        shadowOffsetX: 0,
        shadowOffsetY: 0
    };

    // Get some tools config to not override them
    const lengthConfig = length.getConfiguration();
    const bidirectionalConfig = bidirectional.getConfiguration();
    const ellipticalRoiConfig = ellipticalRoi.getConfiguration();
    const nonTargetConfig = nonTarget.getConfiguration();

    // Add shadow to length tool
    length.setConfiguration({
        ...lengthConfig,
        ...shadowConfig
    });

    // Add shadow to length tool
    bidirectional.setConfiguration({
        ...bidirectionalConfig,
        ...shadowConfig
    });

    // Add shadow to length tool
    ellipticalRoi.setConfiguration({
        ...ellipticalRoiConfig,
        ...shadowConfig
    });

     // Add shadow to non target tool
    nonTarget.setConfiguration({
        ...nonTargetConfig,
        ...shadowConfig
    });

    // Set the configuration values for the text annotation (Arrow) tool
    const annotateConfig = {
        getTextCallback: getAnnotationTextCallback,
        changeTextCallback: changeAnnotationTextCallback,
        drawHandles: false,
        arrowFirst: true
    };
    arrowAnnotate.setConfiguration(annotateConfig);

    const zoomConfig = {
        minScale: 0.05,
        maxScale: 10
    };
    zoom.setConfiguration(zoomConfig);
}

toolManager = {
    init: function() {
        toolManager.addTool('wwwc', {
            mouse: cornerstoneTools.wwwc,
            touch: cornerstoneTools.wwwcTouchDrag
        });
        toolManager.addTool('zoom', {
            mouse: cornerstoneTools.zoom,
            touch: cornerstoneTools.zoomTouchDrag
        });
        toolManager.addTool('wwwcRegion', {
            mouse: cornerstoneTools.wwwcRegion,
            touch: cornerstoneTools.wwwcRegionTouch
        });
        toolManager.addTool('dragProbe', {
            mouse: cornerstoneTools.dragProbe,
            touch: cornerstoneTools.dragProbeTouch
        });
        toolManager.addTool('pan', {
            mouse: cornerstoneTools.pan,
            touch: cornerstoneTools.panTouchDrag
        });
        toolManager.addTool('stackScroll', {
            mouse: cornerstoneTools.stackScroll,
            touch: cornerstoneTools.stackScrollTouchDrag
        });
        toolManager.addTool('length', {
            mouse: cornerstoneTools.length,
            touch: cornerstoneTools.lengthTouch
        });
        toolManager.addTool('angle', {
            mouse: cornerstoneTools.simpleAngle,
            touch: cornerstoneTools.simpleAngleTouch
        });
        toolManager.addTool('magnify', {
            mouse: cornerstoneTools.magnify,
            touch: cornerstoneTools.magnifyTouchDrag
        });
        toolManager.addTool('ellipticalRoi', {
            mouse: cornerstoneTools.ellipticalRoi,
            touch: cornerstoneTools.ellipticalRoiTouch
        });
        toolManager.addTool('rectangleRoi', {
            mouse: cornerstoneTools.rectangleRoi,
            touch: cornerstoneTools.rectangleRoiTouch
        });
        toolManager.addTool('annotate', {
            mouse: cornerstoneTools.arrowAnnotate,
            touch: cornerstoneTools.arrowAnnotateTouch
        });

        toolManager.addTool('rotate', {
            mouse: cornerstoneTools.rotate,
            touch: cornerstoneTools.rotateTouchDrag
        });

        if (OHIF.viewer.defaultTool) {
            activeTool = OHIF.viewer.defaultTool;
        }

        configureTools();
        initialized = true;
    },
    addTool: function(name, base) {
        tools[name] = base;
    },
    getTools: function() {
        return tools;
    },
    setToolDefaultStates: function(states) {
        toolDefaultStates = states;
    },
    getToolDefaultStates: function() {
        return toolDefaultStates;
    },
    setActiveToolForElement: function(tool, element) {
        var canvases = $(element).find('canvas');
        if (element.classList.contains('empty') || !canvases.length) {
            return;
        }

        // First, deactivate the current active tool
        tools[activeTool].mouse.deactivate(element, 1);

        if (tools[activeTool].touch) {
            tools[activeTool].touch.deactivate(element);
        }

        // Enable tools based on their default states
        Object.keys(toolDefaultStates).forEach(function(action) {
            var relevantTools = toolDefaultStates[action];
            if (!relevantTools || !relevantTools.length || action === 'disabledToolButtons') {
                return;
            }
            relevantTools.forEach(function(toolType) {
                // the currently active tool has already been deactivated and can be skipped
                if (action === 'deactivate' && toolType === activeTool) {
                    return;
                }
                tools[toolType].mouse[action](
                    element,
                    (action === 'activate' || action === 'deactivate' ? 1 : void 0)
                );
                tools[toolType].touch[action](element);
            });
        });

        // Get the stack toolData
        var toolData = cornerstoneTools.getToolState(element, 'stack');
        if (!toolData || !toolData.data || !toolData.data.length) {
            return;
        }

        // Get the imageIds for this element
        var imageIds = toolData.data[0].imageIds;

        // Deactivate all the middle mouse, right click, and scroll wheel tools
        cornerstoneTools.pan.deactivate(element);
        cornerstoneTools.zoom.deactivate(element);
        cornerstoneTools.zoomWheel.deactivate(element);
        cornerstoneTools.stackScrollWheel.deactivate(element);

        // Reactivate the relevant scrollwheel tool for this element
        if (imageIds.length > 1) {
            // scroll is the default tool for middle mouse wheel for stacks
            cornerstoneTools.stackScrollWheel.activate(element);
        } else {
            // zoom is the default tool for middle mouse wheel for single images (non stacks)
            cornerstoneTools.zoomWheel.activate(element);
        }

        // This block ensures that the middle mouse and scroll tools keep working
        if (tool === 'pan') {
            cornerstoneTools.pan.activate(element, 3); // 3 means left mouse button and middle mouse button
            cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button
        } else if (tool === 'zoom') {
            cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
            cornerstoneTools.zoom.activate(element, 5); // 5 means left mouse button and right mouse button
        } else {
            // Reactivate the middle mouse and right click tools
            cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
            cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button

            // Activate the chosen tool
            tools[tool].mouse.activate(element, 1);
        }

        if (tools[tool].touch) {
            tools[tool].touch.activate(element);
        }

        cornerstoneTools.zoomTouchPinch.activate(element);
        cornerstoneTools.panMultiTouch.activate(element);
    },
    setActiveTool: function(tool, elements) {
        if (!initialized) {
            toolManager.init();
        }

        if (!tool) {
            tool = defaultTool;
        }

        if (!elements || !elements.length) {
            elements = $('.imageViewerViewport');
        }

        // Otherwise, set the active tool for all viewport elements
        $(elements).each(function(index, element) {
            toolManager.setActiveToolForElement(tool, element);
        });
        activeTool = tool;

        // Store the active tool in the session in order to enable reactivity
        Session.set('ToolManagerActiveTool', tool);
    },
    getActiveTool: function() {
        if (!activeTool) {
            activeTool = defaultTool;
        }

        return activeTool;
    },
    setDefaultTool: function(tool) {
        defaultTool = tool;
    },
    getDefaultTool: function() {
        return defaultTool;
    }

};
<commit_msg>LT-359: Hide handles when Temp measurement tool is not active<commit_after>import { OHIF } from 'meteor/ohif:core';

var activeTool = 'wwwc';
var defaultTool = 'wwwc';

var tools = {};

var toolDefaultStates = {
    activate: [],
    deactivate: ['length', 'angle', 'annotate', 'ellipticalRoi', 'rectangleRoi'],
    enable: [],
    disable: [],
    disabledToolButtons: []
};

var initialized = false;

function configureTools() {

    // Get Cornerstone Tools
    const { panMultiTouch, textStyle, toolStyle, toolColors, length,
            bidirectional, arrowAnnotate, zoom, ellipticalRoi, nonTarget } = cornerstoneTools;

    // Set the configuration for the multitouch pan tool
    const multiTouchPanConfig = {
        testPointers: function(eventData) {
            return (eventData.numPointers >= 3);
        }
    };
    panMultiTouch.setConfiguration(multiTouchPanConfig);

    // Set text box background color
    textStyle.setBackgroundColor('transparent');

    // Set the tool font and font size
    // context.font = "[style] [variant] [weight] [size]/[line height] [font family]";
    const fontFamily = 'Roboto, OpenSans, HelveticaNeue-Light, Helvetica Neue Light, Helvetica Neue, Helvetica, Arial, Lucida Grande, sans-serif';
    textStyle.setFont('15px ' + fontFamily);

    // Set the tool width
    toolStyle.setToolWidth(2);

    // Set color for inactive tools
    toolColors.setToolColor('rgb(255, 255, 0)');

    // Set color for active tools
    toolColors.setActiveColor('rgb(0, 255, 0)');

    // Set shadow configuration for length and bidirectional text boxes
    const shadowConfig = {
        shadow: false,
        shadowColor: '#000000',
        shadowOffsetX: 0,
        shadowOffsetY: 0
    };

    // Get some tools config to not override them
    const lengthConfig = length.getConfiguration();
    const bidirectionalConfig = bidirectional.getConfiguration();
    const ellipticalRoiConfig = ellipticalRoi.getConfiguration();
    const nonTargetConfig = nonTarget.getConfiguration();

    // Add shadow to length tool
    length.setConfiguration({
        ...lengthConfig,
        ...shadowConfig,
        drawHandlesOnHover: true
    });

    // Add shadow to length tool
    bidirectional.setConfiguration({
        ...bidirectionalConfig,
        ...shadowConfig
    });

    // Add shadow to length tool
    ellipticalRoi.setConfiguration({
        ...ellipticalRoiConfig,
        ...shadowConfig
    });

     // Add shadow to non target tool
    nonTarget.setConfiguration({
        ...nonTargetConfig,
        ...shadowConfig
    });

    // Set the configuration values for the text annotation (Arrow) tool
    const annotateConfig = {
        getTextCallback: getAnnotationTextCallback,
        changeTextCallback: changeAnnotationTextCallback,
        drawHandles: false,
        arrowFirst: true
    };
    arrowAnnotate.setConfiguration(annotateConfig);

    const zoomConfig = {
        minScale: 0.05,
        maxScale: 10
    };
    zoom.setConfiguration(zoomConfig);
}

toolManager = {
    init: function() {
        toolManager.addTool('wwwc', {
            mouse: cornerstoneTools.wwwc,
            touch: cornerstoneTools.wwwcTouchDrag
        });
        toolManager.addTool('zoom', {
            mouse: cornerstoneTools.zoom,
            touch: cornerstoneTools.zoomTouchDrag
        });
        toolManager.addTool('wwwcRegion', {
            mouse: cornerstoneTools.wwwcRegion,
            touch: cornerstoneTools.wwwcRegionTouch
        });
        toolManager.addTool('dragProbe', {
            mouse: cornerstoneTools.dragProbe,
            touch: cornerstoneTools.dragProbeTouch
        });
        toolManager.addTool('pan', {
            mouse: cornerstoneTools.pan,
            touch: cornerstoneTools.panTouchDrag
        });
        toolManager.addTool('stackScroll', {
            mouse: cornerstoneTools.stackScroll,
            touch: cornerstoneTools.stackScrollTouchDrag
        });
        toolManager.addTool('length', {
            mouse: cornerstoneTools.length,
            touch: cornerstoneTools.lengthTouch
        });
        toolManager.addTool('angle', {
            mouse: cornerstoneTools.simpleAngle,
            touch: cornerstoneTools.simpleAngleTouch
        });
        toolManager.addTool('magnify', {
            mouse: cornerstoneTools.magnify,
            touch: cornerstoneTools.magnifyTouchDrag
        });
        toolManager.addTool('ellipticalRoi', {
            mouse: cornerstoneTools.ellipticalRoi,
            touch: cornerstoneTools.ellipticalRoiTouch
        });
        toolManager.addTool('rectangleRoi', {
            mouse: cornerstoneTools.rectangleRoi,
            touch: cornerstoneTools.rectangleRoiTouch
        });
        toolManager.addTool('annotate', {
            mouse: cornerstoneTools.arrowAnnotate,
            touch: cornerstoneTools.arrowAnnotateTouch
        });

        toolManager.addTool('rotate', {
            mouse: cornerstoneTools.rotate,
            touch: cornerstoneTools.rotateTouchDrag
        });

        if (OHIF.viewer.defaultTool) {
            activeTool = OHIF.viewer.defaultTool;
        }

        configureTools();
        initialized = true;
    },
    addTool: function(name, base) {
        tools[name] = base;
    },
    getTools: function() {
        return tools;
    },
    setToolDefaultStates: function(states) {
        toolDefaultStates = states;
    },
    getToolDefaultStates: function() {
        return toolDefaultStates;
    },
    setActiveToolForElement: function(tool, element) {
        var canvases = $(element).find('canvas');
        if (element.classList.contains('empty') || !canvases.length) {
            return;
        }

        // First, deactivate the current active tool
        tools[activeTool].mouse.deactivate(element, 1);

        if (tools[activeTool].touch) {
            tools[activeTool].touch.deactivate(element);
        }

        // Enable tools based on their default states
        Object.keys(toolDefaultStates).forEach(function(action) {
            var relevantTools = toolDefaultStates[action];
            if (!relevantTools || !relevantTools.length || action === 'disabledToolButtons') {
                return;
            }
            relevantTools.forEach(function(toolType) {
                // the currently active tool has already been deactivated and can be skipped
                if (action === 'deactivate' && toolType === activeTool) {
                    return;
                }
                tools[toolType].mouse[action](
                    element,
                    (action === 'activate' || action === 'deactivate' ? 1 : void 0)
                );
                tools[toolType].touch[action](element);
            });
        });

        // Get the stack toolData
        var toolData = cornerstoneTools.getToolState(element, 'stack');
        if (!toolData || !toolData.data || !toolData.data.length) {
            return;
        }

        // Get the imageIds for this element
        var imageIds = toolData.data[0].imageIds;

        // Deactivate all the middle mouse, right click, and scroll wheel tools
        cornerstoneTools.pan.deactivate(element);
        cornerstoneTools.zoom.deactivate(element);
        cornerstoneTools.zoomWheel.deactivate(element);
        cornerstoneTools.stackScrollWheel.deactivate(element);

        // Reactivate the relevant scrollwheel tool for this element
        if (imageIds.length > 1) {
            // scroll is the default tool for middle mouse wheel for stacks
            cornerstoneTools.stackScrollWheel.activate(element);
        } else {
            // zoom is the default tool for middle mouse wheel for single images (non stacks)
            cornerstoneTools.zoomWheel.activate(element);
        }

        // This block ensures that the middle mouse and scroll tools keep working
        if (tool === 'pan') {
            cornerstoneTools.pan.activate(element, 3); // 3 means left mouse button and middle mouse button
            cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button
        } else if (tool === 'zoom') {
            cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
            cornerstoneTools.zoom.activate(element, 5); // 5 means left mouse button and right mouse button
        } else {
            // Reactivate the middle mouse and right click tools
            cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
            cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button

            // Activate the chosen tool
            tools[tool].mouse.activate(element, 1);
        }

        if (tools[tool].touch) {
            tools[tool].touch.activate(element);
        }

        cornerstoneTools.zoomTouchPinch.activate(element);
        cornerstoneTools.panMultiTouch.activate(element);
    },
    setActiveTool: function(tool, elements) {
        if (!initialized) {
            toolManager.init();
        }

        if (!tool) {
            tool = defaultTool;
        }

        if (!elements || !elements.length) {
            elements = $('.imageViewerViewport');
        }

        // Otherwise, set the active tool for all viewport elements
        $(elements).each(function(index, element) {
            toolManager.setActiveToolForElement(tool, element);
        });
        activeTool = tool;

        // Store the active tool in the session in order to enable reactivity
        Session.set('ToolManagerActiveTool', tool);
    },
    getActiveTool: function() {
        if (!activeTool) {
            activeTool = defaultTool;
        }

        return activeTool;
    },
    setDefaultTool: function(tool) {
        defaultTool = tool;
    },
    getDefaultTool: function() {
        return defaultTool;
    }

};
<|endoftext|>


<commit_before>var heap_metrics = require( './../build/Release/heap_metrics.node' );
var assert = require('assert');

function consume_heap()
{
    var garbage = [];

    for (var i=0; i<1000; i++)
    {
        garbage.push("this is a long string to consume heap memory... lets make it a little longer... and longer still");

    }
}

describe('DumpHeapMetrics', function(){
  it('should return true', function(){
    for(var i=0;i<100;i++){
        consume_heap();
    }
    assert(heap_metrics.DumpHeapMetrics());
  });
})<commit_msg>more heap usage<commit_after>var heap_metrics = require( './../build/Release/heap_metrics.node' );
var assert = require('assert');

function consume_heap()
{
    var garbage = [];

    for (var i=0; i<1000; i++)
    {
        garbage.push("this is a long string to consume heap memory... lets make it a little longer... and longer still... why stop now");

    }
}

describe('DumpHeapMetrics', function(){
  it('should return true', function(){
    for(var i=0;i<100;i++){
        consume_heap();
    }
    assert(heap_metrics.DumpHeapMetrics());
  });
})<|endoftext|>