<commit_before>'use strict';
/**
 * GhostText for Chrome lib.
 *
 * @licence The MIT License (MIT)
 * @author Guido Krömer <mail 64 cacodaemon 46 de>
 * @author Federico Brigante
 */
var GhostText = {
    /**
     * @type {number} The GhostText protocol version.
     * @private
     * @const
     */
    protocolVersion: 1,

    /**
     * Chrome tab id to WebSocket mapping.
     * @type {Array<WebSocket>}
     * @private
     * @static
     */
    connections: {},

    /**
     * Call the callback with the current tab id (async)
     *
     * @param  {function} callback The function to call with the id
     */
    inCurrentTab: function (callback) {
        chrome.tabs.query({
            active: true,
            currentWindow: true
        }, function(tabs){
            callback(tabs[0].id);
        });
    },

    /**
     * Gets or sets the GhostText server main port.
     *
     * @param {number} port The TCP port number.
     * @returns {number} The TCP port number.
     * @public
     * @static
     */
    serverPort: function(port) {
        if (!port) {
            return localStorage.getItem('server-port-v1') || 4001;
        }

        localStorage.setItem('server-port-v1', port);
    },

    /**
     * Make sure that content scripts and styles are only loaded once
     *
     * @param  {number}   tabId    The tab in which to inject the content scripts
     * @param  {function} callback The function to call after the scripts have been loaded
     */
    loadContentJs: function (tabId, callback) {
        chrome.tabs.executeScript(tabId, {
            code: '!!window.GhostTextContent'//check if it's already loaded
        }, function (hasContentJs) {
            if (hasContentJs[0]) {
                callback();
            } else {
                chrome.tabs.insertCSS(tabId,     { file: 'vendor/humane-ghosttext.css' });
                chrome.tabs.executeScript(tabId, { file: 'vendor/humane-ghosttext.min.js' });
                chrome.tabs.executeScript(tabId, { file: 'scripts/input-area.js' });
                chrome.tabs.executeScript(tabId, { file: 'scripts/content.js' }, callback);
            }
        });
    },

    /**
     * Handles incoming connections from the content script.
     * Has to be started in the background script.
     * @public
     * @static
     */
    connectionHandler: function () {
        chrome.runtime.onConnect.addListener(GhostText.connectionHandlerOnConnect);
        chrome.runtime.onMessage.addListener(GhostText.messageHandler);
        chrome.browserAction.onClicked.addListener(GhostText.toggleCurrentTab);
        chrome.commands.onCommand.addListener(function (command) {
            if (command === 'toggle') {
                GhostText.toggleCurrentTab();
            }
        });
    },

    /**
     * Enable or disable GT in the current tab
     * @public
     * @static
     */
    toggleCurrentTab: function () {
        GhostText.inCurrentTab(function (tabId) {
            GhostText.loadContentJs(tabId, function () {
                if (GhostText.connections[tabId]) {
                    GhostText.closeConnection(tabId);
                } else {
                    chrome.tabs.sendMessage(tabId, {
                        action: 'select-field',
                        tabId: tabId
                    });
                }
            });
        });
    },

    /**
     * Handles incoming chrome messages, used by the connectionHandler.
     *
     * @param {*} port
     * @see https://developer.chrome.com/extensions/runtime#type-Port
     * @private
     */
    connectionHandlerOnConnect: function(port) {
        if (port.name !== 'GhostText') {
            return;
        }

        port.onMessage.addListener(function(msg) {
            /** @type {string} The chrome tab id. */
            var tabId = msg.tabId;

            if (GhostText.connections[tabId] && GhostText.connections[tabId].readyState === 1) { // 1 - connection established
                GhostText.connections[tabId].send(msg.change);

                return;
            }

            fetch('http://localhost:' + GhostText.serverPort())
            .then(r => r.json())
            .then(({ProtocolVersion, WebSocketPort}) => {
                if (!GhostText.checkProtocolVersion(ProtocolVersion)) {
                    return;
                }

                try {
                    GhostText.connections[tabId] = new WebSocket('ws://localhost:' + WebSocketPort);
                } catch (e) {
                    GhostText.errorHandler(e);

                    return;
                }

                GhostText.connections[tabId].onopen = function () {
                    chrome.browserAction.setBadgeText({
                        text: /OS X/i.test(navigator.userAgent)?'✓':'ON',
                        tabId: tabId
                    });
                    chrome.browserAction.setBadgeBackgroundColor({
                        color: '#008040',
                        tabId: tabId
                    });
                    GhostText.connections[tabId].send(msg.change);
                    console.log('Connection: opened');

                    chrome.tabs.sendMessage(tabId, {
                        action: 'enable-field',
                        tabId: tabId
                    });
                };

                GhostText.connections[tabId].onclose = function () {
                    GhostText.closeConnection(tabId);
                };

                GhostText.connections[tabId].onerror = function (event) {
                    GhostText.closeConnection(tabId);
                    console.log('Connection: error:', event);
                    GhostText.errorHandler(event);
                };

                GhostText.connections[tabId].onmessage = function (event) {
                    port.postMessage({
                        tabId: tabId,
                        change: event.data
                    });
                };
            }).fail(GhostText.errorHandler);
        });
    },

    /**
     * Closes a WebSocket connected to a tab.
     *
     * @param {number} tabId
     * @returns {boolean}
     * @private
     * @static
     */
    closeConnection: function(tabId) {
        if (!GhostText.connections[tabId]) {
            return false;
        }

        if (GhostText.connections[tabId].readyState !== 3) { // 3 - connection closed or could not open
            try {
                GhostText.connections[tabId].close();
            } catch (e) {
                console.log('Connection: error during closing:', e);
            }
        }
        delete GhostText.connections[tabId];
        console.log('Connection: closed');

        try { //inform tab that the connection was closed
            chrome.tabs.sendMessage(tabId, {
                action: 'disable-field',
                tabId: tabId
            });

            chrome.browserAction.setBadgeText({
                text: '',
                tabId: tabId
            });

            // we need to query it again because windowId might have changed in the meanwhile
            chrome.tabs.get(tabId, function(tab){

                //focus window back
                chrome.windows.update(tab.windowId, {
                    focused: true
                });

                //focus tab
                chrome.tabs.update(tabId, {
                    active: true
                });
            });

        } catch (e) {
            //tab might have been closed already; don't know how to detect it first.
        }

        return true;
    },

    /**
     * A general error handler.
     *
     * @param {Error} e
     * @private
     * @static
     */
    errorHandler: function(e) {
        if(e && (e.target && e.target.readyState === 3) || e.status === 404 || e.status === 0) {
            GhostText.notifyUser('error',
                'Connection error.',
                '\nMake sure that Sublime Text is open and has GhostText installed.',
                '\nTry closing and opening it and try again.',
                '\nMake sure that the port matches (4001 is the default).',
                '\nSee if there are any errors in Sublime Text\'s console.'
            );
        }
    },

    /**
     * Prints a error message if the server's protocol version differs from the clients.
     *
     * @param {number} version The protocol version.
     * @private
     * @static
     */
    checkProtocolVersion: function(version) {
        if (version === GhostText.protocolVersion) {
            return true;
        }

        GhostText.notifyUser('error', 'Can\'t connect to this GhostText server, the server\'s protocol version is', version, 'the client\'s protocol version is:', GhostText.protocolVersion);

        return false;
    },

    /**
     * Handles messages sent from other parts of the extension
     *
     * @param  {object} request The request object passed by Chrome
     */
    messageHandler: function (request) {
        if (!request || !request.action) {
            return;
        }
        switch (request.action) {
            case 'close-connection':
                GhostText.closeConnection(request.tabId);
                break;
        }
    },

    /**
     * Pipe messages to the document thought content.js
     *
     * @param  {string}              type      The type of message: error|info
     * @param  {...(number|string)}  [message]   Message to display
     * @static
     */
    notifyUser: function (type, message) {
        message = [].slice.call(arguments, 1).join(' ');//get the rest parameters and join them
        GhostText.inCurrentTab(function (tabId) {
            chrome.tabs.sendMessage(tabId, {
                tabId: tabId,
                type: type,
                action: 'notify',
                message: message
            });
        });
    }
};
<commit_msg>Make sure that version is a float<commit_after>'use strict';
/**
 * GhostText for Chrome lib.
 *
 * @licence The MIT License (MIT)
 * @author Guido Krömer <mail 64 cacodaemon 46 de>
 * @author Federico Brigante
 */
