<commit_before>/* See license.txt for terms of usage */

// ********************************************************************************************* //
// Constants

var EXPORTED_SYMBOLS = ["FirebugLoader"];

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");

// xxxHonza: this breaks tracing, needs to be fixed.
//Components.utils.import("resource://firebug/fbtrace.js");
var FBTrace = {};

// ********************************************************************************************* //

function loadSubscript(src, win)
{
    return Services.scriptloader.loadSubScript(src, win);
}

// ********************************************************************************************* //

var FirebugLoader =
{
    extensions: [],

    registerExtension: function(e)
    {
        if (this.extensions.indexOf(e) != -1)
            return;

        this.extensions.push(e);

        this.forEachWindow(function(win)
        {
            e.topWindowReady(win)

            if (!win.Firebug.isInitialized)
                return;

            e.firebugWindowReady(win);
        })
    },

    unregisterExtension: function(e)
    {
        var i = this.extensions.indexOf(e);
        if (i >= 0)
            this.extensions.splice(i, 1);

        if (e.unloadFromWindow)
        {
            this.forEachWindow(function(win)
            {
                e.unloadFromWindow(win);
            })
        }
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    startup: function()
    {
        // allow already started bootstrapped firebug extensions to register themselves
        var XPIProviderBP = Cu.import("resource://gre/modules/XPIProvider.jsm", {});
        var bootstrapScopes = XPIProviderBP.XPIProvider.bootstrapScopes;

        for each(var scope in bootstrapScopes)
        {
            try
            {
                if (scope.firebugStartup)
                    scope.firebugStartup(this);
            }
            catch(e)
            {
                Cu.reportError(e);
            }
        }
    },

    shutdown: function()
    {
        this.forEachWindow(function(win)
        {
            FirebugLoader.unloadFromWindow(win);
        })
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    unloadFromWindow: function(win)
    {
        var fbug = win.Firebug
        this.dispatchToExtensions("unloadFromWindow", [win]);

        if (fbug.shutdown)
        {
            fbug.closeFirebug();
            fbug.shutdown();
        }

        function getRoots(el)
        {
            return Array.slice(el.querySelectorAll("[firebugRootNode]"));
        }

        [getRoots(win.document), getRoots(win.gNavToolbox.palette),
            fbug.GlobalUI.nodesToRemove].forEach(function(list)
        {
            for each(var el in list)
                if (el && el.parentNode)
                    el.parentNode.removeChild(el);
        });

        delete win.Firebug;
        delete win.FBTrace;
        delete win.FBL;
    },

    loadIntoWindow: function(win)
    {
        // This is the place where the global Firebug object is created. This object represents
        // the entire application and all consequently created namespaces and variables should be
        // injected into it.
        // In the future, there should *not* be any other globals except of the Firebug object.
        win.Firebug = {};

        // Apply all Firefox/SeaMonkey overlays to the browser window.
        loadSubscript("chrome://firebug/content/firefox/browserOverlay.js", win);

        // Firebug extensions should initialize here.
        this.dispatchToExtensions("topWindowReady", [win]);
    },

    dispatchToExtensions: function(name, arguments)
    {
        for each (var e in this.extensions)
        {
            try
            {
                if (name in e)
                    e[name].apply(e, arguments);
            }
            catch(e)
            {
                Cu.reportError(e);
            }
        }
    },

    forEachWindow: function(func)
    {
        var enumerator = Services.wm.getEnumerator("navigator:browser");
        while (enumerator.hasMoreElements())
        {
            try
            {
                var win = enumerator.getNext();
                if (win.Firebug)
                    func(win);
            }
            catch(e)
            {
                Cu.reportError(e)
            }
        }
    }
}

// ********************************************************************************************* //

// For a detailed description of all preferences see:
// http://getfirebug.com/wiki/index.php/Firebug_Preferences

// Global
FirebugLoader.defaultPrefs = {
    "defaultModuleList": "",
    "architecture": "inProcess",

    "strict.debug": false,
    "defaultPanelName": "html",
    "throttleMessages": true,
    "textSize": 0,
    "showInfoTips": true,
    "textWrapWidth": 100,
    "framePosition": "bottom",
    "previousPlacement": 0,
    "showErrorCount": true,
    "viewPanelOrient": false,
    "allPagesActivation": "none",
    "hiddenPanels": "",
    "panelTabMinWidth": 50,
    "sourceLinkLabelWidth": 17,
    "currentVersion": "",
    "showFirstRunPage": true,
    "useDefaultLocale": false,
    "activateSameOrigin": true,
    "toolbarCustomizationDone": false,
    "addonBarOpened": false,
    "showBreakNotification": true,
    "showStatusIcon": false,
    "stringCropLength": 50,

// Command line
    "commandEditor": false,
    "alwaysShowCommandLine": false,

// Search
    "searchCaseSensitive": false,
    "searchGlobal": true,
    "searchUseRegularExpression": false,

    "netSearchHeaders": false,
    "netSearchParameters": false,
    "netSearchResponseBody": false,

// Console
    "showJSErrors": true,
    "showJSWarnings": false,
    "showCSSErrors": false,
    "showXMLErrors": false,
    "showChromeErrors": false,
    "showChromeMessages": false,
    "showExternalErrors": false,
    "showNetworkErrors": true,
    "showXMLHttpRequests": true,
    "showStackTrace": false,
    "console.logLimit": 500,
    "console.enableSites": false,
    "tabularLogMaxHeight": 200,
    "consoleFilterTypes": "all",
    "memoryProfilerEnable": false,

// HTML
    "showCommentNodes": false,
    "showTextNodesWithWhitespace": false,
    "showTextNodesWithEntities": true,
    "showFullTextNodes": true,
    "highlightMutations": true,
    "expandMutations": false,
    "scrollToMutations": false,
    "shadeBoxModel": true,
    "showQuickInfoBox": false,
    "displayedAttributeValueLimit": 1024,
    "multiHighlightLimit": 250,

// CSS
    "onlyShowAppliedStyles": false,
    "showUserAgentCSS": false,
    "expandShorthandProps": false,
    "showMozillaSpecificStyles": false,
    "computedStylesDisplay": "grouped",
    "cssEditMode": "Source",

// Script
    "breakOnErrors": false,
    "trackThrowCatch": false,
    "script.enableSites": false,
    "scriptsFilter": "all",
    "replaceTabs": 4,
    "filterSystemURLs": true,
    "maxScriptLineLength": 10000,

// Stack
    "omitObjectPathStack": false,

// DOM
    "showUserProps": true,
    "showUserFuncs": true,
    "showDOMProps": true,
    "showDOMFuncs": false,
    "showDOMConstants": false,
    "showInlineEventHandlers": false,
    "ObjectShortIteratorMax": 3,
    "showEnumerableProperties": true,
    "showOwnProperties": false,

// Layout
    "showRulers": true,

// Net
    "netFilterCategory": "all",
    "net.logLimit": 500,
    "net.enableSites": false,
    "netDisplayedResponseLimit": 102400,
    "netDisplayedPostBodyLimit": 10240,
    "net.hiddenColumns": "netProtocolCol netLocalAddressCol",
    "netPhaseInterval": 1000,
    "sizePrecision": 1,
    "netParamNameLimit": 25,
    "netShowPaintEvents": false,
    "netShowBFCacheResponses": true,
    "netHtmlPreviewHeight": 100,

// JSON Preview
    "sortJsonPreview": false,

// Cache
    "cache.mimeTypes": "",
    "cache.responseLimit": 5242880,

// External Editors
    "externalEditors": "",

// Keyboard
    "key.shortcut.reenterCommand": "accel shift e",
    "key.shortcut.toggleInspecting": "accel shift c",
    "key.shortcut.toggleQuickInfoBox": "accel shift i",
    "key.shortcut.toggleProfiling": "accel shift p",
    "key.shortcut.focusCommandLine": "accel shift l",
    "key.shortcut.focusFirebugSearch": "accel f",
    "key.shortcut.focusWatchEditor": "accel shift n",
    "key.shortcut.focusLocation": "accel shift VK_SPACE",
    "key.shortcut.nextObject": "accel .",
    "key.shortcut.previousObject": "accel :",
    "key.shortcut.toggleFirebug": "VK_F12",
    "key.shortcut.detachFirebug": "accel VK_F12",
    "key.shortcut.leftFirebugTab": "accel shift VK_PAGE_UP",
    "key.shortcut.rightFirebugTab": "accel shift VK_PAGE_DOWN",
    "key.shortcut.previousFirebugTab": "accel `",
    "key.shortcut.clearConsole": "accel shift r",
    "key.shortcut.navBack": "accel shift VK_LEFT",
    "key.shortcut.navForward": "accel shift VK_RIGHT",
    "key.shortcut.increaseTextSize": "accel +",
    "key.shortcut.decreaseTextSize": "accel -",
    "key.shortcut.normalTextSize": "accel 0",

// Accessibility
    "a11y.enable": false,

// Tracing Options
    "DBG_FBS_JSDCONTEXT": false,   // firebug trace scriptinfo(huge)
    "DBG_FBS_FF_START": false,     // firebug trace from FF start(huge)
    "DBG_FBS_CREATION": false,     // firebug script creation
    "DBG_FBS_BP": false,           // firebug breakpoints
    "DBG_FBS_SRCUNITS": false,     // firebug script creation
    "DBG_FBS_ERRORS": false,       // firebug errors
    "DBG_FBS_FINDDEBUGGER": false, // firebug findDebugger
    "DBG_FBS_STEP": false,         // firebug stepping
    "DBG_FBS_TRACKFILES": false,   // dump all js files to disk
    "DBG_FBS_FUNCTION": false,     // firebug new Function
    "DBG_ACTIVATION": false,       // firebug.js and tabWatcher.js
    "DBG_BP": false,               // debugger.js and firebug-services.js; lots of output
    "DBG_COMPILATION_UNITS": false,// debugger.js and firebug-services.js; lots of output
    "DBG_TOPLEVEL": false,         // top level jsd scripts
    "DBG_STACK": false,            // call stack: mostly debugger.js
    "DBG_WATCH": false,            // Watch expressions
    "DBG_UI_LOOP": false,          // debugger.js
    "DBG_ERRORS": false,           // error.js
    "DBG_ERRORLOG": false,         // error.js
    "DBG_FUNCTION_NAMES": false,   // heuristics for anon functions
    "DBG_EVAL": false,             // debugger.js and firebug-service.js
    "DBG_EVENTS": false,           // browser generated events
    "DBG_PANELS": false,           // panel selection
    "DBG_CACHE": false,            // sourceCache
    "DBG_CONSOLE": false,          // console
    "DBG_COMMANDLINE": false,      // command line
    "DBG_CSS": false,              //
    "DBG_CSS_PARSER": false,       //
    "DBG_DBG2FIREBUG": false,      //
    "DBG_DOM": false,              //
    "DBG_DOMPLATE": false,         // domplate engine
    "DBG_DISPATCH": false,         //
    "DBG_HTML": false,             //
    "DBG_LINETABLE": false,        //
    "DBG_LOCATIONS": false,        // panelFileList
    "DBG_MEMORY_PROFILER": false,  //
    "DBG_SOURCEFILES": false,      // debugger and sourceCache
    "DBG_WINDOWS": false,          // tabWatcher: dispatch events; very useful for understand modules/panels
    "DBG_NET": false,              // net.js
    "DBG_NET_EVENTS": false,       // net.js - network events
    "DBG_INITIALIZE": false,       // initialize FB
    "DBG_REGISTRATION": false,     // registry (modules panels,
    "DBG_INSPECT": false,          // inspector
    "DBG_OPTIONS": false,          //
    "DBG_FBS_FLUSH": false,        //
    "DBG_HTTPOBSERVER": false,     // Centralized HTTP Observer
    "DBG_SPY": false,              // spy.js
    "DBG_EDITOR": false,           // Inline editors
    "DBG_SHORTCUTS": false,        // Keyboard shortcuts
    "DBG_A11Y": false,             // a11y
    "DBG_LOCALE": false,           // localization: missing strings
    "DBG_INFOTIP": false,          // popup info tip in panels
    "DBG_ANNOTATIONS": false,      // Page annotations service
    "DBG_XMLVIEWER": false,        // XML explorer
    "DBG_JSONVIEWER": false,       // JSON explorer
    "DBG_SVGVIEWER": false,        // SVG explorer
    "DBG_FONTS": false,            // Fonts information and font viewer
    "DBG_ACTIVITYOBSERVER": false, // Net panel's activity observer
    "DBG_TOOLTIP": false,          // tooltip debugging
    "DBG_HISTORY": false,          // panel navigation history
    "DBG_STORAGE": false,          // storageService
    "DBG_MODULES": false,          // moduleloading
    "DBG_PROFILER": false,         // profiler
    "DBG_SEARCH": false,           // search box
    "DBG_EXTERNALEDITORS": false,  // integration with external editors/IDEs
    "DBG_OBSERVERS": false,        // track/untrack support: should be set: then restart Firefox
    "DBG_EVENTLISTENERS": false,   // track/untrack for registered event listeners: restart needed
}

// ********************************************************************************************* //

var prefTypeMap = (function()
{
    var map = {}, br = Ci.nsIPrefBranch;
    map["string"] = map[br.PREF_STRING] = "CharPref";
    map["boolean"] = map[br.PREF_BOOL] = "BoolPref";
    map["number"] = map[br.PREF_INT] = "IntPref";
    return map;
})();

FirebugLoader.prefDomain = "extensions.firebug.";

FirebugLoader.getPref = function(prefDomain, name)
{
    var prefName;
    if (name == undefined)
        prefName = FirebugLoader.prefDomain + prefDomain;
    else
        prefName = prefDomain + "." + name;

    var prefs = Services.prefs;

    var type = prefTypeMap[prefs.getPrefType(prefName)];
    if (type)
        var value = prefs["get" + type](prefName);

    if (FBTrace.DBG_OPTIONS)
    {
        FBTrace.sysout("options.getPref " + prefName + " has type " +
            type + " and value " + value);
    }

    return value;
}

FirebugLoader.setPref = function(name, value)
{
    var prefName = FirebugLoader.prefDomain + name;
    var prefs = Services.prefs;

    var type = prefTypeMap[typeof value];
    if (type)
        value = prefs["set" + type](prefName, value);

    return value;
}

FirebugLoader.registerDefaultPrefs = function (prefMap, domain)
{
    prefMap = prefMap || this.defaultPrefs;
    domain = domain || this.prefDomain;
    var pb = Services.prefs.getDefaultBranch(domain);

    for (var name in prefMap)
    {
        var value = prefMap[name];
        var type = prefTypeMap[typeof value];

        pb["set" + type](name, value);
    }
}

// not really needed but someone on amo decided to require clearing default prefs
// clear only prefs that are not modified by user
// assumes that if "foo" isn't user modified "foo.*" are not modified as well
FirebugLoader.clearDefaultPrefs = function(domain)
{
    domain = domain || this.prefDomain;
    var pb = Services.prefs.getDefaultBranch(domain);

    var names = pb.getChildList("");
    for each (var name in names)
    {
        if (!pb.prefHasUserValue(name))
            pb.deleteBranch(name);
    }
}

// ********************************************************************************************* //
<commit_msg>[1.10] Issue 3310 (Can't rebind shortcut to deactivate firebug) Needed to re-add the changes of r12715 due to r12758<commit_after>/* See license.txt for terms of usage */

// ********************************************************************************************* //
// Constants

var EXPORTED_SYMBOLS = ["FirebugLoader"];

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");

// xxxHonza: this breaks tracing, needs to be fixed.
//Components.utils.import("resource://firebug/fbtrace.js");
var FBTrace = {};

// ********************************************************************************************* //

function loadSubscript(src, win)
{
    return Services.scriptloader.loadSubScript(src, win);
}

// ********************************************************************************************* //

var FirebugLoader =
{
    extensions: [],

    registerExtension: function(e)
    {
        if (this.extensions.indexOf(e) != -1)
            return;

        this.extensions.push(e);

        this.forEachWindow(function(win)
        {
            e.topWindowReady(win)

            if (!win.Firebug.isInitialized)
                return;

            e.firebugWindowReady(win);
        })
    },

    unregisterExtension: function(e)
    {
        var i = this.extensions.indexOf(e);
        if (i >= 0)
            this.extensions.splice(i, 1);

        if (e.unloadFromWindow)
        {
            this.forEachWindow(function(win)
            {
                e.unloadFromWindow(win);
            })
        }
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    startup: function()
    {
        // allow already started bootstrapped firebug extensions to register themselves
        var XPIProviderBP = Cu.import("resource://gre/modules/XPIProvider.jsm", {});
        var bootstrapScopes = XPIProviderBP.XPIProvider.bootstrapScopes;

        for each(var scope in bootstrapScopes)
        {
            try
            {
                if (scope.firebugStartup)
                    scope.firebugStartup(this);
            }
            catch(e)
            {
                Cu.reportError(e);
            }
        }
    },

    shutdown: function()
    {
        this.forEachWindow(function(win)
        {
            FirebugLoader.unloadFromWindow(win);
        })
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

    unloadFromWindow: function(win)
    {
        var fbug = win.Firebug
        this.dispatchToExtensions("unloadFromWindow", [win]);

        if (fbug.shutdown)
        {
            fbug.closeFirebug();
            fbug.shutdown();
        }

        function getRoots(el)
        {
            return Array.slice(el.querySelectorAll("[firebugRootNode]"));
        }

        [getRoots(win.document), getRoots(win.gNavToolbox.palette),
            fbug.GlobalUI.nodesToRemove].forEach(function(list)
        {
            for each(var el in list)
                if (el && el.parentNode)
                    el.parentNode.removeChild(el);
        });

        delete win.Firebug;
        delete win.FBTrace;
        delete win.FBL;
    },

    loadIntoWindow: function(win)
    {
        // This is the place where the global Firebug object is created. This object represents
        // the entire application and all consequently created namespaces and variables should be
        // injected into it.
        // In the future, there should *not* be any other globals except of the Firebug object.
        win.Firebug = {};

        // Apply all Firefox/SeaMonkey overlays to the browser window.
        loadSubscript("chrome://firebug/content/firefox/browserOverlay.js", win);

        // Firebug extensions should initialize here.
        this.dispatchToExtensions("topWindowReady", [win]);
    },

    dispatchToExtensions: function(name, arguments)
    {
        for each (var e in this.extensions)
        {
            try
            {
                if (name in e)
                    e[name].apply(e, arguments);
            }
            catch(e)
            {
                Cu.reportError(e);
            }
        }
    },

    forEachWindow: function(func)
    {
        var enumerator = Services.wm.getEnumerator("navigator:browser");
        while (enumerator.hasMoreElements())
        {
            try
            {
                var win = enumerator.getNext();
                if (win.Firebug)
                    func(win);
            }
            catch(e)
            {
                Cu.reportError(e)
            }
        }
    }
}

// ********************************************************************************************* //

// For a detailed description of all preferences see:
// http://getfirebug.com/wiki/index.php/Firebug_Preferences

// Global
FirebugLoader.defaultPrefs = {
    "defaultModuleList": "",
    "architecture": "inProcess",

    "strict.debug": false,
    "defaultPanelName": "html",
    "throttleMessages": true,
    "textSize": 0,
    "showInfoTips": true,
    "textWrapWidth": 100,
    "framePosition": "bottom",
    "previousPlacement": 0,
    "showErrorCount": true,
    "viewPanelOrient": false,
    "allPagesActivation": "none",
    "hiddenPanels": "",
    "panelTabMinWidth": 50,
    "sourceLinkLabelWidth": 17,
    "currentVersion": "",
    "showFirstRunPage": true,
    "useDefaultLocale": false,
    "activateSameOrigin": true,
    "toolbarCustomizationDone": false,
    "addonBarOpened": false,
    "showBreakNotification": true,
    "showStatusIcon": false,
    "stringCropLength": 50,

// Command line
    "commandEditor": false,
    "alwaysShowCommandLine": false,

// Search
    "searchCaseSensitive": false,
    "searchGlobal": true,
    "searchUseRegularExpression": false,

    "netSearchHeaders": false,
    "netSearchParameters": false,
    "netSearchResponseBody": false,

// Console
    "showJSErrors": true,
    "showJSWarnings": false,
    "showCSSErrors": false,
    "showXMLErrors": false,
    "showChromeErrors": false,
    "showChromeMessages": false,
    "showExternalErrors": false,
    "showNetworkErrors": true,
    "showXMLHttpRequests": true,
    "showStackTrace": false,
    "console.logLimit": 500,
    "console.enableSites": false,
    "tabularLogMaxHeight": 200,
    "consoleFilterTypes": "all",
    "memoryProfilerEnable": false,

// HTML
    "showCommentNodes": false,
    "showTextNodesWithWhitespace": false,
    "showTextNodesWithEntities": true,
    "showFullTextNodes": true,
    "highlightMutations": true,
    "expandMutations": false,
    "scrollToMutations": false,
    "shadeBoxModel": true,
    "showQuickInfoBox": false,
    "displayedAttributeValueLimit": 1024,
    "multiHighlightLimit": 250,

// CSS
    "onlyShowAppliedStyles": false,
    "showUserAgentCSS": false,
    "expandShorthandProps": false,
    "showMozillaSpecificStyles": false,
    "computedStylesDisplay": "grouped",
    "cssEditMode": "Source",

// Script
    "breakOnErrors": false,
    "trackThrowCatch": false,
    "script.enableSites": false,
    "scriptsFilter": "all",
    "replaceTabs": 4,
    "filterSystemURLs": true,
    "maxScriptLineLength": 10000,

// Stack
    "omitObjectPathStack": false,

// DOM
    "showUserProps": true,
    "showUserFuncs": true,
    "showDOMProps": true,
    "showDOMFuncs": false,
    "showDOMConstants": false,
    "showInlineEventHandlers": false,
    "ObjectShortIteratorMax": 3,
    "showEnumerableProperties": true,
    "showOwnProperties": false,

// Layout
    "showRulers": true,

// Net
    "netFilterCategory": "all",
    "net.logLimit": 500,
    "net.enableSites": false,
    "netDisplayedResponseLimit": 102400,
    "netDisplayedPostBodyLimit": 10240,
    "net.hiddenColumns": "netProtocolCol netLocalAddressCol",
    "netPhaseInterval": 1000,
    "sizePrecision": 1,
    "netParamNameLimit": 25,
    "netShowPaintEvents": false,
    "netShowBFCacheResponses": true,
    "netHtmlPreviewHeight": 100,

// JSON Preview
    "sortJsonPreview": false,

// Cache
    "cache.mimeTypes": "",
    "cache.responseLimit": 5242880,

// External Editors
    "externalEditors": "",

// Keyboard
    "key.shortcut.reenterCommand": "accel shift e",
    "key.shortcut.toggleInspecting": "accel shift c",
    "key.shortcut.toggleQuickInfoBox": "accel shift i",
    "key.shortcut.toggleProfiling": "accel shift p",
    "key.shortcut.focusCommandLine": "accel shift l",
    "key.shortcut.focusFirebugSearch": "accel f",
    "key.shortcut.focusWatchEditor": "accel shift n",
    "key.shortcut.focusLocation": "accel shift VK_SPACE",
    "key.shortcut.nextObject": "accel .",
    "key.shortcut.previousObject": "accel :",
    "key.shortcut.toggleFirebug": "VK_F12",
    "key.shortcut.closeFirebug": "shift VK_F12",
    "key.shortcut.detachFirebug": "accel VK_F12",
    "key.shortcut.leftFirebugTab": "accel shift VK_PAGE_UP",
    "key.shortcut.rightFirebugTab": "accel shift VK_PAGE_DOWN",
    "key.shortcut.previousFirebugTab": "accel `",
    "key.shortcut.clearConsole": "accel shift r",
    "key.shortcut.navBack": "accel shift VK_LEFT",
    "key.shortcut.navForward": "accel shift VK_RIGHT",
    "key.shortcut.increaseTextSize": "accel +",
    "key.shortcut.decreaseTextSize": "accel -",
    "key.shortcut.normalTextSize": "accel 0",

// Accessibility
    "a11y.enable": false,

// Tracing Options
    "DBG_FBS_JSDCONTEXT": false,   // firebug trace scriptinfo(huge)
    "DBG_FBS_FF_START": false,     // firebug trace from FF start(huge)
    "DBG_FBS_CREATION": false,     // firebug script creation
    "DBG_FBS_BP": false,           // firebug breakpoints
    "DBG_FBS_SRCUNITS": false,     // firebug script creation
    "DBG_FBS_ERRORS": false,       // firebug errors
    "DBG_FBS_FINDDEBUGGER": false, // firebug findDebugger
    "DBG_FBS_STEP": false,         // firebug stepping
    "DBG_FBS_TRACKFILES": false,   // dump all js files to disk
    "DBG_FBS_FUNCTION": false,     // firebug new Function
    "DBG_ACTIVATION": false,       // firebug.js and tabWatcher.js
    "DBG_BP": false,               // debugger.js and firebug-services.js; lots of output
    "DBG_COMPILATION_UNITS": false,// debugger.js and firebug-services.js; lots of output
    "DBG_TOPLEVEL": false,         // top level jsd scripts
    "DBG_STACK": false,            // call stack: mostly debugger.js
    "DBG_WATCH": false,            // Watch expressions
    "DBG_UI_LOOP": false,          // debugger.js
    "DBG_ERRORS": false,           // error.js
    "DBG_ERRORLOG": false,         // error.js
    "DBG_FUNCTION_NAMES": false,   // heuristics for anon functions
    "DBG_EVAL": false,             // debugger.js and firebug-service.js
    "DBG_EVENTS": false,           // browser generated events
    "DBG_PANELS": false,           // panel selection
    "DBG_CACHE": false,            // sourceCache
    "DBG_CONSOLE": false,          // console
    "DBG_COMMANDLINE": false,      // command line
    "DBG_CSS": false,              //
    "DBG_CSS_PARSER": false,       //
    "DBG_DBG2FIREBUG": false,      //
    "DBG_DOM": false,              //
    "DBG_DOMPLATE": false,         // domplate engine
    "DBG_DISPATCH": false,         //
    "DBG_HTML": false,             //
    "DBG_LINETABLE": false,        //
    "DBG_LOCATIONS": false,        // panelFileList
    "DBG_MEMORY_PROFILER": false,  //
    "DBG_SOURCEFILES": false,      // debugger and sourceCache
    "DBG_WINDOWS": false,          // tabWatcher: dispatch events; very useful for understand modules/panels
    "DBG_NET": false,              // net.js
    "DBG_NET_EVENTS": false,       // net.js - network events
    "DBG_INITIALIZE": false,       // initialize FB
    "DBG_REGISTRATION": false,     // registry (modules panels,
    "DBG_INSPECT": false,          // inspector
    "DBG_OPTIONS": false,          //
    "DBG_FBS_FLUSH": false,        //
    "DBG_HTTPOBSERVER": false,     // Centralized HTTP Observer
    "DBG_SPY": false,              // spy.js
    "DBG_EDITOR": false,           // Inline editors
    "DBG_SHORTCUTS": false,        // Keyboard shortcuts
    "DBG_A11Y": false,             // a11y
    "DBG_LOCALE": false,           // localization: missing strings
    "DBG_INFOTIP": false,          // popup info tip in panels
    "DBG_ANNOTATIONS": false,      // Page annotations service
    "DBG_XMLVIEWER": false,        // XML explorer
    "DBG_JSONVIEWER": false,       // JSON explorer
    "DBG_SVGVIEWER": false,        // SVG explorer
    "DBG_FONTS": false,            // Fonts information and font viewer
    "DBG_ACTIVITYOBSERVER": false, // Net panel's activity observer
    "DBG_TOOLTIP": false,          // tooltip debugging
    "DBG_HISTORY": false,          // panel navigation history
    "DBG_STORAGE": false,          // storageService
    "DBG_MODULES": false,          // moduleloading
    "DBG_PROFILER": false,         // profiler
    "DBG_SEARCH": false,           // search box
    "DBG_EXTERNALEDITORS": false,  // integration with external editors/IDEs
    "DBG_OBSERVERS": false,        // track/untrack support: should be set: then restart Firefox
    "DBG_EVENTLISTENERS": false,   // track/untrack for registered event listeners: restart needed
}

// ********************************************************************************************* //

var prefTypeMap = (function()
{
    var map = {}, br = Ci.nsIPrefBranch;
    map["string"] = map[br.PREF_STRING] = "CharPref";
    map["boolean"] = map[br.PREF_BOOL] = "BoolPref";
    map["number"] = map[br.PREF_INT] = "IntPref";
    return map;
})();

FirebugLoader.prefDomain = "extensions.firebug.";

FirebugLoader.getPref = function(prefDomain, name)
{
    var prefName;
    if (name == undefined)
        prefName = FirebugLoader.prefDomain + prefDomain;
    else
        prefName = prefDomain + "." + name;

    var prefs = Services.prefs;

    var type = prefTypeMap[prefs.getPrefType(prefName)];
    if (type)
        var value = prefs["get" + type](prefName);

    if (FBTrace.DBG_OPTIONS)
    {
        FBTrace.sysout("options.getPref " + prefName + " has type " +
            type + " and value " + value);
    }

    return value;
}

FirebugLoader.setPref = function(name, value)
{
    var prefName = FirebugLoader.prefDomain + name;
    var prefs = Services.prefs;

    var type = prefTypeMap[typeof value];
    if (type)
        value = prefs["set" + type](prefName, value);

    return value;
}

FirebugLoader.registerDefaultPrefs = function (prefMap, domain)
{
    prefMap = prefMap || this.defaultPrefs;
    domain = domain || this.prefDomain;
    var pb = Services.prefs.getDefaultBranch(domain);

    for (var name in prefMap)
    {
        var value = prefMap[name];
        var type = prefTypeMap[typeof value];

        pb["set" + type](name, value);
    }
}

// not really needed but someone on amo decided to require clearing default prefs
// clear only prefs that are not modified by user
// assumes that if "foo" isn't user modified "foo.*" are not modified as well
FirebugLoader.clearDefaultPrefs = function(domain)
{
    domain = domain || this.prefDomain;
    var pb = Services.prefs.getDefaultBranch(domain);

    var names = pb.getChildList("");
    for each (var name in names)
    {
        if (!pb.prefHasUserValue(name))
            pb.deleteBranch(name);
    }
}

// ********************************************************************************************* //
<|endoftext|>


<commit_before>var rackDragOpt = {
        containment: '#rackContainer',
        scroll: true,
        stack: '.rackG',
        grid: [ 10, 10 ],
        stop: function(event, ui) {
            $(this).draggable('option', 'revert', 'invalid');
            updateRackDimensions(ui.helper);
        }
    },
	rackDropOpt = {};

function updateRackDimensions(rack)
{
    if(typeof(rack) === 'undefined')
    {
        var rack = $('.rackG');
    }
    $(rack).each(function()
    {
        var id = getExactId($(this).find('.rackGform').find('div[id]').attr('id')),
            position = $(this).position(),
            left = position.left,
            bottom = parseInt($('#rackContainer').height() - position.top - $(this).outerHeight(true)) + 1,
			oldPosX = parseInt($(this).find('[id$="_posX"], [id$="_posx"]').val()),
			oldPosY = parseInt($(this).find('[id$="_posY"], [id$="_posy"]').val()),
	        selector = $(this).is('[flowPumpId]') ? 'flowPumps' : 'racks';
		if(oldPosX != left && oldPosY != bottom - 1)
		{
			clearCustomPos(this);
		}
		else if(oldPosX != left || oldPosY != bottom - 1)
		{
			clearCustomPos(this, oldPosX != left ? 'X' : 'Y');
		}
        $(this).find('#debb_configbundle_roomtype_' + selector + '_' + id + '_posX').val(left);
        $(this).find('#debb_configbundle_roomtype_' + selector + '_' + id + '_posY').val(bottom);
    });
}

function setStyleOfRack()
{
    var self = $(this).hasClass('draftRack') ? $(this) : $(this).find('.draftRack:first');
	if(self.hasClass('draftRack'))
	{
		var newRack = self.clone().removeClass('draftRack').addClass('rackG');

		var id = 0;
		$('.rackGform').each(function()
		{
			if(getExactId($(this).find('div[id!=""]').attr('id')) > id)
			{
				id = getExactId($(this).children('div').attr('id'));
				id++;
			}
		});
		id++;

		var prototype = $('#rackContainer').attr('data-prototype-' + (newRack.is('[flowPumpId]') ? 'flowpump' : 'rack')),
			newForm = prototype.replace(/__name__/g, id),
			newFormLi = $('

').append($(newForm).children('div'));
		newFormLi.find('#debb_configbundle_roomtype_' + (newRack.is('[flowPumpId]') ? 'flowPumps' : 'racks') + '_' + id + '_' + (newRack.is('[flowPumpId]') ? 'flowPump' : 'rack')).val(newRack.attr(newRack.is('[flowPumpId]') ? 'flowPumpId' : 'rackId'));
		newRack.append(newFormLi);

		newRack.appendTo('#rackContainer').draggable(rackDragOpt).droppable(rackDropOpt);

        newRack.prepend(' -
');
        newRack.addClass('rack0Deg');
	}
    else
    {
        var newRack = $(this);
    }
	newRack.css('width', (parseFloat(newRack.attr('rackx')) <= 0 ? 99 : parseFloat(newRack.attr('rackx')) * 100 - 1) + 'px');
	newRack.css('height', (parseFloat(newRack.attr('rackz')) <= 0 ? 99 : parseFloat(newRack.attr('rackz')) * 100 - 1) + 'px');
	if(typeof newRack.attr('posx') != 'undefined')
	{
		newRack.css('left', (parseInt(newRack.attr('posx')) < 0 ? 0 : parseInt(newRack.attr('posx'))) + 'px');
		newRack.removeAttr('posx');
	}
	if(typeof newRack.attr('posy') != 'undefined')
	{
		newRack.css('bottom', (parseInt(newRack.attr('posy')) < 0 ? $('#rackContainer').height() - newRack.outerHeight(true) : parseInt(newRack.attr('posy'))) + 'px');
		newRack.removeAttr('posy');
	}
    if(!newRack.is('[rotated]'))
    {
        var rotation = objToRot(newRack);
        newRack.css('border-' + rotToClass(rotation) + '-width', '4px');
        if(rotation == 90 || rotation == 270)
        {
            var rackHeight = newRack.height();
            newRack.height(newRack.width()).width(rackHeight);
        }
        if(rotation == 90 || rotation == 270)
        {
            newRack.width(newRack.width() - 3);
        }
        else
        {
            newRack.height(newRack.height() - 3);
        }
        newRack.attr('rotated', true);
    }
    updateRackDimensions(newRack);
}

function setMinimalRoomSize()
{
    var minX = 50,
        minY = 50;
    $('.rackG').each(function()
    {
        var thisX = $(this).position().left + $(this).outerWidth(true) - 1,
            thisY = $(this).position().top + $(this).outerHeight(true) - 1;
        if(thisX > minX)
        {
            minX = thisX;
        }
        if(thisY > minY)
        {
            minY = thisY;
        }
    });
	$('#rackContainer').resizable('option', 'minHeight', minY).resizable('option', 'minWidth', minX);
}

function objToRot(obj)
{
    var rot = parseInt($(obj).find('input[type="hidden"][id$="_rotation"][name$="[rotation]"]').val());
    return isNaN(rot) ? 0 : rot;
}

function rotToClass(rot)
{
    return rot > 0 && rot < 91 ? 'left' : (rot > 90 && rot < 181 ? 'top' : (rot > 180 && rot < 271 ? 'right' : 'bottom'));
}

/**
 * Clears the custom position of object
 * @param obj
 * @returns {jQuery}
 */
function clearCustomPos(obj, mode)
{
	var obj = typeof obj == 'undefined' ? $(this) : $(obj);
	obj.find('[name*="customPos' + (typeof mode == 'undefined' ? '' : mode) + '"]').val('');
	return obj;
}

/**
 * Generates the content of a rack popover (per click on rack)
 *
 * @returns {string} the data-content
 */
function generateTipContent()
{
    var obj = $(this),
        resObj = $('

'),
		posX = parseInt(obj.find('[name*="posX"]').val()),
		posY = parseInt(obj.find('[name*="posY"]').val()),
		posZ = obj.find('[name*="posZ"]'),
//		rotation = objToRot(obj),
		customPosX = obj.find('[name*="customPosX"]'),
		customPosY = obj.find('[name*="customPosY"]'),
		customPosZ = obj.find('[name*="customPosZ"]');

//	if(rotation == 90 || rotation == 180)
//	{
//		posY += obj.outerHeight(true);
//	}
//	if(rotation == 180 || rotation == 270)
//	{
//		posX += obj.outerWidth(true) - 1;
//	}

    resObj.append('
' + Translator.get('Size') + ': ' + obj.attr('rackx') + 'm /' + obj.attr('racky') + 'm /' + obj.attr('rackz') + 'm' + '
');
    resObj.append($('
' + Translator.get('Actions') + ':
').append(' - '
		+ '

X: <input type="text" style="width: 100px;" value="' + customPosX.val() + '" class="syncwith" syncwith="#' + customPosX.attr('id') + '" placeholder="' + (posX / 100) + '" />m'
		+ '
Y: <input type="text" style="width: 100px;" value="' + customPosY.val() + '" class="syncwith" syncwith="#' + customPosY.attr('id') + '" placeholder="' + (posY / 100) + '" />m'
		+ '
Z: <input type="text" style="width: 100px;" value="' + customPosZ.val() + '" class="syncwith" syncwith="#' + customPosZ.attr('id') + '" placeholder="' + (posZ.val() / 100) + '" />m'));
	return resObj;
}

$(function()
{
	$('.eDraftRack').on('click', setStyleOfRack);
	// dynamic size for our room
	$('#rackContainer').resizable({
		grid: 10,
		stop: function( event, ui ) {
			$('#debb_configbundle_roomtype_sizeX').val(ui.helper.width().toFixed(0));
			$('#debb_configbundle_roomtype_sizeZ').val(ui.helper.height().toFixed(0));
            updateRackDimensions();
		},
		resize: function ( event, ui ) {
			$('#rackSizeX').html((parseInt(ui.size.width) / 100).toFixed(2));
			$('#rackSizeZ').html((parseInt(ui.size.height) / 100).toFixed(2));
            $('#content').width(parseInt(ui.size.width) + 21);
            ui.helper.css('background-position', '1px ' + parseInt(parseInt(ui.size.height) + 1) + 'px');
		},
        start: function ( event, ui ) {
            setMinimalRoomSize();
        }
	}).droppable({tolerance: 'fit'});
	$(document).on('click', '.removeRack', function(e)
	{
		e.preventDefault();
        var obj = $(this).parents('.rackG:first, .popover:first');
        if(obj.is('.popover'))
        {
            obj = obj.prev('.rackG');
        }
        if(typeof(obj.data('popover')) != 'undefined')
        {
            obj.popover('destroy');
        }
        obj.remove();
	});
	// Copied to /src/Debb/ManagementBundle/Resources/public/js/chassis.js:116
    $(document).on('change, keyup', '.syncwith[syncwith]', function(e)
    {
        var obj = $($(this).attr('syncwith'));
        if(obj.length > 0)
        {
            var val = $(this).val();
            if(typeof($(this).attr('maxval')) != 'undefined')
            {
                var maxval = parseFloat($($(this).attr('maxval')).val());
                if(parseFloat(val) > maxval)
                {
                    val = maxval;
                    $(this).val(maxval);
                    e.preventDefault();
                }
            }
            obj.val(val);
        }
    });
    $(document).on('click', '.rotateRack', function(e)
    {
        e.preventDefault();
        var obj = $(this).parents('.rackG:first, .popover:first'),
            rack = obj.is('.popover') ? obj.prev('.rackG') : obj,
            rotation = objToRot(rack);
        rack.css('border-' + rotToClass(rotation) + '-width', '1px');
        rotation += 90;
        if ( rotation > 270 ) { rotation = 0; }
        rack.find('input[id$="_rotation"]').val(rotation);

        var newRack = rack;
        newRack.css('width', (parseFloat(newRack.attr('rackx')) <= 0 ? 99 : parseFloat(newRack.attr('rackx')) * 100 - 1) + 'px');
        newRack.css('height', (parseFloat(newRack.attr('rackz')) <= 0 ? 99 : parseFloat(newRack.attr('rackz')) * 100 - 1) + 'px');
        newRack.css('border-' + rotToClass(rotation) + '-width', '4px');
        if(rotation == 90 || rotation == 270)
        {
            var rackHeight = newRack.height();
            newRack.height(newRack.width()).width(rackHeight);
        }
        if(rotation == 90 || rotation == 270)
        {
            newRack.width(newRack.width() - 3);
        }
        else
        {
            newRack.height(newRack.height() - 3);
        }
        newRack.find('.rotateRack .icon-repeat').css('transform', 'rotateZ(' + (rotation + 90) + 'deg)');
        if(newRack.next().is('.popover'))
        {
            newRack.next('.popover').find('.rotateRack .icon-repeat').css('transform', 'rotateZ(' + (rotation + 90) + 'deg)');
        }
    });
    $(document).on('click', '.rackG', function(e)
    {
        if($(e.target).is('div.rackG'))
        {
            e.preventDefault();
            var mainObj = $(this);
            if(typeof(mainObj.data('popover')) == 'undefined')
            {
                mainObj.popover({html: true, trigger: 'manual', content: generateTipContent}).popover('show');
            }
            else
            {
                mainObj.popover(mainObj.next('div').is('.popover.in:visible') ? 'hide' : 'show');
            }
        }
    });
	// a single rack which we could move in our room
	$('.rackG').draggable(rackDragOpt).droppable(rackDropOpt);
	$('.rackG').each(setStyleOfRack);
    $('.rackG').each(function() { $(this).css('top', $(this).position().top + 1); });
    $('.rackG').popover({html: true, trigger: 'manual', content: generateTipContent});
});
<commit_msg>Fixed bug with display wrong numbers<commit_after>var rackDragOpt = {
        containment: '#rackContainer',
        scroll: true,
        stack: '.rackG',
        grid: [ 10, 10 ],
        stop: function(event, ui) {
            $(this).draggable('option', 'revert', 'invalid');
            updateRackDimensions(ui.helper);
        }
    },
	rackDropOpt = {};

function updateRackDimensions(rack)
{
    if(typeof(rack) === 'undefined')
    {
        var rack = $('.rackG');
    }
    $(rack).each(function()
    {
        var id = getExactId($(this).find('.rackGform').find('div[id]').attr('id')),
            position = $(this).position(),
            left = position.left,
            bottom = parseInt($('#rackContainer').height() - position.top - $(this).outerHeight(true)) + 1,
			oldPosX = parseInt($(this).find('[id$="_posX"], [id$="_posx"]').val()),
			oldPosY = parseInt($(this).find('[id$="_posY"], [id$="_posy"]').val()),
	        selector = $(this).is('[flowPumpId]') ? 'flowPumps' : 'racks';
		if(oldPosX != left && oldPosY != bottom - 1)
		{
			clearCustomPos(this);
		}
		else if(oldPosX != left || oldPosY != bottom - 1)
		{
			clearCustomPos(this, oldPosX != left ? 'X' : 'Y');
		}
        $(this).find('#debb_configbundle_roomtype_' + selector + '_' + id + '_posX').val(left);
        $(this).find('#debb_configbundle_roomtype_' + selector + '_' + id + '_posY').val(bottom);
    });
}

function setStyleOfRack()
{
    var self = $(this).hasClass('draftRack') ? $(this) : $(this).find('.draftRack:first');
	if(self.hasClass('draftRack'))
	{
		var newRack = self.clone().removeClass('draftRack').addClass('rackG');

		var id = 0;
		$('.rackGform').each(function()
		{
			if(getExactId($(this).find('div[id!=""]').attr('id')) > id)
			{
				id = getExactId($(this).children('div').attr('id'));
				id++;
			}
		});
		id++;

		var prototype = $('#rackContainer').attr('data-prototype-' + (newRack.is('[flowPumpId]') ? 'flowpump' : 'rack')),
			newForm = prototype.replace(/__name__/g, id),
			newFormLi = $('

').append($(newForm).children('div'));
		newFormLi.find('#debb_configbundle_roomtype_' + (newRack.is('[flowPumpId]') ? 'flowPumps' : 'racks') + '_' + id + '_' + (newRack.is('[flowPumpId]') ? 'flowPump' : 'rack')).val(newRack.attr(newRack.is('[flowPumpId]') ? 'flowPumpId' : 'rackId'));
		newRack.append(newFormLi);

		newRack.appendTo('#rackContainer').draggable(rackDragOpt).droppable(rackDropOpt);

        newRack.prepend(' -
');
        newRack.addClass('rack0Deg');
	}
    else
    {
        var newRack = $(this);
    }
	newRack.css('width', (parseFloat(newRack.attr('rackx')) <= 0 ? 99 : parseFloat(newRack.attr('rackx')) * 100 - 1) + 'px');
	newRack.css('height', (parseFloat(newRack.attr('rackz')) <= 0 ? 99 : parseFloat(newRack.attr('rackz')) * 100 - 1) + 'px');
	if(typeof newRack.attr('posx') != 'undefined')
	{
		newRack.css('left', (parseInt(newRack.attr('posx')) < 0 ? 0 : parseInt(newRack.attr('posx'))) + 'px');
		newRack.removeAttr('posx');
	}
	if(typeof newRack.attr('posy') != 'undefined')
	{
		newRack.css('bottom', (parseInt(newRack.attr('posy')) < 0 ? $('#rackContainer').height() - newRack.outerHeight(true) : parseInt(newRack.attr('posy'))) + 'px');
		newRack.removeAttr('posy');
	}
    if(!newRack.is('[rotated]'))
    {
        var rotation = objToRot(newRack);
        newRack.css('border-' + rotToClass(rotation) + '-width', '4px');
        if(rotation == 90 || rotation == 270)
        {
            var rackHeight = newRack.height();
            newRack.height(newRack.width()).width(rackHeight);
        }
        if(rotation == 90 || rotation == 270)
        {
            newRack.width(newRack.width() - 3);
        }
        else
        {
            newRack.height(newRack.height() - 3);
        }
        newRack.attr('rotated', true);
    }
    updateRackDimensions(newRack);
}

function setMinimalRoomSize()
{
    var minX = 50,
        minY = 50;
    $('.rackG').each(function()
    {
        var thisX = $(this).position().left + $(this).outerWidth(true) - 1,
            thisY = $(this).position().top + $(this).outerHeight(true) - 1;
        if(thisX > minX)
        {
            minX = thisX;
        }
        if(thisY > minY)
        {
            minY = thisY;
        }
    });
	$('#rackContainer').resizable('option', 'minHeight', minY).resizable('option', 'minWidth', minX);
}

function objToRot(obj)
{
    var rot = parseInt($(obj).find('input[type="hidden"][id$="_rotation"][name$="[rotation]"]').val());
    return isNaN(rot) ? 0 : rot;
}

function rotToClass(rot)
{
    return rot > 0 && rot < 91 ? 'left' : (rot > 90 && rot < 181 ? 'top' : (rot > 180 && rot < 271 ? 'right' : 'bottom'));
}

/**
 * Clears the custom position of object
 * @param obj
 * @returns {jQuery}
 */
function clearCustomPos(obj, mode)
{
	var obj = typeof obj == 'undefined' ? $(this) : $(obj);
	obj.find('[name*="customPos' + (typeof mode == 'undefined' ? '' : mode) + '"]').val('');
	return obj;
}

/**
 * Generates the content of a rack popover (per click on rack)
 *
 * @returns {string} the data-content
 */
function generateTipContent()
{
    var obj = $(this),
        resObj = $('

'),
		posX = parseInt(obj.find('[name*="posX"]').val()),
		posY = parseInt(obj.find('[name*="posY"]').val()),
		posZ = obj.find('[name*="posZ"]'),
//		rotation = objToRot(obj),
		customPosX = obj.find('[name*="customPosX"]'),
		customPosY = obj.find('[name*="customPosY"]'),
		customPosZ = obj.find('[name*="customPosZ"]');

//	if(rotation == 90 || rotation == 180)
//	{
//		posY += obj.outerHeight(true);
//	}
//	if(rotation == 180 || rotation == 270)
//	{
//		posX += obj.outerWidth(true) - 1;
//	}

    resObj.append('
' + Translator.get('Size') + ': ' + obj.attr('rackx') + 'm /' + obj.attr('racky') + 'm /' + obj.attr('rackz') + 'm' + '
');
    resObj.append($('
' + Translator.get('Actions') + ':
').append(' - '
		+ '

X: <input type="text" style="width: 100px;" value="' + customPosX.val() + '" class="syncwith" syncwith="#' + customPosX.attr('id') + '" placeholder="' + toNextTen(posX / 100) + '" />m'
		+ '
Y: <input type="text" style="width: 100px;" value="' + customPosY.val() + '" class="syncwith" syncwith="#' + customPosY.attr('id') + '" placeholder="' + toNextTen(posY / 100) + '" />m'
		+ '
Z: <input type="text" style="width: 100px;" value="' + customPosZ.val() + '" class="syncwith" syncwith="#' + customPosZ.attr('id') + '" placeholder="' + toNextTen(posZ.val() / 100) + '" />m'));
	return resObj;
}

function toNextTen(decimal)
{
	return Math.round(parseFloat(decimal) * 10) / 10;
}

$(function()
{
	$('.eDraftRack').on('click', setStyleOfRack);
	// dynamic size for our room
	$('#rackContainer').resizable({
		grid: 10,
		stop: function( event, ui ) {
			$('#debb_configbundle_roomtype_sizeX').val(ui.helper.width().toFixed(0));
			$('#debb_configbundle_roomtype_sizeZ').val(ui.helper.height().toFixed(0));
            updateRackDimensions();
		},
		resize: function ( event, ui ) {
			$('#rackSizeX').html((parseInt(ui.size.width) / 100).toFixed(2));
			$('#rackSizeZ').html((parseInt(ui.size.height) / 100).toFixed(2));
            $('#content').width(parseInt(ui.size.width) + 21);
            ui.helper.css('background-position', '1px ' + parseInt(parseInt(ui.size.height) + 1) + 'px');
		},
        start: function ( event, ui ) {
            setMinimalRoomSize();
        }
	}).droppable({tolerance: 'fit'});
	$(document).on('click', '.removeRack', function(e)
	{
		e.preventDefault();
        var obj = $(this).parents('.rackG:first, .popover:first');
        if(obj.is('.popover'))
        {
            obj = obj.prev('.rackG');
        }
        if(typeof(obj.data('popover')) != 'undefined')
        {
            obj.popover('destroy');
        }
        obj.remove();
	});
	// Copied to /src/Debb/ManagementBundle/Resources/public/js/chassis.js:116
    $(document).on('change, keyup', '.syncwith[syncwith]', function(e)
    {
        var obj = $($(this).attr('syncwith'));
        if(obj.length > 0)
        {
            var val = $(this).val();
            if(typeof($(this).attr('maxval')) != 'undefined')
            {
                var maxval = parseFloat($($(this).attr('maxval')).val());
                if(parseFloat(val) > maxval)
                {
                    val = maxval;
                    $(this).val(maxval);
                    e.preventDefault();
                }
            }
            obj.val(val);
        }
    });
    $(document).on('click', '.rotateRack', function(e)
    {
        e.preventDefault();
        var obj = $(this).parents('.rackG:first, .popover:first'),
            rack = obj.is('.popover') ? obj.prev('.rackG') : obj,
            rotation = objToRot(rack);
        rack.css('border-' + rotToClass(rotation) + '-width', '1px');
        rotation += 90;
        if ( rotation > 270 ) { rotation = 0; }
        rack.find('input[id$="_rotation"]').val(rotation);

        var newRack = rack;
        newRack.css('width', (parseFloat(newRack.attr('rackx')) <= 0 ? 99 : parseFloat(newRack.attr('rackx')) * 100 - 1) + 'px');
        newRack.css('height', (parseFloat(newRack.attr('rackz')) <= 0 ? 99 : parseFloat(newRack.attr('rackz')) * 100 - 1) + 'px');
        newRack.css('border-' + rotToClass(rotation) + '-width', '4px');
        if(rotation == 90 || rotation == 270)
        {
            var rackHeight = newRack.height();
            newRack.height(newRack.width()).width(rackHeight);
        }
        if(rotation == 90 || rotation == 270)
        {
            newRack.width(newRack.width() - 3);
        }
        else
        {
            newRack.height(newRack.height() - 3);
        }
        newRack.find('.rotateRack .icon-repeat').css('transform', 'rotateZ(' + (rotation + 90) + 'deg)');
        if(newRack.next().is('.popover'))
        {
            newRack.next('.popover').find('.rotateRack .icon-repeat').css('transform', 'rotateZ(' + (rotation + 90) + 'deg)');
        }
    });
    $(document).on('click', '.rackG', function(e)
    {
        if($(e.target).is('div.rackG'))
        {
            e.preventDefault();
            var mainObj = $(this);
            if(typeof(mainObj.data('popover')) == 'undefined')
            {
                mainObj.popover({html: true, trigger: 'manual', content: generateTipContent}).popover('show');
            }
            else
            {
                mainObj.popover(mainObj.next('div').is('.popover.in:visible') ? 'hide' : 'show');
            }
        }
    });
	// a single rack which we could move in our room
	$('.rackG').draggable(rackDragOpt).droppable(rackDropOpt);
	$('.rackG').each(setStyleOfRack);
    $('.rackG').each(function() { $(this).css('top', $(this).position().top + 1); });
    $('.rackG').popover({html: true, trigger: 'manual', content: generateTipContent});
});
<|endoftext|>


<commit_before>export default {
  Enter: '\r',
  Left: '\x1b[D',
  Right: '\x1b[C',
  Up: '\x1b[A',
  Down: '\x1b[B',
  PgUp: '\x1b[5~',
  PgDown: '\x1b[6~',
  Home: '\x1b[1~',
  End: '\x1b[4~',
  CtrlZ: '\x1a',
  CtrlP: '\x10',
};
<commit_msg>add backspace key<commit_after>export default {
  Enter: '\r',
  ArrowLeft: '\x1b[D',
  ArrowRight: '\x1b[C',
  ArrowUp: '\x1b[A',
  ArrowDown: '\x1b[B',
  PgUp: '\x1b[5~',
  PgDown: '\x1b[6~',
  Home: '\x1b[1~',
  End: '\x1b[4~',
  Backspace: '\b',
  CtrlZ: '\x1a',
  CtrlP: '\x10',
};
<|endoftext|>


<commit_before>/*
* The MIT License (MIT)
*
* Product:      Paypal Basket
* Description:  A simple basket & product manager for the PayPal-node-SDK
*
* Copyright (c) 2017 Steven Agyekum <agyekum@posteo.de>
*
* 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.
*
*/

var paypal = require('paypal-rest-sdk')
  , Basket = require('paypal-basket').Basket
  , Product = require('paypal-basket').Product;

/* Configure paypal sdk */
paypal.configure({
  mode: 'sandbox',
  client_id: '',
  client_secret: ''
});

/* A JSON collection of music albums */
var albums = [
  {
    "sku": "davidguettalisten",
    "name": "David Guetta - Listen",
    "price": "5.00"
  },
  {
    "sku": "michaeljacksonworld",
    "name": "Michael Jackson - World",
    "price": "10.00"
  },
  {
    "sku": "simplyredthrillme",
    "name": "Simply Red - Thrill me",
    "price": "10.00"
  }
];

/*
  A collection of music products
  to contain the actual album products
*/
var products = {};

/*
  Create products from albums
  and push to collection
*/
for( var index in albums ) {
  var album = albums[index];
  products[album.sku] = new Product(album);
}

/*
  From here on you can access a product like:

  products['michaeljacksonworld']
  products['davidguettalisten']
*/

/* Create a basket (eg. for a customer) */
var sessionxyzBasket = new Basket({
  label: 'Basket of session xyz',
  urls: {
    return_url: 'http://return.url',
    cancel_url: 'http://cancel.url'
  }
});

/*
  Now let the customer add/del
  some products to/from their basket.
  Presumeble by a website
*/
sessionxyzBasket.add(products['davidguettalisten'])
.then(sessionxyzBasket.add(products['michaeljacksonworld']))
.then(sessionxyzBasket.add(products['simplyredthrillme']))
.then(sessionxyzBasket.del(products['davidguettalisten']));

/* Print current total */
console.log('Current total is: $' + sessionxyzBasket.total);

/*
  Now sell the basket (generate manifest)
  and request actual payment details
*/

/* Promise invocation */
sessionxyzBasket.sell( { 'currency': 'USD' } )
.then( function(manifest) {
  console.log("Payment Response:");
  console.log(manifest.payment);
})
.catch( function(err) { console.log(err) } );

/* Nodeback invocation */
sessionxyzBasket.sell( { 'currency': 'USD' }, function(err, manifest) {
  if( err ) { return console.log(err) }

  console.log("Payment Response:");
  console.log(manifest.payment);
});
<commit_msg>edited music store es5 sample to reflect latest changes<commit_after>/*
* The MIT License (MIT)
*
* Product:      Paypal Basket
* Description:  A simple basket & product manager for the PayPal-node-SDK
*
* Copyright (c) 2017 Steven Agyekum <agyekum@posteo.de>
*
* 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.
*
*/

var Paypal = require('paypal-basket').Paypal
  , Basket = require('paypal-basket').Basket
  , Product = require('paypal-basket').Product;

/* Configure paypal sdk */
Paypal.configure({
  mode: 'sandbox',
  client_id: '',
  client_secret: ''
});

/* A JSON collection of music albums */
var albums = [
  {
    "sku": "davidguettalisten",
    "name": "David Guetta - Listen",
    "price": "5.00"
  },
  {
    "sku": "michaeljacksonworld",
    "name": "Michael Jackson - World",
    "price": "10.00"
  },
  {
    "sku": "simplyredthrillme",
    "name": "Simply Red - Thrill me",
    "price": "10.00"
  }
];

/*
  A collection of music products
  to contain the actual album products
*/
var products = {};

/*
  Create products from albums
  and push to collection
*/
for( var index in albums ) {
  var album = albums[index];
  products[album.sku] = new Product(album);
}

/*
  From here on you can access a product like:

  products['michaeljacksonworld']
  products['davidguettalisten']
*/

/* Create a basket (eg. for a customer) */
var sessionxyzBasket = new Basket({
  label: 'Basket of session xyz',
  urls: {
    return_url: 'http://return.url',
    cancel_url: 'http://cancel.url'
  }
});

/*
  Now let the customer add/del
  some products to/from their basket.
  Presumeble by a website
*/
sessionxyzBasket.add(products['davidguettalisten'])
.then(sessionxyzBasket.add(products['michaeljacksonworld']))
.then(sessionxyzBasket.add(products['simplyredthrillme']))
.then(sessionxyzBasket.del(products['davidguettalisten']));

/* Print current total */
console.log('Current total is: $' + sessionxyzBasket.total);

/*
  Now sell the basket (generate manifest)
  and request actual payment details
*/

/* Promise invocation */
sessionxyzBasket.sell( { 'currency': 'USD' } )
.then( function(manifest) {
  console.log("Payment Response:");
  console.log(manifest.payment);
})
.catch( function(err) { console.log(err) } );

/* Nodeback invocation */
sessionxyzBasket.sell( { 'currency': 'USD' }, function(err, manifest) {
  if( err ) { return console.log(err) }

  console.log("Payment Response:");
  console.log(manifest.payment);
});
<|endoftext|>


<commit_before>import { sendAds, mergeAds, updateBadge } from "utils.js";

chrome.runtime.onMessage.addListener((ads) => {
  if(!localStorage.getItem("redux")) return;
  try {
    const redux = JSON.parse(localStorage.getItem("redux"));
    if(!redux.terms) return;
  } catch(e) {
    console.log(e);
    return;
  }
  let saved = new Set();
  try {
    let store = JSON.parse(localStorage.getItem("redux"));
    store.ratings.map((ad) => saved.add(ad.id));
    store.ratings = mergeAds(store.ratings || [], ads);
    localStorage.setItem('redux', JSON.stringify(store));
    updateBadge(store.ratings);
  } catch(e) {
    console.log(e);
  }
  const saving = ads.filter((ad) => !saved.has(ad.id));
  const success = () => console.log("saved");
  const failure = (e) => console.log(e);
  if(saving.length > 0) sendAds(saving).then(success, failure);
});
<commit_msg>remove extra log<commit_after>import { sendAds, mergeAds, updateBadge } from "utils.js";

chrome.runtime.onMessage.addListener((ads) => {
  if(!localStorage.getItem("redux")) return;
  try {
    const redux = JSON.parse(localStorage.getItem("redux"));
    if(!redux.terms) return;
  } catch(e) {
    return;
  }
  let saved = new Set();
  try {
    let store = JSON.parse(localStorage.getItem("redux"));
    store.ratings.map((ad) => saved.add(ad.id));
    store.ratings = mergeAds(store.ratings || [], ads);
    localStorage.setItem('redux', JSON.stringify(store));
    updateBadge(store.ratings);
  } catch(e) {
    console.log(e);
  }
  const saving = ads.filter((ad) => !saved.has(ad.id));
  const success = () => console.log("saved");
  const failure = (e) => console.log(e);
  if(saving.length > 0) sendAds(saving).then(success, failure);
});
<|endoftext|>


<commit_before>/**
 * Copyright 2018 The Subscribe with Google 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.
 */

import * as sinon from 'sinon';
import {assert, debugLog} from './log';

describes.realWin('debug log', {}, () => {
  const sandbox = sinon.sandbox.create();
  let log;

  beforeEach(() => {
    log = sandbox.spy(console, 'log');
  });

  afterEach(() => {
    log.restore();
  });

  it('should log if swg.dbg=1', () => {
    self.location.hash = 'swg.dbg=1';
    debugLog('Hello World');
    expect(console.log.calledWith('Subscriptions:', 'Hello World')).to.be.true;
  });

  it('should handle multiple arguments', () => {
    self.location.hash = 'swg.dbg=1';
    debugLog('Hello', 'World');
    expect(console.log.calledWith('Subscriptions:', 'Hello', 'World'))
        .to.be.true;
  });

  it('should not log if swg.dbg=1 is not present', () => {
    self.location.hash = '';
    debugLog('Hello World');
    expect(console.log.notCalled).to.be.true;
  });
});

describes.realWin('asserts', {}, env => {
  let win;

  beforeEach(() => {
    win = env.win;
  });

  it('should fail', () => {
    expect(function() {
      assert(false, 'xyz');
    }).to.throw(/xyz/);
    try {
      assert(false, '123');
    } catch (e) {
      expect(e.message).to.equal('123');
      return;
    }
    // Unreachable
    expect(false).to.be.true;
  });

  it('should not fail', () => {
    assert(true, 'True!');
    assert(1, '1');
    assert('abc', 'abc');
  });

  it('should substitute', () => {
    expect(function() {
      assert(false, 'should fail %s', 'XYZ');
    }).to.throw(/should fail XYZ/);
    expect(function() {
      assert(false, 'should fail %s %s', 'XYZ', 'YYY');
    }).to.throw(/should fail XYZ YYY/);
    const div = win.document.createElement('div');
    div.id = 'abc';
    div.textContent = 'foo';
    expect(function() {
      assert(false, 'should fail %s', div);
    }).to.throw(/should fail div#abc/);

    let error;
    try {
      assert(false, '%s a %s b %s', 1, 2, 3);
    } catch (e) {
      error = e;
    }
    expect(error).to.be.instanceof(Error);
    expect(error.message).to.equal('1 a 2 b 3');
    expect(error.messageArray).to.deep.equal([1, 'a', 2, 'b', 3]);
  });

  it('should add element and assert info', () => {
    const div = win.document.createElement('div');
    let error;
    try {
      assert(false, '%s a %s b %s', div, 2, 3);
    } catch (e) {
      error = e;
    }
    expect(error).to.be.instanceof(Error);
    expect(error.associatedElement).to.equal(div);
    expect(error.fromAssert).to.equal(true);
  });
});
<commit_msg>update test<commit_after>/**
 * Copyright 2018 The Subscribe with Google 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.
 */

import * as sinon from 'sinon';
import {assert, debugLog} from './log';

describes.realWin('debug log', {}, () => {
  const sandbox = sinon.sandbox.create();
  let log;

  beforeEach(() => {
    log = sandbox.spy(console, 'log');
  });

  afterEach(() => {
    log.restore();
  });

  it('should log if swg.dbg=1', () => {
    self.location.hash = 'swg.dbg=1';
    debugLog('Hello World');
    expect(console.log.calledWith('[Subscriptions]', 'Hello World')).to.be.true;
  });

  it('should handle multiple arguments', () => {
    self.location.hash = 'swg.dbg=1';
    debugLog('Hello', 'World');
    expect(console.log.calledWith('[Subscriptions]', 'Hello', 'World'))
        .to.be.true;
  });

  it('should not log if swg.dbg=1 is not present', () => {
    self.location.hash = '';
    debugLog('Hello World');
    expect(console.log.notCalled).to.be.true;
  });
});

describes.realWin('asserts', {}, env => {
  let win;

  beforeEach(() => {
    win = env.win;
  });

  it('should fail', () => {
    expect(function() {
      assert(false, 'xyz');
    }).to.throw(/xyz/);
    try {
      assert(false, '123');
    } catch (e) {
      expect(e.message).to.equal('123');
      return;
    }
    // Unreachable
    expect(false).to.be.true;
  });

  it('should not fail', () => {
    assert(true, 'True!');
    assert(1, '1');
    assert('abc', 'abc');
  });

  it('should substitute', () => {
    expect(function() {
      assert(false, 'should fail %s', 'XYZ');
    }).to.throw(/should fail XYZ/);
    expect(function() {
      assert(false, 'should fail %s %s', 'XYZ', 'YYY');
    }).to.throw(/should fail XYZ YYY/);
    const div = win.document.createElement('div');
    div.id = 'abc';
    div.textContent = 'foo';
    expect(function() {
      assert(false, 'should fail %s', div);
    }).to.throw(/should fail div#abc/);

    let error;
    try {
      assert(false, '%s a %s b %s', 1, 2, 3);
    } catch (e) {
      error = e;
    }
    expect(error).to.be.instanceof(Error);
    expect(error.message).to.equal('1 a 2 b 3');
    expect(error.messageArray).to.deep.equal([1, 'a', 2, 'b', 3]);
  });

  it('should add element and assert info', () => {
    const div = win.document.createElement('div');
    let error;
    try {
      assert(false, '%s a %s b %s', div, 2, 3);
    } catch (e) {
      error = e;
    }
    expect(error).to.be.instanceof(Error);
    expect(error.associatedElement).to.equal(div);
    expect(error.fromAssert).to.equal(true);
  });
});
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import { Row, Col, Button, Panel, Glyphicon, Form, Radio, Checkbox, FormGroup, ControlLabel, FormControl } from 'react-bootstrap'
import update from 'react-addons-update'
import { shallowEqual } from 'react-pure-render'

import { getMessage, getComponentMessages } from '../../common/util/config'

export default class DeploymentSettings extends Component {
  constructor (props) {
    super(props)
    this.state = {
      deployment: {
        buildConfig: {},
        routerConfig: {},
        otpServers: this.props.project && this.props.project.otpServers ? this.props.project.otpServers : []
      }
    }
  }
  componentWillReceiveProps (nextProps) {
    this.setState({
      deployment: {
        buildConfig: {},
        routerConfig: {},
        otpServers: nextProps.project && nextProps.project.otpServers ? nextProps.project.otpServers : []
      }
    })
  }
  shouldComponentUpdate (nextProps, nextState) {
    return !shallowEqual(nextProps, this.props) || !shallowEqual(nextState, this.state)
  }
  render () {
    console.log(this.state)
    const messages = getComponentMessages('ProjectSettings')
    const { project, editDisabled, updateProjectSettings } = this.props
    const noEdits = Object.keys(this.state.deployment.buildConfig).length === 0 &&
      Object.keys(this.state.deployment.routerConfig).length === 0 &&
      shallowEqual(this.state.deployment.otpServers, project.otpServers)
    return (

        <Panel header={
{getMessage(messages, 'deployment.buildConfig.title')}
}>
          <Row>
            <Col xs={6}>
              <FormGroup>
                <FormControl
                  componentClass='select'
                  defaultValue={project.buildConfig && project.buildConfig.fetchElevationUS ? project.buildConfig.fetchElevationUS : ''}
                  label={getMessage(messages, 'deployment.buildConfig.fetchElevationUS')}
                  ref='fetchElevationUS'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { buildConfig: { fetchElevationUS: { $set: (evt.target.value === 'true') } } } }
                    this.setState(update(this.state, stateUpdate))
                  }}>
                  <option value='false'>false</option>
                  <option value='true'>true</option>
                </FormControl>
              </FormGroup>
            </Col>
            <Col xs={6}>
              <FormGroup>
                <FormControl
                  componentClass='select'
                  defaultValue={project.buildConfig && project.buildConfig.stationTransfers ? project.buildConfig.stationTransfers : ''}
                  label={getMessage(messages, 'deployment.buildConfig.stationTransfers')}
                  ref='stationTransfers'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { buildConfig: { stationTransfers: { $set: (evt.target.value === 'true') } } } }
                    this.setState(update(this.state, stateUpdate))
                  }}>
                  <option value='false'>false</option>
                  <option value='true'>true</option>
                </FormControl>
              </FormGroup>
            </Col>
          </Row>
          <FormGroup>
            <FormControl
              defaultValue={project.buildConfig && project.buildConfig.subwayAccessTime ? project.buildConfig.subwayAccessTime : ''}
              placeholder='2.5 (min)'
              label={getMessage(messages, 'deployment.buildConfig.subwayAccessTime')}
              ref='subwayAccessTime'
              onChange={(evt) => {
                let stateUpdate = { deployment: { buildConfig: { subwayAccessTime: { $set: +evt.target.value } } } }
                this.setState(update(this.state, stateUpdate))
              }} />
          </FormGroup>
          <FormGroup>
            <FormControl
              defaultValue={project.buildConfig && project.buildConfig.fares ? project.buildConfig.fares : ''}
              placeholder='fares'
              label={getMessage(messages, 'deployment.buildConfig.fares')}
              ref='fares'
              onChange={(evt) => {
                let stateUpdate = { deployment: { buildConfig: { fares: { $set: evt.target.value } } } }
                this.setState(update(this.state, stateUpdate))
              }} />
          </FormGroup>
        </Panel>
        <Panel header={
Router Config
}>
          <Row>
            <Col xs={6}>
              <FormGroup>
                <FormControl
                  type='integer'
                  defaultValue={project.routerConfig && project.routerConfig.numItineraries ? project.routerConfig.numItineraries : ''}
                  placeholder='6'
                  label={getMessage(messages, 'deployment.buildConfig.numItineraries')}
                  ref='numItineraries'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { routerConfig: { numItineraries: { $set: +evt.target.value } } } }
                    this.setState(update(this.state, stateUpdate))
                  }} />
              </FormGroup>
            </Col>
            <Col xs={6}>
              <FormGroup>
                <FormControl
                  type='number'
                  defaultValue={project.routerConfig && project.routerConfig.walkSpeed ? project.routerConfig.walkSpeed : ''}
                  placeholder='3.0'
                  label={getMessage(messages, 'deployment.buildConfig.walkSpeed')}
                  ref='walkSpeed'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { routerConfig: { walkSpeed: { $set: +evt.target.value } } } }
                    this.setState(update(this.state, stateUpdate))
                  }} />
              </FormGroup>
            </Col>
          </Row>
          <Row>
            <Col xs={6}>
              <FormGroup>
                <FormControl
                  type='number'
                  defaultValue={project.routerConfig && project.routerConfig.stairsReluctance ? project.routerConfig.stairsReluctance : ''}
                  placeholder='2.0'
                  label={getMessage(messages, 'deployment.buildConfig.stairsReluctance')}
                  ref='stairsReluctance'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { routerConfig: { stairsReluctance: { $set: +evt.target.value } } } }
                    this.setState(update(this.state, stateUpdate))
                  }} />
              </FormGroup>
            </Col>
            <Col xs={6}>
              <FormGroup>
                <FormControl
                  type='number'
                  defaultValue={project.routerConfig && project.routerConfig.carDropoffTime ? project.routerConfig.carDropoffTime : ''}
                  placeholder='240 (sec)'
                  label={getMessage(messages, 'deployment.buildConfig.carDropoffTime')}
                  ref='carDropoffTime'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { routerConfig: { carDropoffTime: { $set: +evt.target.value } } } }
                    this.setState(update(this.state, stateUpdate))
                  }} />
              </FormGroup>
            </Col>
          </Row>
          <FormGroup>
            <FormControl
              type='text'
              defaultValue={project.routerConfig && project.routerConfig.brandingUrlRoot ? project.routerConfig.brandingUrlRoot : ''}
              placeholder='http://gtfs.example.com/branding'
              label={getMessage(messages, 'deployment.buildConfig.brandingUrlRoot')}
              ref='brandingUrlRoot'
              onChange={(evt) => {
                let stateUpdate = { deployment: { routerConfig: { brandingUrlRoot: { $set: evt.target.value } } } }
                this.setState(update(this.state, stateUpdate))
              }} />
          </FormGroup>
        </Panel>
        <Panel header={

            <Button
              className='pull-right'
              bsStyle='success'
              bsSize='xsmall'
              onClick={() => {
                let stateUpdate = { deployment: { otpServers: { $push: [{name: '', publicUrl: '', internalUrl: [], admin: false}] } } }
                this.setState(update(this.state, stateUpdate))
              }}>
              <Glyphicon glyph='plus' /> {getMessage(messages, 'deployment.servers.new')}
            </Button>
            {getMessage(messages, 'deployment.servers.title')}

        }>

            {this.state.deployment.otpServers && this.state.deployment.otpServers.map((server, i) => {
              let title = (

                  {server.name}{'  '}
                  {server.publicUrl}

              )
              return (
                <Panel key={i}
                  header={server.name ? title : `[${getMessage(messages, 'deployment.servers.serverPlaceholder')}]`}
                  defaultExpanded={server.name === ''}
                  collapsible>
                  <Form>
                    <Button
                      bsSize='xsmall'
                      bsStyle='danger'
                      className='pull-right'
                      onClick={() => {
                        let stateUpdate = { deployment: { otpServers: { $splice: [[i, 1]] } } }
                        this.setState(update(this.state, stateUpdate))
                      }}>
                      Remove <Glyphicon glyph='remove' />
                    </Button>
                    <FormGroup>
                      <ControlLabel>{getMessage(messages, 'deployment.servers.name')}</ControlLabel>
                      <FormControl
                        type='text'
                        placeholder={getMessage(messages, 'deployment.servers.namePlaceholder')}
                        defaultValue={server.name}
                        onChange={(evt) => {
                          let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { name: evt.target.value } } } } }
                          this.setState(update(this.state, stateUpdate))
                        }} />
                    </FormGroup>
                    <FormGroup>
                      <ControlLabel>{getMessage(messages, 'deployment.servers.public')}</ControlLabel>
                      <FormControl
                        type='text'
                        placeholder='http://otp.example.com'
                        defaultValue={server.publicUrl}
                        onChange={(evt) => {
                          let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { publicUrl: evt.target.value } } } } }
                          this.setState(update(this.state, stateUpdate))
                        }} />
                    </FormGroup>
                    <FormGroup>
                      <ControlLabel>{getMessage(messages, 'deployment.servers.internal')}</ControlLabel>
                      <FormControl
                        type='text'
                        placeholder='http://127.0.0.1/otp,http://0.0.0.0/otp'
                        defaultValue={server.internalUrl && server.internalUrl.join(',')}
                        onChange={(evt) => {
                          let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { internalUrl: evt.target.value.split(',') } } } } }
                          this.setState(update(this.state, stateUpdate))
                        }} />
                    </FormGroup>
                    <FormGroup>
                      <ControlLabel>{getMessage(messages, 'deployment.servers.s3Bucket')}</ControlLabel>
                      <FormControl
                        type='text'
                        placeholder='s3_bucket_name'
                        defaultValue={server.s3Bucket}
                        onChange={(evt) => {
                          let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { s3Bucket: evt.target.value } } } } }
                          this.setState(update(this.state, stateUpdate))
                        }} />
                    </FormGroup>
                    <Checkbox
                      checked={server.admin}
                      onChange={(evt) => {
                        let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { admin: evt.target.checked } } } } }
                        this.setState(update(this.state, stateUpdate))
                      }}>
                      {getMessage(messages, 'deployment.servers.admin')}
                    </Checkbox>
                  </Form>
                </Panel>
              )
            })}

        </Panel>
        <Panel header={
{getMessage(messages, 'deployment.osm.title')}
}>
          <FormGroup
            onChange={(evt) => {
              let stateUpdate = { deployment: { useCustomOsmBounds: { $set: (evt.target.value === 'true') } } }
              this.setState(update(this.state, stateUpdate))
            }}
          >
            <Radio
              name='osm-extract'
              checked={typeof this.state.deployment.useCustomOsmBounds !== 'undefined' ? !this.state.deployment.useCustomOsmBounds : !project.useCustomOsmBounds}
              value={false}>
              {getMessage(messages, 'deployment.osm.gtfs')}
            </Radio>
            <Radio
              name='osm-extract'
              checked={typeof this.state.deployment.useCustomOsmBounds !== 'undefined' ? this.state.deployment.useCustomOsmBounds : project.useCustomOsmBounds}
              value>
              {getMessage(messages, 'deployment.osm.custom')}
            </Radio>
          </FormGroup>
          {project.useCustomOsmBounds || this.state.deployment.useCustomOsmBounds
            ? <FormControl
              type='text'
              defaultValue={project.osmNorth !== null ? `${project.osmWest},${project.osmSouth},${project.osmEast},${project.osmNorth}` : ''}
              placeholder='-88.45,33.22,-87.12,34.89'
              label={(<Glyphicon glyph='fullscreen' /> {getMessage(messages, 'deployment.osm.bounds')})}
              ref='osmBounds'
              onChange={(evt) => {
                const bBox = evt.target.value.split(',')
                if (bBox.length === 4) {
                  let stateUpdate = { deployment: { $merge: { osmWest: bBox[0], osmSouth: bBox[1], osmEast: bBox[2], osmNorth: bBox[3] } } }
                  this.setState(update(this.state, stateUpdate))
                }
              }} />
            : null
          }
        </Panel>
        <Row>
          <Col md={12}>
            {/* Save button */}
            <Button
              bsStyle='primary'
              type='submit'
              disabled={editDisabled || noEdits}
              onClick={(evt) => {
                evt.preventDefault()
                console.log(this.state)
                console.log(project)
                updateProjectSettings(project, this.state.deployment)
              }}>
              {getMessage(messages, 'save')}
            </Button>
          </Col>
        </Row>

    )
  }
}
<commit_msg>fix(DeploymentSettings): add back in deployment config labels<commit_after>import React, {Component} from 'react'
import { Row, Col, Button, Panel, Glyphicon, Form, Radio, Checkbox, FormGroup, ControlLabel, FormControl } from 'react-bootstrap'
import update from 'react-addons-update'
import { shallowEqual } from 'react-pure-render'