var GhostText = {
    /**
     * @type {number} The GhostText protocol version.
     * @private
     * @const
     */
    protocolVersion: 1,

    /**
     * Chrome tab id to WebSocket mapping.
     * @type {Array<WebSocket>}
     * @private
     * @static
     */
    connections: {},

    /**
     * Call the callback with the current tab id (async)
     *
     * @param  {function} callback The function to call with the id
     */
    inCurrentTab: function (callback) {
        chrome.tabs.query({
            active: true,
            currentWindow: true
        }, function(tabs){
            callback(tabs[0].id);
        });
    },

    /**
     * Gets or sets the GhostText server main port.
     *
     * @param {number} port The TCP port number.
     * @returns {number} The TCP port number.
     * @public
     * @static
     */
    serverPort: function(port) {
        if (!port) {
            return localStorage.getItem('server-port-v1') || 4001;
        }

        localStorage.setItem('server-port-v1', port);
    },

    /**
     * Make sure that content scripts and styles are only loaded once
     *
     * @param  {number}   tabId    The tab in which to inject the content scripts
     * @param  {function} callback The function to call after the scripts have been loaded
     */
    loadContentJs: function (tabId, callback) {
        chrome.tabs.executeScript(tabId, {
            code: '!!window.GhostTextContent'//check if it's already loaded
        }, function (hasContentJs) {
            if (hasContentJs[0]) {
                callback();
            } else {
                chrome.tabs.insertCSS(tabId,     { file: 'vendor/humane-ghosttext.css' });
                chrome.tabs.executeScript(tabId, { file: 'vendor/humane-ghosttext.min.js' });
                chrome.tabs.executeScript(tabId, { file: 'scripts/input-area.js' });
                chrome.tabs.executeScript(tabId, { file: 'scripts/content.js' }, callback);
            }
        });
    },

    /**
     * Handles incoming connections from the content script.
     * Has to be started in the background script.
     * @public
     * @static
     */
    connectionHandler: function () {
        chrome.runtime.onConnect.addListener(GhostText.connectionHandlerOnConnect);
        chrome.runtime.onMessage.addListener(GhostText.messageHandler);
        chrome.browserAction.onClicked.addListener(GhostText.toggleCurrentTab);
        chrome.commands.onCommand.addListener(function (command) {
            if (command === 'toggle') {
                GhostText.toggleCurrentTab();
            }
        });
    },

    /**
     * Enable or disable GT in the current tab
     * @public
     * @static
     */
    toggleCurrentTab: function () {
        GhostText.inCurrentTab(function (tabId) {
            GhostText.loadContentJs(tabId, function () {
                if (GhostText.connections[tabId]) {
                    GhostText.closeConnection(tabId);
                } else {
                    chrome.tabs.sendMessage(tabId, {
                        action: 'select-field',
                        tabId: tabId
                    });
                }
            });
        });
    },

    /**
     * Handles incoming chrome messages, used by the connectionHandler.
     *
     * @param {*} port
     * @see https://developer.chrome.com/extensions/runtime#type-Port
     * @private
     */
    connectionHandlerOnConnect: function(port) {
        if (port.name !== 'GhostText') {
            return;
        }

        port.onMessage.addListener(function(msg) {
            /** @type {string} The chrome tab id. */
            var tabId = msg.tabId;

            if (GhostText.connections[tabId] && GhostText.connections[tabId].readyState === 1) { // 1 - connection established
                GhostText.connections[tabId].send(msg.change);

                return;
            }

            fetch('http://localhost:' + GhostText.serverPort())
            .then(r => r.json())
            .then(({ProtocolVersion, WebSocketPort}) => {
                if (!GhostText.checkProtocolVersion(ProtocolVersion)) {
                    return;
                }

                try {
                    GhostText.connections[tabId] = new WebSocket('ws://localhost:' + WebSocketPort);
                } catch (e) {
                    GhostText.errorHandler(e);

                    return;
                }

                GhostText.connections[tabId].onopen = function () {
                    chrome.browserAction.setBadgeText({
                        text: /OS X/i.test(navigator.userAgent)?'✓':'ON',
                        tabId: tabId
                    });
                    chrome.browserAction.setBadgeBackgroundColor({
                        color: '#008040',
                        tabId: tabId
                    });
                    GhostText.connections[tabId].send(msg.change);
                    console.log('Connection: opened');

                    chrome.tabs.sendMessage(tabId, {
                        action: 'enable-field',
                        tabId: tabId
                    });
                };

                GhostText.connections[tabId].onclose = function () {
                    GhostText.closeConnection(tabId);
                };

                GhostText.connections[tabId].onerror = function (event) {
                    GhostText.closeConnection(tabId);
                    console.log('Connection: error:', event);
                    GhostText.errorHandler(event);
                };

                GhostText.connections[tabId].onmessage = function (event) {
                    port.postMessage({
                        tabId: tabId,
                        change: event.data
                    });
                };
            }).fail(GhostText.errorHandler);
        });
    },

    /**
     * Closes a WebSocket connected to a tab.
     *
     * @param {number} tabId
     * @returns {boolean}
     * @private
     * @static
     */
    closeConnection: function(tabId) {
        if (!GhostText.connections[tabId]) {
            return false;
        }

        if (GhostText.connections[tabId].readyState !== 3) { // 3 - connection closed or could not open
            try {
                GhostText.connections[tabId].close();
            } catch (e) {
                console.log('Connection: error during closing:', e);
            }
        }
        delete GhostText.connections[tabId];
        console.log('Connection: closed');

        try { //inform tab that the connection was closed
            chrome.tabs.sendMessage(tabId, {
                action: 'disable-field',
                tabId: tabId
            });

            chrome.browserAction.setBadgeText({
                text: '',
                tabId: tabId
            });

            // we need to query it again because windowId might have changed in the meanwhile
            chrome.tabs.get(tabId, function(tab){

                //focus window back
                chrome.windows.update(tab.windowId, {
                    focused: true
                });

                //focus tab
                chrome.tabs.update(tabId, {
                    active: true
                });
            });

        } catch (e) {
            //tab might have been closed already; don't know how to detect it first.
        }

        return true;
    },

    /**
     * A general error handler.
     *
     * @param {Error} e
     * @private
     * @static
     */
    errorHandler: function(e) {
        if(e && (e.target && e.target.readyState === 3) || e.status === 404 || e.status === 0) {
            GhostText.notifyUser('error',
                'Connection error.',
                '\nMake sure that Sublime Text is open and has GhostText installed.',
                '\nTry closing and opening it and try again.',
                '\nMake sure that the port matches (4001 is the default).',
                '\nSee if there are any errors in Sublime Text\'s console.'
            );
        }
    },

    /**
     * Prints a error message if the server's protocol version differs from the clients.
     *
     * @param {number} version The protocol version.
     * @private
     * @static
     */
    checkProtocolVersion: function(version) {
        version = parseFloat(version);
        if (version === GhostText.protocolVersion) {
            return true;
        }

        GhostText.notifyUser('error', 'Can\'t connect to this GhostText server, the server\'s protocol version is', version, 'the client\'s protocol version is:', GhostText.protocolVersion);

        return false;
    },

    /**
     * Handles messages sent from other parts of the extension
     *
     * @param  {object} request The request object passed by Chrome
     */
    messageHandler: function (request) {
        if (!request || !request.action) {
            return;
        }
        switch (request.action) {
            case 'close-connection':
                GhostText.closeConnection(request.tabId);
                break;
        }
    },

    /**
     * Pipe messages to the document thought content.js
     *
     * @param  {string}              type      The type of message: error|info
     * @param  {...(number|string)}  [message]   Message to display
     * @static
     */
    notifyUser: function (type, message) {
        message = [].slice.call(arguments, 1).join(' ');//get the rest parameters and join them
        GhostText.inCurrentTab(function (tabId) {
            chrome.tabs.sendMessage(tabId, {
                tabId: tabId,
                type: type,
                action: 'notify',
                message: message
            });
        });
    }
};
<|endoftext|>


<commit_before>module.exports = function (overlaysCollection, mapDefModel, userModel) {
  var overlays = overlaysCollection.pluck('type');
  var canRemoveLogo = userModel.get('actions').remove_logo;

  return [{
    setting: 'search',
    label: _t('editor.settings.preview.options.elements.search'),
    related: 'overlays',
    disabled: false,
    enabler: overlays.indexOf('search') > 0
  },
  {
    setting: 'zoom',
    label: _t('editor.settings.preview.options.elements.zoom'),
    related: 'overlays',
    disabled: false,
    enabler: overlays.indexOf('zoom') > 0
  },
  {
    setting: 'logo',
    label: _t('editor.settings.preview.options.elements.logo'),
    related: 'overlays',
    disabled: !canRemoveLogo,
    enabler: overlays.indexOf('logo') > 0
  },
  {
    setting: 'legends',
    label: _t('editor.settings.preview.options.elements.legends'),
    related: 'map',
    disabled: false,
    enabler: mapDefModel.get('legends') === true
  },
  {
    setting: 'layer_selector',
    label: _t('editor.settings.preview.options.elements.layer_selector'),
    related: 'map',
    disabled: false,
    enabler: mapDefModel.get('layer_selector') === true
  },
  {
    setting: 'dashboard_menu',
    label: _t('editor.settings.preview.options.elements.dashboard_menu'),
    related: 'map',
    disabled: false,
    enabler: mapDefModel.get('dashboard_menu') === true
  },
  {
    setting: 'scrollwheel',
    label: _t('editor.settings.preview.options.elements.scrollwheel'),
    related: 'map',
    disabled: false,
    enabler: mapDefModel.get('scrollwheel') === true
  }];
};
<commit_msg>Create hidden option for map settings<commit_after>module.exports = function (overlaysCollection, mapDefModel, userModel) {
  var overlays = overlaysCollection.pluck('type');
  var canRemoveLogo = userModel.get('actions').remove_logo;

  return [{
    setting: 'search',
    label: _t('editor.settings.preview.options.elements.search'),
    related: 'overlays',
    disabled: false,
    enabler: overlays.indexOf('search') > 0
  },
  {
    setting: 'zoom',
    label: _t('editor.settings.preview.options.elements.zoom'),
    related: 'overlays',
    disabled: false,
    enabler: overlays.indexOf('zoom') > 0
  },
  {
    setting: 'logo',
    label: _t('editor.settings.preview.options.elements.logo'),
    related: 'overlays',
    disabled: false,
    hidden: !canRemoveLogo,
    enabler: overlays.indexOf('logo') > 0
  },
  {
    setting: 'legends',
    label: _t('editor.settings.preview.options.elements.legends'),
    related: 'map',
    disabled: false,
    enabler: mapDefModel.get('legends') === true
  },
  {
    setting: 'layer_selector',
    label: _t('editor.settings.preview.options.elements.layer_selector'),
    related: 'map',
    disabled: false,
    enabler: mapDefModel.get('layer_selector') === true
  },
  {
    setting: 'dashboard_menu',
    label: _t('editor.settings.preview.options.elements.dashboard_menu'),
    related: 'map',
    disabled: false,
    enabler: mapDefModel.get('dashboard_menu') === true
  },
  {
    setting: 'scrollwheel',
    label: _t('editor.settings.preview.options.elements.scrollwheel'),
    related: 'map',
    disabled: false,
    enabler: mapDefModel.get('scrollwheel') === true
  }];
};
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

//------------------------------------------------------------------------------
// The logger module exports the following properties/functions:
//
// LOG                          - constant for the level LOG
// ERROR                        - constant for the level ERROR
// WARN                         - constant for the level WARN
// INFO                         - constant for the level INFO
// DEBUG                        - constant for the level DEBUG
// logLevel()                   - returns current log level
// logLevel(value)              - sets and returns a new log level
// useConsole()                 - returns whether logger is using console
// useConsole(value)            - sets and returns whether logger is using console
// log(message,...)             - logs a message at level LOG
// error(message,...)           - logs a message at level ERROR
// warn(message,...)            - logs a message at level WARN
// info(message,...)            - logs a message at level INFO
// debug(message,...)           - logs a message at level DEBUG
// logLevel(level,message,...)  - logs a message specified level
//
//------------------------------------------------------------------------------

var logger = exports;

var exec    = require('cordova/exec');
var utils   = require('cordova/utils');

var UseConsole   = false;
var UseLogger    = true;
var Queued       = [];
var DeviceReady  = false;
var CurrentLevel;

var originalConsole = console;

/**
 * Logging levels
 */

var Levels = [
    "LOG",
    "ERROR",
    "WARN",
    "INFO",
    "DEBUG"
];

/*
 * add the logging levels to the logger object and
 * to a separate levelsMap object for testing
 */

var LevelsMap = {};
for (var i=0; i<Levels.length; i++) {
    var level = Levels[i];
    LevelsMap[level] = i;
    logger[level]    = level;
}

CurrentLevel = LevelsMap.WARN;

/**
 * Getter/Setter for the logging level
 *
 * Returns the current logging level.
 *
 * When a value is passed, sets the logging level to that value.
 * The values should be one of the following constants:
 *    logger.LOG
 *    logger.ERROR
 *    logger.WARN
 *    logger.INFO
 *    logger.DEBUG
 *
 * The value used determines which messages get printed.  The logging
 * values above are in order, and only messages logged at the logging
 * level or above will actually be displayed to the user.  E.g., the
 * default level is WARN, so only messages logged with LOG, ERROR, or
 * WARN will be displayed; INFO and DEBUG messages will be ignored.
 */
logger.level = function (value) {
    if (arguments.length) {
        if (LevelsMap[value] === null) {
            throw new Error("invalid logging level: " + value);
        }
        CurrentLevel = LevelsMap[value];
    }

    return Levels[CurrentLevel];
};

/**
 * Getter/Setter for the useConsole functionality
 *
 * When useConsole is true, the logger will log via the
 * browser 'console' object.
 */
logger.useConsole = function (value) {
    if (arguments.length) UseConsole = !!value;

    if (UseConsole) {
        if (typeof console == "undefined") {
            throw new Error("global console object is not defined");
        }

        if (typeof console.log != "function") {
            throw new Error("global console object does not have a log function");
        }

        if (typeof console.useLogger == "function") {
            if (console.useLogger()) {
                throw new Error("console and logger are too intertwingly");
            }
        }
    }

    return UseConsole;
};

/**
 * Getter/Setter for the useLogger functionality
 *
 * When useLogger is true, the logger will log via the
 * native Logger plugin.
 */
logger.useLogger = function (value) {
    // Enforce boolean
    if (arguments.length) UseLogger = !!value;
    return UseLogger;
};

/**
 * Logs a message at the LOG level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.log   = function(message) { logWithArgs("LOG",   arguments); };

/**
 * Logs a message at the ERROR level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.error = function(message) { logWithArgs("ERROR", arguments); };

/**
 * Logs a message at the WARN level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.warn  = function(message) { logWithArgs("WARN",  arguments); };

/**
 * Logs a message at the INFO level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.info  = function(message) { logWithArgs("INFO",  arguments); };

/**
 * Logs a message at the DEBUG level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.debug = function(message) { logWithArgs("DEBUG", arguments); };

// log at the specified level with args
function logWithArgs(level, args) {
    args = [level].concat([].slice.call(args));
    logger.logLevel.apply(logger, args);
}

// return the correct formatString for an object
function formatStringForMessage(message) {
    return (typeof message === "string") ? "" : "%o";
}

/**
 * Logs a message at the specified level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.logLevel = function(level /* , ... */) {
    // format the message with the parameters
    var formatArgs = [].slice.call(arguments, 1);
    formatArgs.unshift(formatStringForMessage(formatArgs[0])); // add formatString
    var message    = logger.format.apply(logger.format, formatArgs);

    if (LevelsMap[level] === null) {
        throw new Error("invalid logging level: " + level);
    }

    if (LevelsMap[level] > CurrentLevel) return;

    // queue the message if not yet at deviceready
    if (!DeviceReady && !UseConsole) {
        Queued.push([level, message]);
        return;
    }

    // Log using the native logger if that is enabled
    if (UseLogger) {
        exec(null, null, "Console", "logLevel", [level, message]);
    }

    // Log using the console if that is enabled
    if (UseConsole) {
        // make sure console is not using logger
        if (console.useLogger()) {
            throw new Error("console and logger are too intertwingly");
        }

        // log to the console
        switch (level) {
            case logger.LOG:   originalConsole.log(message); break;
            case logger.ERROR: originalConsole.log("ERROR: " + message); break;
            case logger.WARN:  originalConsole.log("WARN: "  + message); break;
            case logger.INFO:  originalConsole.log("INFO: "  + message); break;
            case logger.DEBUG: originalConsole.log("DEBUG: " + message); break;
        }
    }
};

/**
 * Formats a string and arguments following it ala console.log()
 *
 * Any remaining arguments will be appended to the formatted string.
 *
 * for rationale, see FireBug's Console API:
 *    http://getfirebug.com/wiki/index.php/Console_API
 */
logger.format = function(formatString, args) {
    return __format(arguments[0], [].slice.call(arguments,1)).join(' ');
};