import { getMessage, getComponentMessages } from '../../common/util/config'

export default class DeploymentSettings extends Component {
  constructor (props) {
    super(props)
    this.state = {
      deployment: {
        buildConfig: {},
        routerConfig: {},
        otpServers: this.props.project && this.props.project.otpServers ? this.props.project.otpServers : []
      }
    }
  }
  componentWillReceiveProps (nextProps) {
    this.setState({
      deployment: {
        buildConfig: {},
        routerConfig: {},
        otpServers: nextProps.project && nextProps.project.otpServers ? nextProps.project.otpServers : []
      }
    })
  }
  shouldComponentUpdate (nextProps, nextState) {
    return !shallowEqual(nextProps, this.props) || !shallowEqual(nextState, this.state)
  }
  render () {
    console.log(this.state)
    const messages = getComponentMessages('ProjectSettings')
    const { project, editDisabled, updateProjectSettings } = this.props
    const noEdits = Object.keys(this.state.deployment.buildConfig).length === 0 &&
      Object.keys(this.state.deployment.routerConfig).length === 0 &&
      shallowEqual(this.state.deployment.otpServers, project.otpServers)
    return (

        <Panel header={
{getMessage(messages, 'deployment.buildConfig.title')}
}>
          <Row>
            <Col xs={6}>
              <FormGroup>
                <ControlLabel>{getMessage(messages, 'deployment.buildConfig.fetchElevationUS')}</ControlLabel>
                <FormControl
                  componentClass='select'
                  defaultValue={project.buildConfig && project.buildConfig.fetchElevationUS ? project.buildConfig.fetchElevationUS : ''}
                  ref='fetchElevationUS'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { buildConfig: { fetchElevationUS: { $set: (evt.target.value === 'true') } } } }
                    this.setState(update(this.state, stateUpdate))
                  }}>
                  <option value='false'>false</option>
                  <option value='true'>true</option>
                </FormControl>
              </FormGroup>
            </Col>
            <Col xs={6}>
              <FormGroup>
                <ControlLabel>{getMessage(messages, 'deployment.buildConfig.stationTransfers')}</ControlLabel>
                <FormControl
                  componentClass='select'
                  defaultValue={project.buildConfig && project.buildConfig.stationTransfers ? project.buildConfig.stationTransfers : ''}
                  ref='stationTransfers'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { buildConfig: { stationTransfers: { $set: (evt.target.value === 'true') } } } }
                    this.setState(update(this.state, stateUpdate))
                  }}>
                  <option value='false'>false</option>
                  <option value='true'>true</option>
                </FormControl>
              </FormGroup>
            </Col>
          </Row>
          <FormGroup>
            <ControlLabel>{getMessage(messages, 'deployment.buildConfig.subwayAccessTime')}</ControlLabel>
            <FormControl
              defaultValue={project.buildConfig && project.buildConfig.subwayAccessTime ? project.buildConfig.subwayAccessTime : ''}
              placeholder='2.5 (min)'
              ref='subwayAccessTime'
              onChange={(evt) => {
                let stateUpdate = { deployment: { buildConfig: { subwayAccessTime: { $set: +evt.target.value } } } }
                this.setState(update(this.state, stateUpdate))
              }} />
          </FormGroup>
          <FormGroup>
            <ControlLabel>{getMessage(messages, 'deployment.buildConfig.fares')}</ControlLabel>
            <FormControl
              defaultValue={project.buildConfig && project.buildConfig.fares ? project.buildConfig.fares : ''}
              placeholder='fares'
              ref='fares'
              onChange={(evt) => {
                let stateUpdate = { deployment: { buildConfig: { fares: { $set: evt.target.value } } } }
                this.setState(update(this.state, stateUpdate))
              }} />
          </FormGroup>
        </Panel>
        <Panel header={
Router Config
}>
          <Row>
            <Col xs={6}>
              <FormGroup>
                <ControlLabel>{getMessage(messages, 'deployment.routerConfig.numItineraries')}</ControlLabel>
                <FormControl
                  type='integer'
                  defaultValue={project.routerConfig && project.routerConfig.numItineraries ? project.routerConfig.numItineraries : ''}
                  placeholder='6'
                  ref='numItineraries'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { routerConfig: { numItineraries: { $set: +evt.target.value } } } }
                    this.setState(update(this.state, stateUpdate))
                  }} />
              </FormGroup>
            </Col>
            <Col xs={6}>
              <FormGroup>
                <ControlLabel>{getMessage(messages, 'deployment.routerConfig.walkSpeed')}</ControlLabel>
                <FormControl
                  type='number'
                  defaultValue={project.routerConfig && project.routerConfig.walkSpeed ? project.routerConfig.walkSpeed : ''}
                  placeholder='3.0'
                  ref='walkSpeed'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { routerConfig: { walkSpeed: { $set: +evt.target.value } } } }
                    this.setState(update(this.state, stateUpdate))
                  }} />
              </FormGroup>
            </Col>
          </Row>
          <Row>
            <Col xs={6}>
              <FormGroup>
                <ControlLabel>{getMessage(messages, 'deployment.routerConfig.stairsReluctance')}</ControlLabel>
                <FormControl
                  type='number'
                  defaultValue={project.routerConfig && project.routerConfig.stairsReluctance ? project.routerConfig.stairsReluctance : ''}
                  placeholder='2.0'
                  ref='stairsReluctance'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { routerConfig: { stairsReluctance: { $set: +evt.target.value } } } }
                    this.setState(update(this.state, stateUpdate))
                  }} />
              </FormGroup>
            </Col>
            <Col xs={6}>
              <FormGroup>
                <ControlLabel>{getMessage(messages, 'deployment.routerConfig.carDropoffTime')}</ControlLabel>
                <FormControl
                  type='number'
                  defaultValue={project.routerConfig && project.routerConfig.carDropoffTime ? project.routerConfig.carDropoffTime : ''}
                  placeholder='240 (sec)'
                  ref='carDropoffTime'
                  onChange={(evt) => {
                    let stateUpdate = { deployment: { routerConfig: { carDropoffTime: { $set: +evt.target.value } } } }
                    this.setState(update(this.state, stateUpdate))
                  }} />
              </FormGroup>
            </Col>
          </Row>
          <FormGroup>
            <ControlLabel>{getMessage(messages, 'deployment.routerConfig.brandingUrlRoot')}</ControlLabel>
            <FormControl
              type='text'
              defaultValue={project.routerConfig && project.routerConfig.brandingUrlRoot ? project.routerConfig.brandingUrlRoot : ''}
              placeholder='http://gtfs.example.com/branding'
              ref='brandingUrlRoot'
              onChange={(evt) => {
                let stateUpdate = { deployment: { routerConfig: { brandingUrlRoot: { $set: evt.target.value } } } }
                this.setState(update(this.state, stateUpdate))
              }} />
          </FormGroup>
        </Panel>
        <Panel header={

            <Button
              className='pull-right'
              bsStyle='success'
              bsSize='xsmall'
              onClick={() => {
                let stateUpdate = { deployment: { otpServers: { $push: [{name: '', publicUrl: '', internalUrl: [], admin: false}] } } }
                this.setState(update(this.state, stateUpdate))
              }}>
              <Glyphicon glyph='plus' /> {getMessage(messages, 'deployment.servers.new')}
            </Button>
            {getMessage(messages, 'deployment.servers.title')}

        }>

            {this.state.deployment.otpServers && this.state.deployment.otpServers.map((server, i) => {
              let title = (

                  {server.name}{'  '}
                  {server.publicUrl}

              )
              return (
                <Panel key={i}
                  header={server.name ? title : `[${getMessage(messages, 'deployment.servers.serverPlaceholder')}]`}
                  defaultExpanded={server.name === ''}
                  collapsible>
                  <Form>
                    <Button
                      bsSize='xsmall'
                      bsStyle='danger'
                      className='pull-right'
                      onClick={() => {
                        let stateUpdate = { deployment: { otpServers: { $splice: [[i, 1]] } } }
                        this.setState(update(this.state, stateUpdate))
                      }}>
                      Remove <Glyphicon glyph='remove' />
                    </Button>
                    <FormGroup>
                      <ControlLabel>{getMessage(messages, 'deployment.servers.name')}</ControlLabel>
                      <FormControl
                        type='text'
                        placeholder={getMessage(messages, 'deployment.servers.namePlaceholder')}
                        defaultValue={server.name}
                        onChange={(evt) => {
                          let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { name: evt.target.value } } } } }
                          this.setState(update(this.state, stateUpdate))
                        }} />
                    </FormGroup>
                    <FormGroup>
                      <ControlLabel>{getMessage(messages, 'deployment.servers.public')}</ControlLabel>
                      <FormControl
                        type='text'
                        placeholder='http://otp.example.com'
                        defaultValue={server.publicUrl}
                        onChange={(evt) => {
                          let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { publicUrl: evt.target.value } } } } }
                          this.setState(update(this.state, stateUpdate))
                        }} />
                    </FormGroup>
                    <FormGroup>
                      <ControlLabel>{getMessage(messages, 'deployment.servers.internal')}</ControlLabel>
                      <FormControl
                        type='text'
                        placeholder='http://127.0.0.1/otp,http://0.0.0.0/otp'
                        defaultValue={server.internalUrl && server.internalUrl.join(',')}
                        onChange={(evt) => {
                          let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { internalUrl: evt.target.value.split(',') } } } } }
                          this.setState(update(this.state, stateUpdate))
                        }} />
                    </FormGroup>
                    <FormGroup>
                      <ControlLabel>{getMessage(messages, 'deployment.servers.s3Bucket')}</ControlLabel>
                      <FormControl
                        type='text'
                        placeholder='s3_bucket_name'
                        defaultValue={server.s3Bucket}
                        onChange={(evt) => {
                          let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { s3Bucket: evt.target.value } } } } }
                          this.setState(update(this.state, stateUpdate))
                        }} />
                    </FormGroup>
                    <Checkbox
                      checked={server.admin}
                      onChange={(evt) => {
                        let stateUpdate = { deployment: { otpServers: { [i]: { $merge: { admin: evt.target.checked } } } } }
                        this.setState(update(this.state, stateUpdate))
                      }}>
                      {getMessage(messages, 'deployment.servers.admin')}
                    </Checkbox>
                  </Form>
                </Panel>
              )
            })}

        </Panel>
        <Panel header={
{getMessage(messages, 'deployment.osm.title')}
}>
          <FormGroup
            onChange={(evt) => {
              let stateUpdate = { deployment: { useCustomOsmBounds: { $set: (evt.target.value === 'true') } } }
              this.setState(update(this.state, stateUpdate))
            }}
          >
            <Radio
              name='osm-extract'
              checked={typeof this.state.deployment.useCustomOsmBounds !== 'undefined' ? !this.state.deployment.useCustomOsmBounds : !project.useCustomOsmBounds}
              value={false}>
              {getMessage(messages, 'deployment.osm.gtfs')}
            </Radio>
            <Radio
              name='osm-extract'
              checked={typeof this.state.deployment.useCustomOsmBounds !== 'undefined' ? this.state.deployment.useCustomOsmBounds : project.useCustomOsmBounds}
              value>
              {getMessage(messages, 'deployment.osm.custom')}
            </Radio>
          </FormGroup>
          {project.useCustomOsmBounds || this.state.deployment.useCustomOsmBounds
            ? <FormGroup>
              <ControlLabel>{(<Glyphicon glyph='fullscreen' /> {getMessage(messages, 'deployment.osm.bounds')})}</ControlLabel>
              <FormControl
                type='text'
                defaultValue={project.osmNorth !== null ? `${project.osmWest},${project.osmSouth},${project.osmEast},${project.osmNorth}` : ''}
                placeholder='-88.45,33.22,-87.12,34.89'
                ref='osmBounds'
                onChange={(evt) => {
                  const bBox = evt.target.value.split(',')
                  if (bBox.length === 4) {
                    let stateUpdate = { deployment: { $merge: { osmWest: bBox[0], osmSouth: bBox[1], osmEast: bBox[2], osmNorth: bBox[3] } } }
                    this.setState(update(this.state, stateUpdate))
                  }
                }} />
            </FormGroup>
            : null
          }
        </Panel>
        <Row>
          <Col md={12}>
            {/* Save button */}
            <Button
              bsStyle='primary'
              type='submit'
              disabled={editDisabled || noEdits}
              onClick={(evt) => {
                evt.preventDefault()
                console.log(this.state)
                console.log(project)
                updateProjectSettings(project, this.state.deployment)
              }}>
              {getMessage(messages, 'save')}
            </Button>
          </Col>
        </Row>

    )
  }
}
<|endoftext|>