//------------------------------------------------------------------------------
/**
 * Formats a string and arguments following it ala vsprintf()
 *
 * format chars:
 *   %j - format arg as JSON
 *   %o - format arg as JSON
 *   %c - format arg as ''
 *   %% - replace with '%'
 * any other char following % will format it's
 * arg via toString().
 *
 * Returns an array containing the formatted string and any remaining
 * arguments.
 */
function __format(formatString, args) {
    if (formatString === null || formatString === undefined) return [""];
    if (arguments.length == 1) return [formatString.toString()];

    if (typeof formatString != "string")
        formatString = formatString.toString();

    var pattern = /(.*?)%(.)(.*)/;
    var rest    = formatString;
    var result  = [];

    while (args.length) {
        var match = pattern.exec(rest);
        if (!match) break;

        var arg   = args.shift();
        rest = match[3];
        result.push(match[1]);

        if (match[2] == '%') {
            result.push('%');
            args.unshift(arg);
            continue;
        }

        result.push(__formatted(arg, match[2]));
    }

    result.push(rest);

    var remainingArgs = [].slice.call(args);
    remainingArgs.unshift(result.join(''));
    return remainingArgs;
}

function __formatted(object, formatChar) {

    try {
        switch(formatChar) {
            case 'j':
            case 'o': return JSON.stringify(object);
            case 'c': return '';
        }
    }
    catch (e) {
        return "error JSON.stringify()ing argument: " + e;
    }

    if ((object === null) || (object === undefined)) {
        return Object.prototype.toString.call(object);
    }

    return object.toString();
}

//------------------------------------------------------------------------------
// when deviceready fires, log queued messages
logger.__onDeviceReady = function() {
    if (DeviceReady) return;

    DeviceReady = true;

    for (var i=0; i<Queued.length; i++) {
        var messageArgs = Queued[i];
        logger.logLevel(messageArgs[0], messageArgs[1]);
    }

    Queued = null;
};

// add a deviceready event to log queued messages
document.addEventListener("deviceready", logger.__onDeviceReady, false);
<commit_msg>CB-5154 log formatting incorrectly to native<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

//------------------------------------------------------------------------------
// The logger module exports the following properties/functions:
//
// LOG                          - constant for the level LOG
// ERROR                        - constant for the level ERROR
// WARN                         - constant for the level WARN
// INFO                         - constant for the level INFO
// DEBUG                        - constant for the level DEBUG
// logLevel()                   - returns current log level
// logLevel(value)              - sets and returns a new log level
// useConsole()                 - returns whether logger is using console
// useConsole(value)            - sets and returns whether logger is using console
// log(message,...)             - logs a message at level LOG
// error(message,...)           - logs a message at level ERROR
// warn(message,...)            - logs a message at level WARN
// info(message,...)            - logs a message at level INFO
// debug(message,...)           - logs a message at level DEBUG
// logLevel(level,message,...)  - logs a message specified level
//
//------------------------------------------------------------------------------

var logger = exports;

var exec    = require('cordova/exec');
var utils   = require('cordova/utils');

var UseConsole   = false;
var UseLogger    = true;
var Queued       = [];
var DeviceReady  = false;
var CurrentLevel;

var originalConsole = console;

/**
 * Logging levels
 */

var Levels = [
    "LOG",
    "ERROR",
    "WARN",
    "INFO",
    "DEBUG"
];

/*
 * add the logging levels to the logger object and
 * to a separate levelsMap object for testing
 */

var LevelsMap = {};
for (var i=0; i<Levels.length; i++) {
    var level = Levels[i];
    LevelsMap[level] = i;
    logger[level]    = level;
}

CurrentLevel = LevelsMap.WARN;

/**
 * Getter/Setter for the logging level
 *
 * Returns the current logging level.
 *
 * When a value is passed, sets the logging level to that value.
 * The values should be one of the following constants:
 *    logger.LOG
 *    logger.ERROR
 *    logger.WARN
 *    logger.INFO
 *    logger.DEBUG
 *
 * The value used determines which messages get printed.  The logging
 * values above are in order, and only messages logged at the logging
 * level or above will actually be displayed to the user.  E.g., the
 * default level is WARN, so only messages logged with LOG, ERROR, or
 * WARN will be displayed; INFO and DEBUG messages will be ignored.
 */
logger.level = function (value) {
    if (arguments.length) {
        if (LevelsMap[value] === null) {
            throw new Error("invalid logging level: " + value);
        }
        CurrentLevel = LevelsMap[value];
    }

    return Levels[CurrentLevel];
};

/**
 * Getter/Setter for the useConsole functionality
 *
 * When useConsole is true, the logger will log via the
 * browser 'console' object.
 */
logger.useConsole = function (value) {
    if (arguments.length) UseConsole = !!value;

    if (UseConsole) {
        if (typeof console == "undefined") {
            throw new Error("global console object is not defined");
        }

        if (typeof console.log != "function") {
            throw new Error("global console object does not have a log function");
        }

        if (typeof console.useLogger == "function") {
            if (console.useLogger()) {
                throw new Error("console and logger are too intertwingly");
            }
        }
    }

    return UseConsole;
};

/**
 * Getter/Setter for the useLogger functionality
 *
 * When useLogger is true, the logger will log via the
 * native Logger plugin.
 */
logger.useLogger = function (value) {
    // Enforce boolean
    if (arguments.length) UseLogger = !!value;
    return UseLogger;
};

/**
 * Logs a message at the LOG level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.log   = function(message) { logWithArgs("LOG",   arguments); };

/**
 * Logs a message at the ERROR level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.error = function(message) { logWithArgs("ERROR", arguments); };

/**
 * Logs a message at the WARN level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.warn  = function(message) { logWithArgs("WARN",  arguments); };

/**
 * Logs a message at the INFO level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.info  = function(message) { logWithArgs("INFO",  arguments); };

/**
 * Logs a message at the DEBUG level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.debug = function(message) { logWithArgs("DEBUG", arguments); };

// log at the specified level with args
function logWithArgs(level, args) {
    args = [level].concat([].slice.call(args));
    logger.logLevel.apply(logger, args);
}

// return the correct formatString for an object
function formatStringForMessage(message) {
    return (typeof message === "string") ? "" : "%o";
}

/**
 * Logs a message at the specified level.
 *
 * Parameters passed after message are used applied to
 * the message with utils.format()
 */
logger.logLevel = function(level /* , ... */) {
    // format the message with the parameters
    var formatArgs = [].slice.call(arguments, 1);
    var fmtString = formatStringForMessage(formatArgs[0]);
    if (fmtString.length > 0){
        formatArgs.unshift(fmtString); // add formatString
    }

    var message    = logger.format.apply(logger.format, formatArgs);

    if (LevelsMap[level] === null) {
        throw new Error("invalid logging level: " + level);
    }

    if (LevelsMap[level] > CurrentLevel) return;

    // queue the message if not yet at deviceready
    if (!DeviceReady && !UseConsole) {
        Queued.push([level, message]);
        return;
    }

    // Log using the native logger if that is enabled
    if (UseLogger) {
        exec(null, null, "Console", "logLevel", [level, message]);
    }

    // Log using the console if that is enabled
    if (UseConsole) {
        // make sure console is not using logger
        if (console.useLogger()) {
            throw new Error("console and logger are too intertwingly");
        }

        // log to the console
        switch (level) {
            case logger.LOG:   originalConsole.log(message); break;
            case logger.ERROR: originalConsole.log("ERROR: " + message); break;
            case logger.WARN:  originalConsole.log("WARN: "  + message); break;
            case logger.INFO:  originalConsole.log("INFO: "  + message); break;
            case logger.DEBUG: originalConsole.log("DEBUG: " + message); break;
        }
    }
};

/**
 * Formats a string and arguments following it ala console.log()
 *
 * Any remaining arguments will be appended to the formatted string.
 *
 * for rationale, see FireBug's Console API:
 *    http://getfirebug.com/wiki/index.php/Console_API
 */
logger.format = function(formatString, args) {
    return __format(arguments[0], [].slice.call(arguments,1)).join(' ');
};

//------------------------------------------------------------------------------
/**
 * Formats a string and arguments following it ala vsprintf()
 *
 * format chars:
 *   %j - format arg as JSON
 *   %o - format arg as JSON
 *   %c - format arg as ''
 *   %% - replace with '%'
 * any other char following % will format it's
 * arg via toString().
 *
 * Returns an array containing the formatted string and any remaining
 * arguments.
 */
function __format(formatString, args) {
    if (formatString === null || formatString === undefined) return [""];
    if (arguments.length == 1) return [formatString.toString()];

    if (typeof formatString != "string")
        formatString = formatString.toString();

    var pattern = /(.*?)%(.)(.*)/;
    var rest    = formatString;
    var result  = [];

    while (args.length) {
        var match = pattern.exec(rest);
        if (!match) break;

        var arg   = args.shift();
        rest = match[3];
        result.push(match[1]);

        if (match[2] == '%') {
            result.push('%');
            args.unshift(arg);
            continue;
        }

        result.push(__formatted(arg, match[2]));
    }

    result.push(rest);

    var remainingArgs = [].slice.call(args);
    remainingArgs.unshift(result.join(''));
    return remainingArgs;
}

function __formatted(object, formatChar) {

    try {
        switch(formatChar) {
            case 'j':
            case 'o': return JSON.stringify(object);
            case 'c': return '';
        }
    }
    catch (e) {
        return "error JSON.stringify()ing argument: " + e;
    }

    if ((object === null) || (object === undefined)) {
        return Object.prototype.toString.call(object);
    }

    return object.toString();
}

//------------------------------------------------------------------------------
// when deviceready fires, log queued messages
logger.__onDeviceReady = function() {
    if (DeviceReady) return;

    DeviceReady = true;

    for (var i=0; i<Queued.length; i++) {
        var messageArgs = Queued[i];
        logger.logLevel(messageArgs[0], messageArgs[1]);
    }

    Queued = null;
};

// add a deviceready event to log queued messages
document.addEventListener("deviceready", logger.__onDeviceReady, false);
<|endoftext|>


<commit_before>const _ = require('underscore');
const Backbone = require('backbone');
const UserUrlModel = require('dashboard/data/user-url-model');

const UserModel = Backbone.Model.extend({
  urlRoot: '/api/v1/users',

  defaults: {
    avatar_url: 'http://cartodb.s3.amazonaws.com/static/public_dashboard_default_avatar.png',
    username: ''
  },

  initialize: function (attrs, opts) {
    debugger;
    attrs = attrs || {};
    opts = opts || {};
    this.tables = [];
    // Removing avatar_url attribute if it comes as null
    // Due to a Backbone Model constructor uses _.extends
    // instead of _.defaults
    if (this.get('avatar_url') === null) {
      this.set('avatar_url', this.defaults.avatar_url);
    }

    this.email = (typeof attrs.email !== 'undefined') ? attrs.email : '';

    if (opts.groups) {
      this.setGroups(opts.groups);
    }

    if (opts.organization) {
      this.setOrganization(opts.organization);
    }
  },

  setGroups: function (groups) {
    this.groups = groups;
  },

  setOrganization: function (organization) {
    this.organization = organization;

    if (this.groups) {
      this.groups.organization = organization;
    }
  },

  isInsideOrg: function () {
    if (this.organization) {
      return this.organization.id !== false || this.isOrgOwner();
    }
    return false;
  },

  isAuthUsernamePasswordEnabled: function () {
    if (this.organization) {
      return this.organization.get('auth_username_password_enabled');
    }
    return false;
  },

  isOrgOwner: function () {
    if (this.organization) {
      return this.organization.owner.get('id') === this.get('id');
    }
    return false;
  },

  isOrgAdmin: function () {
    if (this.organization) {
      return this.organization.isOrgAdmin(this);
    }
    return false;
  },

  isViewer: function () {
    return this.get('viewer') === true;
  },

  isBuilder: function () {
    return !this.isViewer();
  },

  nameOrUsername: function () {
    return this.fullName() || this.get('username');
  },

  fullName: function () {
    var name = this.get('name') || '';
    var lastName = this.get('last_name') || '';
    if (name || lastName) {
      return name + (name && lastName ? ' ' : '') + lastName;
    }
    return '';
  },

  renderData: function (currentUser) {
    var name = this.get('username');

    if (currentUser && currentUser.id === this.id) {
      name = _t('You');
    }

    return {
      username: name,
      avatar_url: this.get('avatar_url')
    };
  },

  hasCreateDatasetsFeature: function () {
    return this.isBuilder();
  },

  canCreateDatasets: function () {
    if (!this.get('remaining_byte_quota') || this.get('remaining_byte_quota') <= 0) {
      return false;
    }

    return this.hasCreateDatasetsFeature();
  },

  hasCreateMapsFeature: function () {
    return this.isBuilder();
  },

  canAddLayerTo: function (map) {
    if (!map || !map.layers || !map.layers.getDataLayers) {
      throw new Error('Map model is not defined or wrong');
    }
    var dataLayers = map.layers.getDataLayers();
    return dataLayers.length < this.getMaxLayers();
  },

  getMaxLayers: function () {
    return (this.get('limits') && this.get('limits').max_layers) || 5;
  },

  getMaxConcurrentImports: function () {
    return (this.get('limits') && this.get('limits').concurrent_imports) || 1;
  },

  featureEnabled: function (name) {
    var featureFlags = this.get('feature_flags');

    if (!featureFlags || featureFlags.length === 0 || !name) {
      return false;
    }

    return _.contains(featureFlags, name);
  },

  isCloseToLimits: function () {
    var quota = this.get('quota_in_bytes');
    var remainingQuota = this.get('remaining_byte_quota');

    return ((remainingQuota * 100) / quota) < 20;
  },

  isEnterprise: function () {
    return this.get('account_type').toLowerCase().indexOf('enterprise') != -1; // eslint-disable-line
  },

  getOrgName: function () {
    return this.isInsideOrg() ? this.getOrganization().get('name') : '';
  },

  getMaxLayersPerMap: function () {
    return this.get('max_layers') || 4;
  },

  canStartTrial: function () {
    return !this.isInsideOrg() && this.get('account_type') === 'FREE' && this.get('table_count') > 0;
  },

  canCreatePrivateDatasets: function () {
    var actions = this.get('actions');
    return actions && actions.private_tables;
  },

  equals: function (otherUser) {
    if (otherUser.get) {
      return this.get('id') === otherUser.get('id');
    }
  },

  viewUrl: function () {
    return new UserUrlModel({
      base_url: this.get('base_url'),
      is_org_admin: this.isOrgAdmin()
    });
  },

  upgradeContactEmail: function () {
    if (this.isInsideOrg()) {
      if (this.isOrgOwner()) {
        return 'enterprise-support@carto.com';
      } else {
        return this.organization.owner.get('email');
      }
    } else {
      return 'support@carto.com';
    }
  },

  usedQuotaPercentage: function () {
    return (this.get('db_size_in_bytes') * 100) / this.organization.get('available_quota_for_user');
  },

  assignedQuotaInRoundedMb: function () {
    return Math.floor(this.get('quota_in_bytes') / 1024 / 1024).toFixed(0);
  },

  assignedQuotaPercentage: function () {
    return (this.get('quota_in_bytes') * 100) / this.organization.get('available_quota_for_user');
  },

  getGoogleApiKey: function () {
    return this.get('google_maps_private_key');
  },

  hasGoogleMaps: function () {
    return !!this.getGoogleApiKey();
  },

  showGoogleApiKeys: function () {
    return this.hasGoogleMaps() && (!this.isInsideOrg() || this.isOrgOwner());
  },

  getSchema: function () {
    return this.isInsideOrg() ? this.get('username') : 'public';
  },

  getAuthToken: function () {
    return btoa(`${this.get('username')}:${this.get('api_key')}`);
  }
});

module.exports = UserModel;
<commit_msg>Remove unexpected debugger<commit_after>const _ = require('underscore');
const Backbone = require('backbone');
const UserUrlModel = require('dashboard/data/user-url-model');

const UserModel = Backbone.Model.extend({
  urlRoot: '/api/v1/users',

  defaults: {
    avatar_url: 'http://cartodb.s3.amazonaws.com/static/public_dashboard_default_avatar.png',
    username: ''
  },

  initialize: function (attrs, opts) {
    attrs = attrs || {};
    opts = opts || {};
    this.tables = [];
    // Removing avatar_url attribute if it comes as null
    // Due to a Backbone Model constructor uses _.extends
    // instead of _.defaults
    if (this.get('avatar_url') === null) {
      this.set('avatar_url', this.defaults.avatar_url);
    }

    this.email = (typeof attrs.email !== 'undefined') ? attrs.email : '';

    if (opts.groups) {
      this.setGroups(opts.groups);
    }

    if (opts.organization) {
      this.setOrganization(opts.organization);
    }
  },

  setGroups: function (groups) {
    this.groups = groups;
  },

  setOrganization: function (organization) {
    this.organization = organization;

    if (this.groups) {
      this.groups.organization = organization;
    }
  },

  isInsideOrg: function () {
    if (this.organization) {
      return this.organization.id !== false || this.isOrgOwner();
    }
    return false;
  },

  isAuthUsernamePasswordEnabled: function () {
    if (this.organization) {
      return this.organization.get('auth_username_password_enabled');
    }
    return false;
  },

  isOrgOwner: function () {
    if (this.organization) {
      return this.organization.owner.get('id') === this.get('id');
    }
    return false;
  },

  isOrgAdmin: function () {
    if (this.organization) {
      return this.organization.isOrgAdmin(this);
    }
    return false;
  },

  isViewer: function () {
    return this.get('viewer') === true;
  },

  isBuilder: function () {
    return !this.isViewer();
  },

  nameOrUsername: function () {
    return this.fullName() || this.get('username');
  },

  fullName: function () {
    var name = this.get('name') || '';
    var lastName = this.get('last_name') || '';
    if (name || lastName) {
      return name + (name && lastName ? ' ' : '') + lastName;
    }
    return '';
  },

  renderData: function (currentUser) {
    var name = this.get('username');

    if (currentUser && currentUser.id === this.id) {
      name = _t('You');
    }

    return {
      username: name,
      avatar_url: this.get('avatar_url')
    };
  },

  hasCreateDatasetsFeature: function () {
    return this.isBuilder();
  },

  canCreateDatasets: function () {
    if (!this.get('remaining_byte_quota') || this.get('remaining_byte_quota') <= 0) {
      return false;
    }

    return this.hasCreateDatasetsFeature();
  },

  hasCreateMapsFeature: function () {
    return this.isBuilder();
  },

  canAddLayerTo: function (map) {
    if (!map || !map.layers || !map.layers.getDataLayers) {
      throw new Error('Map model is not defined or wrong');
    }
    var dataLayers = map.layers.getDataLayers();
    return dataLayers.length < this.getMaxLayers();
  },

  getMaxLayers: function () {
    return (this.get('limits') && this.get('limits').max_layers) || 5;
  },

  getMaxConcurrentImports: function () {
    return (this.get('limits') && this.get('limits').concurrent_imports) || 1;
  },

  featureEnabled: function (name) {
    var featureFlags = this.get('feature_flags');

    if (!featureFlags || featureFlags.length === 0 || !name) {
      return false;
    }

    return _.contains(featureFlags, name);
  },

  isCloseToLimits: function () {
    var quota = this.get('quota_in_bytes');
    var remainingQuota = this.get('remaining_byte_quota');

    return ((remainingQuota * 100) / quota) < 20;
  },

  isEnterprise: function () {
    return this.get('account_type').toLowerCase().indexOf('enterprise') != -1; // eslint-disable-line
  },

  getOrgName: function () {
    return this.isInsideOrg() ? this.getOrganization().get('name') : '';
  },

  getMaxLayersPerMap: function () {
    return this.get('max_layers') || 4;
  },

  canStartTrial: function () {
    return !this.isInsideOrg() && this.get('account_type') === 'FREE' && this.get('table_count') > 0;
  },

  canCreatePrivateDatasets: function () {
    var actions = this.get('actions');
    return actions && actions.private_tables;
  },

  equals: function (otherUser) {
    if (otherUser.get) {
      return this.get('id') === otherUser.get('id');
    }
  },

  viewUrl: function () {
    return new UserUrlModel({
      base_url: this.get('base_url'),
      is_org_admin: this.isOrgAdmin()
    });
  },

  upgradeContactEmail: function () {
    if (this.isInsideOrg()) {
      if (this.isOrgOwner()) {
        return 'enterprise-support@carto.com';
      } else {
        return this.organization.owner.get('email');
      }
    } else {
      return 'support@carto.com';
    }
  },

  usedQuotaPercentage: function () {
    return (this.get('db_size_in_bytes') * 100) / this.organization.get('available_quota_for_user');
  },

  assignedQuotaInRoundedMb: function () {
    return Math.floor(this.get('quota_in_bytes') / 1024 / 1024).toFixed(0);
  },

  assignedQuotaPercentage: function () {
    return (this.get('quota_in_bytes') * 100) / this.organization.get('available_quota_for_user');
  },

  getGoogleApiKey: function () {
    return this.get('google_maps_private_key');
  },

  hasGoogleMaps: function () {
    return !!this.getGoogleApiKey();
  },

  showGoogleApiKeys: function () {
    return this.hasGoogleMaps() && (!this.isInsideOrg() || this.isOrgOwner());
  },

  getSchema: function () {
    return this.isInsideOrg() ? this.get('username') : 'public';
  },

  getAuthToken: function () {
    return btoa(`${this.get('username')}:${this.get('api_key')}`);
  }
});

module.exports = UserModel;
<|endoftext|>


<commit_before>const highlightjs = require('highlight.js')
const marked = require('marked')
const remote = require('remote')
const Menu = remote.require('menu')
const MenuItem = remote.require('menu-item')
const ipc = require('ipc')
const conf = remote.getGlobal('conf')

marked.setOptions({
  highlight: function (code, lang) {
    return highlightjs.highlightAuto(code, [ lang ]).value
  }
})

ipc.on('md', function (raw) {
  const md = marked(raw)
  const base = document.querySelector('base')
  const body = document.querySelector('.markdown-body')
  base.setAttribute('href', remote.getGlobal('baseUrl'))
  body.innerHTML = md
})

window.addEventListener('keydown', function (ev) {
  var esc = ev.keyCode === 27
  var w = ev.keyCode === 87
  var ctrlW = ev.ctrlKey && w
  var cmdW = ev.metaKey && w

  if (esc || ctrlW || cmdW) remote.getCurrentWindow().close()
})

var zoom = require('./zoom')(conf.zoom)

// menu
var vmdSubmenu = [
  { label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: function () { remote.require('app').quit() } }
]

if (process.platform === 'darwin') {
  vmdSubmenu = [
    { label: 'About vmd', selector: 'orderFrontStandardAboutPanel:' },
    { type: 'separator' }
  ].concat(vmdSubmenu)
}
// Doc: https://github.com/atom/electron/blob/master/docs/api/menu-item.md
var template = [
  {
    label: 'vmd',
    submenu: vmdSubmenu
  },
  {
    label: 'File',
    submenu: [
      { label: 'Print', accelerator: 'CmdOrCtrl+P', click: function () { window.print() } }
    ]
  },
  {
    label: 'Edit',
    submenu: [
        { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy'},
        { label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectall' }
    ]
  },
  {
    label: 'View',
    submenu: [
      { label: 'Zoom In', accelerator: 'CmdOrCtrl+Plus', click: function () { zoom.zoomIn() } },
      { label: 'Zoom Out', accelerator: 'CmdOrCtrl+-', click: function () { zoom.zoomOut() } },
      { label: 'Reset Zoom', accelerator: 'CmdOrCtrl+0', click: function () { zoom.reset() } }
    ]
  }
]

Menu.setApplicationMenu(Menu.buildFromTemplate(template))
<commit_msg>standard test<commit_after>const highlightjs = require('highlight.js')
const marked = require('marked')
const remote = require('remote')
const Menu = remote.require('menu')
const ipc = require('ipc')
const conf = remote.getGlobal('conf')

marked.setOptions({
  highlight: function (code, lang) {
    return highlightjs.highlightAuto(code, [ lang ]).value
  }
})

ipc.on('md', function (raw) {
  const md = marked(raw)
  const base = document.querySelector('base')
  const body = document.querySelector('.markdown-body')
  base.setAttribute('href', remote.getGlobal('baseUrl'))
  body.innerHTML = md
})

window.addEventListener('keydown', function (ev) {
  var esc = ev.keyCode === 27
  var w = ev.keyCode === 87
  var ctrlW = ev.ctrlKey && w
  var cmdW = ev.metaKey && w

  if (esc || ctrlW || cmdW) remote.getCurrentWindow().close()
})

var zoom = require('./zoom')(conf.zoom)

// menu
var vmdSubmenu = [
  { label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: function () { remote.require('app').quit() } }
]

if (process.platform === 'darwin') {
  vmdSubmenu = [
    { label: 'About vmd', selector: 'orderFrontStandardAboutPanel:' },
    { type: 'separator' }
  ].concat(vmdSubmenu)
}
// Doc: https://github.com/atom/electron/blob/master/docs/api/menu-item.md
var template = [
  {
    label: 'vmd',
    submenu: vmdSubmenu
  },
  {
    label: 'File',
    submenu: [
      { label: 'Print', accelerator: 'CmdOrCtrl+P', click: function () { window.print() } }
    ]
  },
  {
    label: 'Edit',
    submenu: [
        { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' },
        { label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectall' }
    ]
  },
  {
    label: 'View',
    submenu: [
      { label: 'Zoom In', accelerator: 'CmdOrCtrl+Plus', click: function () { zoom.zoomIn() } },
      { label: 'Zoom Out', accelerator: 'CmdOrCtrl+-', click: function () { zoom.zoomOut() } },
      { label: 'Reset Zoom', accelerator: 'CmdOrCtrl+0', click: function () { zoom.reset() } }
    ]
  }
]

Menu.setApplicationMenu(Menu.buildFromTemplate(template))
<|endoftext|>


<commit_before>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview A button control. This implementation extends {@link
 * goog.ui.Control}.
 *
 * @see ../demos/button.html
 */

goog.provide('goog.ui.Button');
goog.provide('goog.ui.Button.Side');

goog.require('goog.events.KeyCodes');
goog.require('goog.ui.ButtonRenderer');
goog.require('goog.ui.ButtonSide');
goog.require('goog.ui.Control');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.NativeButtonRenderer');

/**
 * A button control, rendered as a native browser button by default.
 *
 * @param {goog.ui.ControlContent} content Text caption or existing DOM
 *     structure to display as the button's caption.
 * @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
 *     decorate the button; defaults to {@link goog.ui.NativeButtonRenderer}.
 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
 *     document interaction.
 * @constructor
 * @extends {goog.ui.Control}
 */
goog.ui.Button = function(content, opt_renderer, opt_domHelper) {
  goog.ui.Control.call(this, content, opt_renderer ||
      goog.ui.NativeButtonRenderer.getInstance(), opt_domHelper);
};
goog.inherits(goog.ui.Button, goog.ui.Control);

/**
 * Constants for button sides, see {@link goog.ui.Button.prototype.setCollapsed}
 * for details. Aliased from goog.ui.ButtonSide to support legacy users without
 * creating a circular dependency in {@link goog.ui.ButtonRenderer}.
 * @enum {number}
 * @deprecated use {@link goog.ui.ButtonSide} instead.
 */
goog.ui.Button.Side = goog.ui.ButtonSide;

/**
 * Value associated with the button.
 * @type {*}
 * @private
 */
goog.ui.Button.prototype.value_;

/**
 * Tooltip text for the button, displayed on hover.
 * @type {string|undefined}
 * @private
 */
goog.ui.Button.prototype.tooltip_;

// goog.ui.Button API implementation.

/**
 * Returns the value associated with the button.
 * @return {*} Button value (undefined if none).
 */
goog.ui.Button.prototype.getValue = function() {
  return this.value_;
};

/**
 * Sets the value associated with the button, and updates its DOM.
 * @param {*} value New button value.
 */
goog.ui.Button.prototype.setValue = function(value) {
  this.value_ = value;
  this.getRenderer().setValue(this.getElement(), value);
};

/**
 * Sets the value associated with the button.  Unlike {@link #setValue},
 * doesn't update the button's DOM.  Considered protected; to be called only
 * by renderer code during element decoration.
 * @param {*} value New button value.
 * @protected
 */
goog.ui.Button.prototype.setValueInternal = function(value) {
  this.value_ = value;
};

/**
 * Returns the tooltip for the button.
 * @return {string|undefined} Tooltip text (undefined if none).
 */
goog.ui.Button.prototype.getTooltip = function() {
  return this.tooltip_;
};

/**
 * Sets the tooltip for the button, and updates its DOM.
 * @param {string} tooltip New tooltip text.
 */
goog.ui.Button.prototype.setTooltip = function(tooltip) {
  this.tooltip_ = tooltip;
  this.getRenderer().setTooltip(this. getElement(), tooltip);
};

/**
 * Sets the tooltip for the button.  Unlike {@link #setTooltip}, doesn't update
 * the button's DOM.  Considered protected; to be called only by renderer code
 * during element decoration.
 * @param {string} tooltip New tooltip text.
 * @protected
 */
goog.ui.Button.prototype.setTooltipInternal = function(tooltip) {
  this.tooltip_ = tooltip;
};

/**
 * Collapses the border on one or both sides of the button, allowing it to be
 * combined with the adjancent button(s), forming a single UI componenet with
 * multiple targets.
 * @param {number} sides Bitmap of one or more {@link goog.ui.ButtonSide}s for
 *     which borders should be collapsed.
 */
goog.ui.Button.prototype.setCollapsed = function(sides) {
  this.getRenderer().setCollapsed(this, sides);
};

// goog.ui.Control & goog.ui.Component API implementation.

/** @inheritDoc */
goog.ui.Button.prototype.disposeInternal = function() {
  goog.ui.Button.superClass_.disposeInternal.call(this);
  delete this.value_;
  delete this.tooltip_;
};

/** @inheritDoc */
goog.ui.Button.prototype.enterDocument = function() {
  goog.ui.Button.superClass_.enterDocument.call(this);
  if (this.isSupportedState(goog.ui.Component.State.FOCUSED)) {
    var keyTarget = this.getKeyEventTarget();
    if (keyTarget) {
      this.getHandler().listen(keyTarget, goog.events.EventType.KEYUP,
          this.handleKeyEventInternal);
    }
  }
};

/**
 * Attempts to handle a keyboard event; returns true if the event was handled,
 * false otherwise.  If the button is enabled and the Enter/Space key was
 * pressed, handles the event by dispatching an {@code ACTION} event,
 * and returns true. Overrides {@link goog.ui.Control#handleKeyEventInternal}.
 * @param {goog.events.KeyEvent} e Key event to handle.
 * @return {boolean} Whether the key event was handled.
 * @protected
 * @override
 */
goog.ui.Button.prototype.handleKeyEventInternal = function(e) {
  if (e.keyCode == goog.events.KeyCodes.ENTER &&
      e.type == goog.events.KeyHandler.EventType.KEY ||
      e.keyCode == goog.events.KeyCodes.SPACE &&
      e.type == goog.events.EventType.KEYUP) {
    return this.performActionInternal(e);
  }
  // Return true for space keypress (even though the event is handled on keyup)
  // as preventDefault needs to be called up keypress to take effect in IE and
  // WebKit.
  return e.keyCode == goog.events.KeyCodes.SPACE;
};

// Register a decorator factory function for goog.ui.Buttons.
goog.ui.registry.setDecoratorByClassName(goog.ui.ButtonRenderer.CSS_CLASS,
    function() {
      return new goog.ui.Button(null);
    });
<commit_msg><commit_after>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview A button control. This implementation extends {@link
 * goog.ui.Control}.
 *
 * @see ../demos/button.html
 */

goog.provide('goog.ui.Button');
goog.provide('goog.ui.Button.Side');

goog.require('goog.events.KeyCodes');
goog.require('goog.ui.ButtonRenderer');
goog.require('goog.ui.ButtonSide');
goog.require('goog.ui.Control');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.NativeButtonRenderer');

/**
 * A button control, rendered as a native browser button by default.
 *
 * @param {goog.ui.ControlContent} content Text caption or existing DOM
 *     structure to display as the button's caption.
 * @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
 *     decorate the button; defaults to {@link goog.ui.NativeButtonRenderer}.
 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
 *     document interaction.
 * @constructor
 * @extends {goog.ui.Control}
 */
goog.ui.Button = function(content, opt_renderer, opt_domHelper) {
  goog.ui.Control.call(this, content, opt_renderer ||
      goog.ui.NativeButtonRenderer.getInstance(), opt_domHelper);
};
goog.inherits(goog.ui.Button, goog.ui.Control);

/**
 * Constants for button sides, see {@link goog.ui.Button.prototype.setCollapsed}
 * for details. Aliased from goog.ui.ButtonSide to support legacy users without
 * creating a circular dependency in {@link goog.ui.ButtonRenderer}.
 * @enum {number}
 * @deprecated use {@link goog.ui.ButtonSide} instead.
 */
goog.ui.Button.Side = goog.ui.ButtonSide;

/**
 * Value associated with the button.
 * @type {*}
 * @private
 */
goog.ui.Button.prototype.value_;

/**
 * Tooltip text for the button, displayed on hover.
 * @type {string|undefined}
 * @private
 */
goog.ui.Button.prototype.tooltip_;

// goog.ui.Button API implementation.

/**
 * Returns the value associated with the button.
 * @return {*} Button value (undefined if none).
 */
goog.ui.Button.prototype.getValue = function() {
  return this.value_;
};

/**
 * Sets the value associated with the button, and updates its DOM.
 * @param {*} value New button value.
 */
goog.ui.Button.prototype.setValue = function(value) {
  this.value_ = value;
  this.getRenderer().setValue(this.getElement(), value);
};

/**
 * Sets the value associated with the button.  Unlike {@link #setValue},
 * doesn't update the button's DOM.  Considered protected; to be called only
 * by renderer code during element decoration.
 * @param {*} value New button value.
 * @protected
 */
goog.ui.Button.prototype.setValueInternal = function(value) {
  this.value_ = value;
};

/**
 * Returns the tooltip for the button.
 * @return {string|undefined} Tooltip text (undefined if none).
 */
goog.ui.Button.prototype.getTooltip = function() {
  return this.tooltip_;
};

/**
 * Sets the tooltip for the button, and updates its DOM.
 * @param {string} tooltip New tooltip text.
 */
goog.ui.Button.prototype.setTooltip = function(tooltip) {
  this.tooltip_ = tooltip;
  this.getRenderer().setTooltip(this.getElement(), tooltip);
};

/**
 * Sets the tooltip for the button.  Unlike {@link #setTooltip}, doesn't update
 * the button's DOM.  Considered protected; to be called only by renderer code
 * during element decoration.
 * @param {string} tooltip New tooltip text.
 * @protected
 */
goog.ui.Button.prototype.setTooltipInternal = function(tooltip) {
  this.tooltip_ = tooltip;
};

/**
 * Collapses the border on one or both sides of the button, allowing it to be
 * combined with the adjancent button(s), forming a single UI componenet with
 * multiple targets.
 * @param {number} sides Bitmap of one or more {@link goog.ui.ButtonSide}s for
 *     which borders should be collapsed.
 */
goog.ui.Button.prototype.setCollapsed = function(sides) {
  this.getRenderer().setCollapsed(this, sides);
};

// goog.ui.Control & goog.ui.Component API implementation.

/** @inheritDoc */
goog.ui.Button.prototype.disposeInternal = function() {
  goog.ui.Button.superClass_.disposeInternal.call(this);
  delete this.value_;
  delete this.tooltip_;
};

/** @inheritDoc */
goog.ui.Button.prototype.enterDocument = function() {
  goog.ui.Button.superClass_.enterDocument.call(this);
  if (this.isSupportedState(goog.ui.Component.State.FOCUSED)) {
    var keyTarget = this.getKeyEventTarget();
    if (keyTarget) {
      this.getHandler().listen(keyTarget, goog.events.EventType.KEYUP,
          this.handleKeyEventInternal);
    }
  }
};

/**
 * Attempts to handle a keyboard event; returns true if the event was handled,
 * false otherwise.  If the button is enabled and the Enter/Space key was
 * pressed, handles the event by dispatching an {@code ACTION} event,
 * and returns true. Overrides {@link goog.ui.Control#handleKeyEventInternal}.
 * @param {goog.events.KeyEvent} e Key event to handle.
 * @return {boolean} Whether the key event was handled.
 * @protected
 * @override
 */
goog.ui.Button.prototype.handleKeyEventInternal = function(e) {
  if (e.keyCode == goog.events.KeyCodes.ENTER &&
      e.type == goog.events.KeyHandler.EventType.KEY ||
      e.keyCode == goog.events.KeyCodes.SPACE &&
      e.type == goog.events.EventType.KEYUP) {
    return this.performActionInternal(e);
  }
  // Return true for space keypress (even though the event is handled on keyup)
  // as preventDefault needs to be called up keypress to take effect in IE and
  // WebKit.
  return e.keyCode == goog.events.KeyCodes.SPACE;
};

// Register a decorator factory function for goog.ui.Buttons.
goog.ui.registry.setDecoratorByClassName(goog.ui.ButtonRenderer.CSS_CLASS,
    function() {
      return new goog.ui.Button(null);
    });
<|endoftext|>


<commit_before>/**
 * Bootbox
 * @type {{dialog, form, formCreate, init}}
 */
var pmBootbox = function () {
    "use strict";

    return {
        dialog: function (element, size, callback) {
            pmUtilLoading.start();
            if (!size) {
                size = "small";
            }

            $.get($(element).attr('href'), {}, function (result) {
                bootbox.dialog({
                    title: $(element).attr('title'),
                    message: result,
                    size: size,
                    buttons: {
                        close: {
                            label: "Schließen",
                            className: "btn-success"
                        }
                    }
                });

                if (typeof callback === "function") {
                    callback();
                }

                pmUtilLoading.stop();
            }, 'html');
        },
        /**
         * Form
         *
         * @param element
         */
        form: function (element) {
            var _self = this;

            pmUtilLoading.start();
            $.get($(element).attr('href'), {}, function (result) {
                _self.formCreate(element, result);
            });
        },
        /**
         * Form Create
         *
         * @param element
         * @param content
         */
        formCreate: function (element, content) {
            var _self = this, title;

            if ($(element).attr('title')) {
                title = $(element).attr('title');
            } else {
                title = $(element).text();
            }

            bootbox.dialog({
                className: "bootbox-form-dialog",
                title: title,
                message: content,
                buttons: {
                    save: {
                        label: "Speichern",
                        className: "btn-success",
                        callback: function () {
                            pmUtilLoading.start();
                            $.post($(element).attr('href'), $('.bootbox-form-dialog form').serialize(), function (result) {
                                if ("" !== result) {
                                    _self.formCreate(element, result);
                                } else {
                                    window.location.reload(true);
                                }
                            });
                        }
                    },
                    close: {
                        label: "Abbrechen",
                        className: "btn-warning"
                    }
                }
            });

            pmUtilLoading.stop();
        },
        /**
         * Init
         */
        init: function () {
            var _self = this;

            $('a.bootbox-dialog').on('click', function () {
                if ($(this).hasClass("bootbox-form")) {
                    _self.form(this, $(this).data("size"));
                } else {
                    _self.dialog(this, $(this).data("size"));
                }

                return false;
            });
        }
    };
}();

$(document).ready(function () {
    pmBootbox.init();
});<commit_msg>Bootbox File Upload<commit_after>/**
 * Bootbox
 * @type {{dialog, form, formCreate, init}}
 */
var pmBootbox = function () {
    "use strict";

    return {
        dialog: function (element, size, callback) {
            pmUtilLoading.start();
            if (!size) {
                size = "small";
            }

            $.get($(element).attr('href'), {}, function (result) {
                bootbox.dialog({
                    title: $(element).attr('title'),
                    message: result,
                    size: size,
                    buttons: {
                        close: {
                            label: "Schließen",
                            className: "btn-success"
                        }
                    }
                });

                if (typeof callback === "function") {
                    callback();
                }

                pmUtilLoading.stop();
            }, 'html');
        },
        /**
         * Form
         *
         * @param element
         */
        form: function (element) {
            var _self = this;

            pmUtilLoading.start();
            $.get($(element).attr('href'), {}, function (result) {
                _self.formCreate(element, result);
            });
        },
        /**
         * Form Create
         *
         * @param element
         * @param content
         */
        formCreate: function (element, content) {
            var _self = this, title;

            if ($(element).attr('title')) {
                title = $(element).attr('title');
            } else {
                title = $(element).text();
            }

            bootbox.dialog({
                className: "bootbox-form-dialog",
                title: title,
                message: content,
                buttons: {
                    save: {
                        label: "Speichern",
                        className: "btn-success",
                        callback: function () {
                            pmUtilLoading.start();

                            var form = $('.bootbox-form-dialog form');

                            if(0<form.find('input[type="file"]').length){
                                $.ajax({
                                    url: $(element).attr('href'),
                                    type: "POST",
                                    data: new FormData(form[0]),
                                    contentType: false,
                                    cache: false,
                                    processData:false,
                                    success: function(data) {
                                        if ("" !== result) {
                                            _self.formCreate(element, result);
                                        } else {
                                            window.location.reload(true);
                                        }
                                    }
                                });

                            } else {
                                $.post($(element).attr('href'), form.serialize(), function (result) {
                                    if ("" !== result) {
                                        _self.formCreate(element, result);
                                    } else {
                                        window.location.reload(true);
                                    }
                                });
                            }
                        }
                    },
                    close: {
                        label: "Abbrechen",
                        className: "btn-warning"
                    }
                }
            });

            pmUtilLoading.stop();
        },
        /**
         * Init
         */
        init: function () {
            var _self = this;

            $('a.bootbox-dialog').on('click', function () {
                if ($(this).hasClass("bootbox-form")) {
                    _self.form(this, $(this).data("size"));
                } else {
                    _self.dialog(this, $(this).data("size"));
                }

                return false;
            });
        }
    };
}();

$(document).ready(function () {
    pmBootbox.init();
});<|endoftext|>