<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @constructor
 * @implements {WebInspector.SourceMapping}
 * @param {!WebInspector.Workspace} workspace
 * @param {!WebInspector.DebuggerModel} debuggerModel
 */
WebInspector.FormatterScriptMapping = function(workspace, debuggerModel)
{
    this._workspace = workspace;
    this._debuggerModel = debuggerModel;

    this._init();

    this._projectId = "formatter:";
    this._projectDelegate = new WebInspector.FormatterProjectDelegate(workspace, this._projectId);
    this._debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
}

WebInspector.FormatterScriptMapping.prototype = {
    /**
     * @param {!WebInspector.RawLocation} rawLocation
     * @return {?WebInspector.UILocation}
     */
    rawLocationToUILocation: function(rawLocation)
    {
        var debuggerModelLocation = /** @type {!WebInspector.DebuggerModel.Location} */ (rawLocation);
        var script = debuggerModelLocation.script();
        var uiSourceCode = this._uiSourceCodes.get(script);
        if (!uiSourceCode)
            return null;

        var formatData = this._formatData.get(uiSourceCode);
        if (!formatData)
            return null;
        var mapping = formatData.mapping;
        var lineNumber = debuggerModelLocation.lineNumber;
        var columnNumber = debuggerModelLocation.columnNumber || 0;
        var formattedLocation = mapping.originalToFormatted(lineNumber, columnNumber);
        return uiSourceCode.uiLocation(formattedLocation[0], formattedLocation[1]);
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {number} lineNumber
     * @param {number} columnNumber
     * @return {?WebInspector.DebuggerModel.Location}
     */
    uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber)
    {
        var formatData = this._formatData.get(uiSourceCode);
        if (!formatData)
            return null;
        var originalLocation = formatData.mapping.formattedToOriginal(lineNumber, columnNumber)
        return this._debuggerModel.createRawLocation(formatData.scripts[0], originalLocation[0], originalLocation[1]);
    },

    /**
     * @return {boolean}
     */
    isIdentity: function()
    {
        return false;
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {number} lineNumber
     * @return {boolean}
     */
    uiLineHasMapping: function(uiSourceCode, lineNumber)
    {
        return true;
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @return {!Array.<!WebInspector.Script>}
     */
    _scriptsForUISourceCode: function(uiSourceCode)
    {
        /**
         * @param {!WebInspector.Script} script
         * @return {boolean}
         */
        function isInlineScript(script)
        {
            return script.isInlineScript();
        }

        if (uiSourceCode.contentType() === WebInspector.resourceTypes.Document)
            return this._debuggerModel.scriptsForSourceURL(uiSourceCode.url).filter(isInlineScript);
        if (uiSourceCode.contentType() === WebInspector.resourceTypes.Script) {
            var rawLocation =  /** @type {!WebInspector.DebuggerModel.Location} */ (uiSourceCode.uiLocationToRawLocation(this._debuggerModel.target(), 0, 0));
            return rawLocation ? [rawLocation.script()] : [];
        }
        return [];
    },

    _init: function()
    {
        /** @type {!Map.<!WebInspector.Script, !WebInspector.UISourceCode>} */
        this._uiSourceCodes = new Map();
        /** @type {!StringMap.<string>} */
        this._formattedPaths = new StringMap();
        /** @type {!Map.<!WebInspector.UISourceCode, !WebInspector.FormatterScriptMapping.FormatData>} */
        this._formatData = new Map();
    },

    _debuggerReset: function()
    {
        var formattedPaths = this._formattedPaths.values();
        for (var i = 0; i < formattedPaths.length; ++i)
            this._projectDelegate._removeFormatted(formattedPaths[i]);
        this._init();
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {function(?WebInspector.UISourceCode, !WebInspector.FormatterSourceMapping=)} callback
     */
    _performUISourceCodeScriptFormatting: function(uiSourceCode, callback)
    {
        var path = this._formattedPaths.get(uiSourceCode.project().id() + ":" + uiSourceCode.path());
        if (path) {
            var uiSourceCodePath = path;
            var formattedUISourceCode = this._workspace.uiSourceCode(this._projectId, uiSourceCodePath);
            var formatData = formattedUISourceCode ? this._formatData.get(formattedUISourceCode) : null;
            if (!formatData)
                callback(null);
            else
                callback(formattedUISourceCode, formatData.mapping);
            return;
        }

        uiSourceCode.requestContent(contentLoaded.bind(this));

        /**
         * @this {WebInspector.FormatterScriptMapping}
         * @param {?string} content
         */
        function contentLoaded(content)
        {
            var formatter = WebInspector.Formatter.createFormatter(uiSourceCode.contentType());
            formatter.formatContent(uiSourceCode.highlighterType(), content || "", innerCallback.bind(this));
        }

        /**
         * @this {WebInspector.FormatterScriptMapping}
         * @param {string} formattedContent
         * @param {!WebInspector.FormatterSourceMapping} formatterMapping
         */
        function innerCallback(formattedContent, formatterMapping)
        {
            var scripts = this._scriptsForUISourceCode(uiSourceCode);
            if (!scripts.length) {
                callback(null);
                return;
            }
            var name;
            if (uiSourceCode.contentType() === WebInspector.resourceTypes.Document)
                name = uiSourceCode.displayName();
            else
                name = uiSourceCode.name() || scripts[0].scriptId;
            path = this._projectDelegate._addFormatted(name, uiSourceCode.url, uiSourceCode.contentType(), formattedContent);
            var formattedUISourceCode = /** @type {!WebInspector.UISourceCode} */ (this._workspace.uiSourceCode(this._projectId, path));

            var formatData = new WebInspector.FormatterScriptMapping.FormatData(uiSourceCode.project().id(), uiSourceCode.path(), formatterMapping, scripts);
            this._formatData.put(formattedUISourceCode, formatData);
            this._formattedPaths.put(uiSourceCode.project().id() + ":" + uiSourceCode.path(), path);
            for (var i = 0; i < scripts.length; ++i) {
                this._uiSourceCodes.put(scripts[i], formattedUISourceCode);
                scripts[i].pushSourceMapping(this);
            }
            formattedUISourceCode.setSourceMappingForTarget(this._debuggerModel.target(), this);
            callback(formattedUISourceCode, formatterMapping);
        }
    },

    /**
     * @param {!WebInspector.UISourceCode} formattedUISourceCode
     * @return {?WebInspector.FormatterSourceMapping}
     */
    _discardFormattedUISourceCodeScript: function(formattedUISourceCode)
    {
        var formatData = this._formatData.get(formattedUISourceCode);
        if (!formatData)
            return null;

        this._formatData.remove(formattedUISourceCode);
        this._formattedPaths.remove(formatData.projectId + ":" + formatData.path);
        for (var i = 0; i < formatData.scripts.length; ++i) {
            this._uiSourceCodes.remove(formatData.scripts[i]);
            formatData.scripts[i].popSourceMapping();
        }
        this._projectDelegate._removeFormatted(formattedUISourceCode.path());
        return formatData.mapping;
    }
}

/**
 * @constructor
 * @param {string} projectId
 * @param {string} path
 * @param {!WebInspector.FormatterSourceMapping} mapping
 * @param {!Array.<!WebInspector.Script>} scripts
 */
WebInspector.FormatterScriptMapping.FormatData = function(projectId, path, mapping, scripts)
{
    this.projectId = projectId;
    this.path = path;
    this.mapping = mapping;
    this.scripts = scripts;
}

/**
 * @constructor
 * @param {!WebInspector.Workspace} workspace
 * @param {string} id
 * @extends {WebInspector.ContentProviderBasedProjectDelegate}
 */
WebInspector.FormatterProjectDelegate = function(workspace, id)
{
    WebInspector.ContentProviderBasedProjectDelegate.call(this, workspace, id, WebInspector.projectTypes.Formatter);
}

WebInspector.FormatterProjectDelegate.prototype = {
    /**
     * @return {string}
     */
    displayName: function()
    {
        return "formatter";
    },

    /**
     * @param {string} name
     * @param {string} sourceURL
     * @param {!WebInspector.ResourceType} contentType
     * @param {string} content
     * @return {string}
     */
    _addFormatted: function(name, sourceURL, contentType, content)
    {
        var contentProvider = new WebInspector.StaticContentProvider(contentType, content);
        return this.addContentProvider(sourceURL, name + ":formatted", "deobfuscated:" + sourceURL, contentProvider);
    },

    /**
     * @param {string} path
     */
    _removeFormatted: function(path)
    {
        this.removeFile(path);
    },

    __proto__: WebInspector.ContentProviderBasedProjectDelegate.prototype
}

/**
 * @constructor
 * @implements {WebInspector.SourcesView.EditorAction}
 */
WebInspector.ScriptFormatterEditorAction = function()
{
    this._scriptMapping = new WebInspector.FormatterScriptMapping(WebInspector.workspace, WebInspector.debuggerModel);
}

WebInspector.ScriptFormatterEditorAction.prototype = {
    /**
     * @param {!WebInspector.Event} event
     */
    _editorSelected: function(event)
    {
        var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data);
        this._updateButton(uiSourceCode);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _editorClosed: function(event)
    {
        var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data.uiSourceCode);
        var wasSelected = /** @type {boolean} */ (event.data.wasSelected);

        if (wasSelected)
            this._updateButton(null);
        this._discardFormattedUISourceCodeScript(uiSourceCode);
    },

    /**
     * @param {?WebInspector.UISourceCode} uiSourceCode
     */
    _updateButton: function(uiSourceCode)
    {
        this._button.element.classList.toggle("hidden", !this._isFormatableScript(uiSourceCode));
    },

    /**
     * @param {!WebInspector.SourcesView} sourcesView
     * @return {!Element}
     */
    button: function(sourcesView)
    {
        if (this._button)
            return this._button.element;

        this._sourcesView = sourcesView;
        this._sourcesView.addEventListener(WebInspector.SourcesView.Events.EditorSelected, this._editorSelected.bind(this));
        this._sourcesView.addEventListener(WebInspector.SourcesView.Events.EditorClosed, this._editorClosed.bind(this));

        this._button = new WebInspector.StatusBarButton(WebInspector.UIString("Pretty print"), "sources-toggle-pretty-print-status-bar-item");
        this._button.toggled = false;
        this._button.addEventListener("click", this._toggleFormatScriptSource, this);
        this._updateButton(null);

        return this._button.element;
    },

    /**
     * @param {?WebInspector.UISourceCode} uiSourceCode
     * @return {boolean}
     */
    _isFormatableScript: function(uiSourceCode)
    {
        if (!uiSourceCode)
            return false;
        var supportedProjectTypes = [WebInspector.projectTypes.Network, WebInspector.projectTypes.Debugger, WebInspector.projectTypes.ContentScripts];
        if (supportedProjectTypes.indexOf(uiSourceCode.project().type()) === -1)
            return false;
        var contentType = uiSourceCode.contentType();
        return contentType === WebInspector.resourceTypes.Script || contentType === WebInspector.resourceTypes.Document;
    },

    _toggleFormatScriptSource: function()
    {
        var uiSourceCode = this._sourcesView.currentUISourceCode();
        if (!this._isFormatableScript(uiSourceCode))
            return;
        this._formatUISourceCodeScript(uiSourceCode);

        WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, {
            action: WebInspector.UserMetrics.UserActionNames.TogglePrettyPrint,
            enabled: true,
            url: uiSourceCode.originURL()
        });
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     */
    _formatUISourceCodeScript: function(uiSourceCode)
    {
        this._scriptMapping._performUISourceCodeScriptFormatting(uiSourceCode, innerCallback.bind(this));

        /**
         * @this {WebInspector.ScriptFormatterEditorAction}
         * @param {?WebInspector.UISourceCode} formattedUISourceCode
         * @param {!WebInspector.FormatterSourceMapping=} mapping
         */
        function innerCallback(formattedUISourceCode, mapping)
        {
            if (!formattedUISourceCode)
                return;
            if (uiSourceCode !== this._sourcesView.currentUISourceCode())
                return;
            var sourceFrame = this._sourcesView.viewForFile(uiSourceCode);
            var start = [0, 0];
            if (sourceFrame) {
                var selection = sourceFrame.selection();
                start = mapping.originalToFormatted(selection.startLine, selection.startColumn);
            }
            this._sourcesView.showSourceLocation(formattedUISourceCode, start[0], start[1]);
            this._updateButton(formattedUISourceCode);
        }
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     */
    _discardFormattedUISourceCodeScript: function(uiSourceCode)
    {
        this._scriptMapping._discardFormattedUISourceCodeScript(uiSourceCode);
    }
}
<commit_msg>DevTools: Support multiple target in ScriptFormatterAction<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @constructor
 * @implements {WebInspector.SourceMapping}
 * @param {!WebInspector.Target} target
 * @param {!WebInspector.ScriptFormatterEditorAction} editorAction
 */
WebInspector.FormatterScriptMapping = function(target, editorAction)
{
    this._target = target;
    this._editorAction = editorAction;
}

WebInspector.FormatterScriptMapping.prototype = {
    /**
     * @param {!WebInspector.RawLocation} rawLocation
     * @return {?WebInspector.UILocation}
     */
    rawLocationToUILocation: function(rawLocation)
    {
        var debuggerModelLocation = /** @type {!WebInspector.DebuggerModel.Location} */ (rawLocation);
        var script = debuggerModelLocation.script();
        var uiSourceCode = this._editorAction._uiSourceCodes.get(script);
        if (!uiSourceCode)
            return null;

        var formatData = this._editorAction._formatData.get(uiSourceCode);
        if (!formatData)
            return null;
        var mapping = formatData.mapping;
        var lineNumber = debuggerModelLocation.lineNumber;
        var columnNumber = debuggerModelLocation.columnNumber || 0;
        var formattedLocation = mapping.originalToFormatted(lineNumber, columnNumber);
        return uiSourceCode.uiLocation(formattedLocation[0], formattedLocation[1]);
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {number} lineNumber
     * @param {number} columnNumber
     * @return {?WebInspector.DebuggerModel.Location}
     */
    uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber)
    {
        var formatData = this._editorAction._formatData.get(uiSourceCode);
        if (!formatData)
            return null;
        var originalLocation = formatData.mapping.formattedToOriginal(lineNumber, columnNumber);
        for (var i = 0; i < formatData.scripts.length; ++i) {
            if (formatData.scripts[i].target() === this._target)
                return this._target.debuggerModel.createRawLocation(formatData.scripts[i], originalLocation[0], originalLocation[1])
        }
        return null;
    },

    /**
     * @return {boolean}
     */
    isIdentity: function()
    {
        return false;
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {number} lineNumber
     * @return {boolean}
     */
    uiLineHasMapping: function(uiSourceCode, lineNumber)
    {
        return true;
    }

}

/**
 * @constructor
 * @param {string} projectId
 * @param {string} path
 * @param {!WebInspector.FormatterSourceMapping} mapping
 * @param {!Array.<!WebInspector.Script>} scripts
 */
WebInspector.FormatterScriptMapping.FormatData = function(projectId, path, mapping, scripts)
{
    this.projectId = projectId;
    this.path = path;
    this.mapping = mapping;
    this.scripts= scripts;
}

/**
 * @constructor
 * @param {!WebInspector.Workspace} workspace
 * @param {string} id
 * @extends {WebInspector.ContentProviderBasedProjectDelegate}
 */
WebInspector.FormatterProjectDelegate = function(workspace, id)
{
    WebInspector.ContentProviderBasedProjectDelegate.call(this, workspace, id, WebInspector.projectTypes.Formatter);
}

WebInspector.FormatterProjectDelegate.prototype = {
    /**
     * @return {string}
     */
    displayName: function()
    {
        return "formatter";
    },

    /**
     * @param {string} name
     * @param {string} sourceURL
     * @param {!WebInspector.ResourceType} contentType
     * @param {string} content
     * @return {string}
     */
    _addFormatted: function(name, sourceURL, contentType, content)
    {
        var contentProvider = new WebInspector.StaticContentProvider(contentType, content);
        return this.addContentProvider(sourceURL, name + ":formatted", "deobfuscated:" + sourceURL, contentProvider);
    },

    /**
     * @param {string} path
     */
    _removeFormatted: function(path)
    {
        this.removeFile(path);
    },

    __proto__: WebInspector.ContentProviderBasedProjectDelegate.prototype
}

/**
 * @constructor
 * @implements {WebInspector.SourcesView.EditorAction}
 * @implements {WebInspector.TargetManager.Observer}
 */
WebInspector.ScriptFormatterEditorAction = function()
{
    this._projectId = "formatter:";
    this._projectDelegate = new WebInspector.FormatterProjectDelegate(WebInspector.workspace, this._projectId);

    /** @type {!Map.<!WebInspector.Script, !WebInspector.UISourceCode>} */
    this._uiSourceCodes = new Map();
    /** @type {!StringMap.<string>} */
    this._formattedPaths = new StringMap();
    /** @type {!Map.<!WebInspector.UISourceCode, !WebInspector.FormatterScriptMapping.FormatData>} */
    this._formatData = new Map();

    /** @type {!Map.<!WebInspector.Target, !WebInspector.FormatterScriptMapping>} */
    this._scriptMappingByTarget = new Map();
    this._workspace = WebInspector.workspace;
    WebInspector.targetManager.observeTargets(this);
}

WebInspector.ScriptFormatterEditorAction.prototype = {
    /**
     * @param {!WebInspector.Target} target
     */
    targetAdded: function(target)
    {
        this._scriptMappingByTarget.put(target, new WebInspector.FormatterScriptMapping(target, this));
        target.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
    },

    /**
     * @param {!WebInspector.Target} target
     */
    targetRemoved: function(target)
    {
        this._scriptMappingByTarget.remove(target);
        this._cleanForTarget(target);
        target.debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _editorSelected: function(event)
    {
        var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data);
        this._updateButton(uiSourceCode);
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _editorClosed: function(event)
    {
        var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data.uiSourceCode);
        var wasSelected = /** @type {boolean} */ (event.data.wasSelected);

        if (wasSelected)
            this._updateButton(null);
        this._discardFormattedUISourceCodeScript(uiSourceCode);
    },

    /**
     * @param {?WebInspector.UISourceCode} uiSourceCode
     */
    _updateButton: function(uiSourceCode)
    {
        this._button.element.classList.toggle("hidden", !this._isFormatableScript(uiSourceCode));
    },

    /**
     * @param {!WebInspector.SourcesView} sourcesView
     * @return {!Element}
     */
    button: function(sourcesView)
    {
        if (this._button)
            return this._button.element;

        this._sourcesView = sourcesView;
        this._sourcesView.addEventListener(WebInspector.SourcesView.Events.EditorSelected, this._editorSelected.bind(this));
        this._sourcesView.addEventListener(WebInspector.SourcesView.Events.EditorClosed, this._editorClosed.bind(this));

        this._button = new WebInspector.StatusBarButton(WebInspector.UIString("Pretty print"), "sources-toggle-pretty-print-status-bar-item");
        this._button.toggled = false;
        this._button.addEventListener("click", this._toggleFormatScriptSource, this);
        this._updateButton(null);

        return this._button.element;
    },

    /**
     * @param {?WebInspector.UISourceCode} uiSourceCode
     * @return {boolean}
     */
    _isFormatableScript: function(uiSourceCode)
    {
        if (!uiSourceCode)
            return false;
        var supportedProjectTypes = [WebInspector.projectTypes.Network, WebInspector.projectTypes.Debugger, WebInspector.projectTypes.ContentScripts];
        if (supportedProjectTypes.indexOf(uiSourceCode.project().type()) === -1)
            return false;
        var contentType = uiSourceCode.contentType();
        return contentType === WebInspector.resourceTypes.Script || contentType === WebInspector.resourceTypes.Document;
    },

    _toggleFormatScriptSource: function()
    {
        var uiSourceCode = this._sourcesView.currentUISourceCode();
        if (!this._isFormatableScript(uiSourceCode))
            return;
        this._formatUISourceCodeScript(uiSourceCode);

        WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, {
            action: WebInspector.UserMetrics.UserActionNames.TogglePrettyPrint,
            enabled: true,
            url: uiSourceCode.originURL()
        });
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @param {!WebInspector.UISourceCode} formattedUISourceCode
     * @param {!WebInspector.FormatterSourceMapping} mapping
     * @private
     */
    _showIfNeeded: function(uiSourceCode, formattedUISourceCode, mapping)
    {
        if (uiSourceCode !== this._sourcesView.currentUISourceCode())
            return;
        var sourceFrame = this._sourcesView.viewForFile(uiSourceCode);
        var start = [0, 0];
        if (sourceFrame) {
            var selection = sourceFrame.selection();
            start = mapping.originalToFormatted(selection.startLine, selection.startColumn);
        }
        this._sourcesView.showSourceLocation(formattedUISourceCode, start[0], start[1]);
        this._updateButton(formattedUISourceCode);
    },

    /**
     * @param {!WebInspector.UISourceCode} formattedUISourceCode
     */
    _discardFormattedUISourceCodeScript: function(formattedUISourceCode)
    {
        var formatData = this._formatData.get(formattedUISourceCode);
        if (!formatData)
            return;

        this._formatData.remove(formattedUISourceCode);
        this._formattedPaths.remove(formatData.projectId + ":" + formatData.path);
        for (var i = 0; i < formatData.scripts.length; ++i) {
            this._uiSourceCodes.remove(formatData.scripts[i]);
            formatData.scripts[i].popSourceMapping();
        }
        this._projectDelegate._removeFormatted(formattedUISourceCode.path());
    },

    /**
     * @param {!WebInspector.Target} target
     */
    _cleanForTarget: function(target)
    {
        var uiSourceCodes = this._formatData.keys();
        for (var i = 0; i < uiSourceCodes.length; ++i) {
            uiSourceCodes[i].setSourceMappingForTarget(target, null);
            var formatData = this._formatData.get(uiSourceCodes[i]);
            var scripts = [];
            for (var j = 0; j < formatData.scripts.length; ++j) {
                if (formatData.scripts[j].target() === target)
                    this._uiSourceCodes.remove(formatData.scripts[j]);
                else
                    scripts.push(formatData.scripts[j]);
            }

            if (scripts.length)
                formatData.scripts = scripts;
            else {
                this._formattedPaths.remove(formatData.projectId + ":" + formatData.path);
                this._formatData.remove(uiSourceCodes[i]);
                this._projectDelegate._removeFormatted(uiSourceCodes[i].path());
            }
        }
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _debuggerReset: function(event)
    {
        var debuggerModel = /** @type {!WebInspector.DebuggerModel} */ (event.target);
        this._cleanForTarget(debuggerModel.target());
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     * @return {!Array.<!WebInspector.Script>}
     */
    _scriptsForUISourceCode: function(uiSourceCode)
    {
        /**
         * @param {!WebInspector.Script} script
         * @return {boolean}
         */
        function isInlineScript(script)
        {
            return script.isInlineScript();
        }

        if (uiSourceCode.contentType() === WebInspector.resourceTypes.Document) {
            var scripts = [];
            var targets = WebInspector.targetManager.targets();
            for (var i = 0; i < targets.length; ++i)
                scripts.pushAll(targets[i].debuggerModel.scriptsForSourceURL(uiSourceCode.url));
            return scripts.filter(isInlineScript);
        }
        if (uiSourceCode.contentType() === WebInspector.resourceTypes.Script) {
            var rawLocations = (uiSourceCode.uiLocationToRawLocations(0, 0));
            return rawLocations.map(function(rawLocation) { return rawLocation.script()});
        }
        return [];
    },

    /**
     * @param {!WebInspector.UISourceCode} uiSourceCode
     */
    _formatUISourceCodeScript: function(uiSourceCode)
    {
        var path = this._formattedPaths.get(uiSourceCode.project().id() + ":" + uiSourceCode.path());
        if (path) {
            var uiSourceCodePath = path;
            var formattedUISourceCode = this._workspace.uiSourceCode(this._projectId, uiSourceCodePath);
            var formatData = formattedUISourceCode ? this._formatData.get(formattedUISourceCode) : null;
            if (formatData)
                 this._showIfNeeded(uiSourceCode, /** @type {!WebInspector.UISourceCode} */ (formattedUISourceCode), formatData.mapping);
            return;
        }

        uiSourceCode.requestContent(contentLoaded.bind(this));

        /**
         * @this {WebInspector.ScriptFormatterEditorAction}
         * @param {?string} content
         */
        function contentLoaded(content)
        {
            var formatter = WebInspector.Formatter.createFormatter(uiSourceCode.contentType());
            formatter.formatContent(uiSourceCode.highlighterType(), content || "", innerCallback.bind(this));
        }

        /**
         * @this {WebInspector.ScriptFormatterEditorAction}
         * @param {string} formattedContent
         * @param {!WebInspector.FormatterSourceMapping} formatterMapping
         */
        function innerCallback(formattedContent, formatterMapping)
        {
            var scripts = this._scriptsForUISourceCode(uiSourceCode);
            if (!scripts.length)
                return;

            var name;
            if (uiSourceCode.contentType() === WebInspector.resourceTypes.Document)
                name = uiSourceCode.displayName();
            else
                name = uiSourceCode.name() || scripts[0].scriptId;
            path = this._projectDelegate._addFormatted(name, uiSourceCode.url, uiSourceCode.contentType(), formattedContent);
            var formattedUISourceCode = /** @type {!WebInspector.UISourceCode} */ (this._workspace.uiSourceCode(this._projectId, path));
            var formatData = new WebInspector.FormatterScriptMapping.FormatData(uiSourceCode.project().id(), uiSourceCode.path(), formatterMapping, scripts);
            this._formatData.put(formattedUISourceCode, formatData);
            this._formattedPaths.put(uiSourceCode.project().id() + ":" + uiSourceCode.path(), path);
            for (var i = 0; i < scripts.length; ++i) {
                this._uiSourceCodes.put(scripts[i], formattedUISourceCode);
                var scriptMapping = /** @type {!WebInspector.FormatterScriptMapping} */(this._scriptMappingByTarget.get(scripts[i].target()));
                scripts[i].pushSourceMapping(scriptMapping);
            }

            var targets = WebInspector.targetManager.targets();
            for (var i = 0; i < targets.length; ++i) {
                var scriptMapping = /** @type {!WebInspector.FormatterScriptMapping} */(this._scriptMappingByTarget.get(targets[i]));
                formattedUISourceCode.setSourceMappingForTarget(targets[i], scriptMapping);
            }
            this._showIfNeeded(uiSourceCode, formattedUISourceCode, formatterMapping);
        }
    }
}
<|endoftext|>


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

const PalindromeSwapper = (str) => {
  const inputArray = str.split('');
  const strLen = inputArray.length;
  const palTester = (arr) => {
    const len = arr.length;
    for (let i = 0; i < len; i += 1) {
      if (arr[i] !== arr[len - (1 + i)]) {
        return false;
      }
    }
    return true;
  };

  for (let i = 0; i < strLen - 1; i += 1) {
    const newArray = Array.from(inputArray);
    newArray.splice(i, 2, newArray[i + 1], newArray[i]);
    if (palTester(newArray)) {
      return newArray.join('');
    }

    // console.log('PalindromeSwapper');
  }
  return -1;
};

const in1 = 'anna'; // input
const expect1 = 'anna'; // output
const test1 = PalindromeSwapper(in1);
assert.strictEqual(test1, expect1, `should be ${expect1}`);
// console.log(test1);

const in2 = 'kayak'; // input
const expect2 = 'kayak'; // output
const test2 = PalindromeSwapper(in2);
assert.strictEqual(test2, expect2, `should be ${expect2}`);
// console.log(test2);
<commit_msg>wip-objective comment<commit_after>// objective:

// solution:
const assert = require('assert');

const PalindromeSwapper = (str) => {
  const inputArray = str.split('');
  const strLen = inputArray.length;
  const palTester = (arr) => {
    const len = arr.length;
    for (let i = 0; i < len; i += 1) {
      if (arr[i] !== arr[len - (1 + i)]) {
        return false;
      }
    }
    return true;
  };

  for (let i = 0; i < strLen - 1; i += 1) {
    const newArray = Array.from(inputArray);
    newArray.splice(i, 2, newArray[i + 1], newArray[i]);
    if (palTester(newArray)) {
      return newArray.join('');
    }

    // console.log('PalindromeSwapper');
  }
  return -1;
};

const in1 = 'anna'; // input
const expect1 = 'anna'; // output
const test1 = PalindromeSwapper(in1);
assert.strictEqual(test1, expect1, `should be ${expect1}`);
// console.log(test1);

const in2 = 'kayak'; // input
const expect2 = 'kayak'; // output
const test2 = PalindromeSwapper(in2);
assert.strictEqual(test2, expect2, `should be ${expect2}`);
// console.log(test2);
<|endoftext|>


<commit_before>({
	"findLabel": "찾을 문자열:",
	"replaceLabel": "바꿀 대상:",
	"findReplace": "토글 찾기/바꾸기",
	"matchCase": "대소문자 일치",
	"backwards": "뒤로",
	"replaceAll": "모두 바꾸기",
	"findButton": "찾기",
	"replaceButton": "바꾸기",
	"replaceDialogText": "${0} 개를 바꿨습니다."
})

<commit_msg>One more correction from IBM TV. Refs #10470<commit_after>({
	"findLabel": "찾을 문자열:",
	"replaceLabel": "바꿀 대상:",
	"findReplace": "토글 찾기/바꾸기",
	"matchCase": "대소문자 일치",
	"backwards": "뒤로",
	"replaceAll": "모두 바꾸기",
	"findButton": "찾기",
	"replaceButton": "바꾸기",
	"replaceDialogText": "${0}개를 바꿨습니다."
})

<|endoftext|>


<commit_before>let Card = require('./Card.js');
let React = require('react');
let update = require('react-addons-update');

let DropTarget = require('react-dnd').DropTarget;
let reactstrap = require('reactstrap');
let Modal = reactstrap.Modal;
let ModalHeader = reactstrap.ModalHeader;
let ModalBody = reactstrap.ModalBody;
let ModalFooter = reactstrap.ModalFooter;
import { connect, Provider } from "react-redux";
import { combineForms, Form, Control } from "react-redux-form";
import { compose, createStore } from "redux";
import Select from 'react-select';

const initialUser = {};
const store = createStore(
    combineForms({
        user: initialUser
    })
);

class TutorDropDown extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            categoryValue: null,
            options: [],
        };
        this.handleSelectChange = this.handleSelectChange.bind(this);
        this.setUp = this.setUp.bind(this);
        this.setUp();
    }

    setUp() {
        let shiftId = this.props.shiftId;
        console.log("shiftId");
        console.log(shiftId);
        let tutorData = this.props.tutorData;
        console.log(tutorData);
        for (let i=0; i<tutorData.length; i++) {
            let prefer = tutorData[i].tutorPreferences.shiftPreferences.PREFER;
            console.log("prefer");
            console.log(prefer);
            for (let j=0; j<prefer.length; j++) {
                if (prefer[j].id == shiftId) {
                    let name = tutorData[i].firstName + " " + tutorData[i].lastName + ", Preferred"
                    this.state.options.push({
                        value: tutorData[i].id,
                        label: name
                    });
                }
            }
            let willing = tutorData[i].tutorPreferences.shiftPreferences.WILLING;
            console.log("willing");
            console.log(willing);
            for (let j=0; j<willing.length; j++) {
                if (willing[j].id == shiftId) {
                    let name = tutorData[i].firstName + " " + tutorData[i].lastName + ", Willing";
                    this.state.options.push({
                        value: tutorData[i].id,
                        label: name
                    });
                }
            }
            console.log("this.state.options");
            console.log(this.state.options);
        }
    }

    handleSelectChange(value){
        console.log("in handleSelectChange");
        console.log("value");
        console.log(value);
        this.setState({ categoryValue: value });
        this.props.setTutorId(parseInt(value));
    };

    render() {
        let reactSelect = props => (
            <Select
                {...props}
            />
        );
        console.log("this.state.categoryValue");
        console.log(this.state.categoryValue);
        // console.log(this.state.categoryValue.length);

        return (

                        {this.props.title}
                        {this.props.isRequired ? (
                            *
                        ) : (
                            ''
                        )}

                <Control.custom
                    model={this.props.model}
                    mapProps={
                        {
                            onChange: (props) => props.onChange
                        }
                    }
                    id={this.props.model}
                    component={reactSelect}
                    simpleValue
                    multi
                    value={this.state.categoryValue}
                    options={this.state.options}
                    onChange={this.handleSelectChange}
                    joinValues
                    name={this.props.model}
                    required
                />

        );
    }
}

class CourseDropDown extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            categoryValue: null,
            options: [],
        };
        this.handleSelectChange = this.handleSelectChange.bind(this);
        this.setUp = this.setUp.bind(this);
        this.setUp();
    }

    setUp() {
        let shiftId = this.props.shiftId;
        console.log("shiftId");
        console.log(shiftId);
        let tutorData = this.props.tutorData;
        console.log(tutorData);
        for (let i=0; i<tutorData.length; i++) {
            let prefer = tutorData[i].tutorPreferences.shiftPreferences.PREFER;
            console.log("prefer");
            console.log(prefer);
            for (let j=0; j<prefer.length; j++) {
                if (prefer[j].id == shiftId) {
                    let name = tutorData[i].firstName + " " + tutorData[i].lastName + ", Preferred"
                    this.state.options.push({
                        value: tutorData[i].id,
                        label: name
                    });
                }
            }
            let willing = tutorData[i].tutorPreferences.shiftPreferences.WILLING;
            console.log("willing");
            console.log(willing);
            for (let j=0; j<willing.length; j++) {
                if (willing[j].id == shiftId) {
                    let name = tutorData[i].firstName + " " + tutorData[i].lastName + ", Willing";
                    this.state.options.push({
                        value: tutorData[i].id,
                        label: name
                    });
                }
            }
            console.log("this.state.options");
            console.log(this.state.options);
        }
    }

    handleSelectChange(value){
        console.log("in handleSelectChange");
        console.log("value");
        console.log(value);
        this.setState({ categoryValue: value });
        this.props.setTutorId(parseInt(value));
    };

    render() {
        let reactSelect = props => (
            <Select
                {...props}
            />
        );
        console.log("this.state.categoryValue");
        console.log(this.state.categoryValue);
        // console.log(this.state.categoryValue.length);

        return (

                        {this.props.title}
                        {this.props.isRequired ? (
                            *
                        ) : (
                            ''
                        )}

                <Control.custom
                    model={this.props.model}
                    mapProps={
                        {
                            onChange: (props) => props.onChange
                        }
                    }
                    id={this.props.model}
                    component={reactSelect}
                    simpleValue
                    multi
                    value={this.state.categoryValue}
                    options={this.state.options}
                    onChange={this.handleSelectChange}
                    joinValues
                    name={this.props.model}
                    required
                />

        );
    }
}

class Container extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            cards: props.list,
            tutorData: this.props.tutorData,
            setContainerDataList: this.props.setContainerDataList.bind(this),
            printc: this.props.printc.bind(this),
            day: this.props.day,
            modal : false,
            deleteMessageModal: false,
            tutorId: null,
        };
        this.setCard = this.setCard.bind(this);
        this.toggleGridModal = this.toggleGridModal.bind(this);
        this.toggleDeleteMessageModal = this.toggleDeleteMessageModal.bind(this);
        this.setTutorId = this.setTutorId.bind(this);
  	}

    toggleGridModal() {
        this.setState({
            modal : ! this.state.modal
        })
    }

    toggleDeleteMessageModal() {
        this.setState({
            deleteMessageModal: !this.state.deleteMessageModal
        })
    }

  	setCard(index, card) {
        console.log("in setCard");
        let cards = this.state.cards;
        cards[index] = card;
        console.log("cards");
        console.log(cards);
        this.props.setContainerDataList(this.props.id - 1, cards);
    }

    deleteCard(index) {
        console.log("in deleteCard");
        this.state.cards.splice(index, 1);
        console.log(this.state.cards);
        this.props.printc();
        this.props.setContainerDataList(this.props.id - 1, this.state.cards);
        this.props.printc();
        console.log("exiting deleteCard");
    }

    handleSubmit(e){
        console.log(e);
    };

    setTutorId(id) {
        this.setState({
            tutorId : id
        })
    }

	pushCard(card) {
        console.log("in pushCard");
		this.setState(update(this.state, {
			cards: {
				$push: [ card ]
			}
		}));

        this.props.printc();
        this.props.setContainerDataList(this.props.id - 1, this.state.cards);
        this.props.printc();
        console.log("exiting pushCard");
	}

	removeCard(index) {
        console.log("in removeCard");
		this.setState(update(this.state, {
			cards: {
				$splice: [
					[index, 1]
				]
			}
		}));

		console.log(this.state.cards);
        this.props.printc();
        this.props.setContainerDataList(this.props.id - 1, this.state.cards);
        this.props.printc();
        console.log("exiting removeCard");
	}

    moveCard(dragIndex, hoverIndex) {
        console.log("in moveCard");
        const { cards } = this.state;
        const dragCard = cards[dragIndex];

        this.setState(update(this.state, {
            cards: {
                $splice: [
                    [dragIndex, 1],
                    [hoverIndex, 0, dragCard]
                ]
            }
        }));

        this.props.printc();
        this.props.setContainerDataList(this.props.id - 1, this.state.cards);
        this.props.printc();
        console.log("exiting moveCard");
    }

    render(){
        const { cards } = this.state;
        const { canDrop, isOver, connectDropTarget } = this.props;
        const isActive = canDrop && isOver;
        const style = {
            width: "100%",
            height: "100%"
        };

        const backgroundColor = isActive ? 'lightgreen' : '#FFF';

        return connectDropTarget(

                {cards.map((card, i) => {
                    return (
                        <Card
                            key={card.id}
                            index={i}
                            listId={this.props.id}
                            card={card}
                            setCard={this.setCard}
                            day={this.state.day}
                            deleteCard={this.deleteCard.bind(this)}
                            removeCard={this.removeCard.bind(this)}
                            moveCard={this.moveCard.bind(this)}
                            tutorData={this.props.tutorData}
                            toggleDeleteMessageModal={this.toggleDeleteMessageModal}
                            />
                    );
                })}

                <button type="button" className="btn btn-success btn-block" onClick={this.toggleGridModal}
                        style={{background: "#c5050c", "textAlign": "center"}} > Add Assignment </button>

                <Modal isOpen={this.state.modal} toggle={this.toggleGridModal}>
                    <ModalHeader toggle={this.toggleGridModal} >

Shift {this.state.day}

                    </ModalHeader>
                    <ModalBody>
                        <Provider store={store}>

Add Tutor Assignment

Select a tutor available for this shift

                                    <Form model="user" onSubmit={this.handleSubmit}>
                                        <TutorDropDown model="user.category" tutorData={this.props.tutorData}
                                                       shiftId={this.props.shiftId} setTutorId={this.setTutorId}/>
                                    </Form>

                        </Provider>
                    </ModalBody>
                    <ModalFooter>
                        <button type="button" className="btn btn-success btn-block" onClick={this.savePopUp}
                                style={{"textAlign": "center"}} > Save </button>
                        <button type="button" className="btn btn-success btn-block" onClick={this.deleteCard.bind(this)}
                                style={{"textAlign": "center"}} > Cancel </button>
                    </ModalFooter>
                </Modal>

                <Modal isOpen={this.state.deleteMessageModal} toggle={this.toggleDeleteMessageModal}>
                    <ModalHeader toggle={this.toggleDeleteMessageModal} >

                            Shift Deletion

                    </ModalHeader>
                    <ModalBody>

 Shift Successfully Deleted

                    </ModalBody>
                </Modal>

        );
    }
}

const cardTarget = {
	drop(props, monitor, component ) {
		const { id } = props;
		const sourceObj = monitor.getItem();
		if ( id !== sourceObj.listId ) component.pushCard(sourceObj.card);
		return {
			listId: id
		};
	}
};

module.exports = DropTarget("CARD", cardTarget, (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
    canDrop: monitor.canDrop()
}))(Container);
<commit_msg>course dropdown in add assignment works<commit_after>let Card = require('./Card.js');
let React = require('react');
let update = require('react-addons-update');

let DropTarget = require('react-dnd').DropTarget;
let reactstrap = require('reactstrap');
let Modal = reactstrap.Modal;
let ModalHeader = reactstrap.ModalHeader;
let ModalBody = reactstrap.ModalBody;
let ModalFooter = reactstrap.ModalFooter;
import { connect, Provider } from "react-redux";
import { combineForms, Form, Control } from "react-redux-form";
import { compose, createStore } from "redux";
import Select from 'react-select';

const initialUser = {};
const store = createStore(
    combineForms({
        user: initialUser
    })
);

class TutorDropDown extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            categoryValue: null,
            options: [],
        };
        this.handleSelectChange = this.handleSelectChange.bind(this);
        this.setUp = this.setUp.bind(this);
        this.setUp();
    }

    setUp() {
        let shiftId = this.props.shiftId;
        console.log("shiftId");
        console.log(shiftId);
        let tutorData = this.props.tutorData;
        console.log(tutorData);
        for (let i=0; i<tutorData.length; i++) {
            let prefer = tutorData[i].tutorPreferences.shiftPreferences.PREFER;
            console.log("prefer");
            console.log(prefer);
            for (let j=0; j<prefer.length; j++) {
                if (prefer[j].id == shiftId) {
                    let name = tutorData[i].firstName + " " + tutorData[i].lastName + ", Preferred"
                    this.state.options.push({
                        value: tutorData[i].id,
                        label: name
                    });
                }
            }
            let willing = tutorData[i].tutorPreferences.shiftPreferences.WILLING;
            console.log("willing");
            console.log(willing);
            for (let j=0; j<willing.length; j++) {
                if (willing[j].id == shiftId) {
                    let name = tutorData[i].firstName + " " + tutorData[i].lastName + ", Willing";
                    this.state.options.push({
                        value: tutorData[i].id,
                        label: name
                    });
                }
            }
            console.log("this.state.options");
            console.log(this.state.options);
        }
    }

    handleSelectChange(value){
        console.log("in TutorDropDown.handleSelectChange");
        console.log("value");
        console.log(value);
        this.setState({ categoryValue: value });
        this.props.setTutorId(parseInt(value));
        console.log(parseInt(value));
    };

    render() {
        let reactSelect = props => (
            <Select
                {...props}
            />
        );
        console.log("this.state.categoryValue");
        console.log(this.state.categoryValue);
        // console.log(this.state.categoryValue.length);

        return (

                        {this.props.title}
                        {this.props.isRequired ? (
                            *
                        ) : (
                            ''
                        )}

                <Control.custom
                    model={this.props.model}
                    mapProps={
                        {
                            onChange: (props) => props.onChange
                        }
                    }
                    id={this.props.model}
                    component={reactSelect}
                    simpleValue
                    multi
                    value={this.state.categoryValue}
                    options={this.state.options}
                    onChange={this.handleSelectChange}
                    joinValues
                    name={this.props.model}
                    required
                />

        );
    }
}

class CourseDropDown extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            categoryValue: null,
            tutorId: this.props.tutorId,
            options: [],
        };
        this.handleSelectChange = this.handleSelectChange.bind(this);
    }

    handleSelectChange(value){
        console.log("in CourseDropDown.handleSelectChange");
        console.log("value");
        console.log(value);
        this.setState({ categoryValue: value });
        this.props.setTutorCourse(parseInt(value));
    };

    render() {
        console.log("in CourseDropDown render");
        let tutorId = this.props.tutorId;
        let tutorData = this.props.tutorData;
        console.log("tutorId, tutorData");
        console.log(tutorId);
        console.log(this.props.tutorId);
        console.log(tutorData);
        this.state.options = [];
        if (tutorId != null) {
            for (let i=0; i<tutorData.length; i++) {
                if (tutorId == tutorData[i].id) {
                    let prefer = tutorData[i].tutorPreferences.coursePreferences.PREFER;
                    for (let j=0; j<prefer.length; j++) {
                        let name = prefer[j].name + ", Preferred";
                        this.state.options.push({
                            value: prefer[j].id,
                            label: name
                        });
                    }
                    let willing = tutorData[i].tutorPreferences.coursePreferences.WILLING;
                    for (let j=0; j<willing.length; j++) {
                        let name = willing[j].name + ", Willing";
                        this.state.options.push({
                            value: willing[j].id,
                            label: name
                        });
                    }
                    break;
                }
            }
        }

        let reactSelect = props => (
            <Select
                {...props}
            />
        );
        console.log("this.state.categoryValue");
        console.log(this.state.categoryValue);
        // console.log(this.state.categoryValue.length);

        return (

                        {this.props.title}
                        {this.props.isRequired ? (
                            *
                        ) : (
                            ''
                        )}

                <Control.custom
                    model={this.props.model}
                    mapProps={
                        {
                            onChange: (props) => props.onChange
                        }
                    }
                    id={this.props.model}
                    component={reactSelect}
                    simpleValue
                    multi
                    value={this.state.categoryValue}
                    options={this.state.options}
                    onChange={this.handleSelectChange}
                    joinValues
                    name={this.props.model}
                    required
                />

        );
    }
}

class Container extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            cards: props.list,
            tutorData: this.props.tutorData,
            setContainerDataList: this.props.setContainerDataList.bind(this),
            printc: this.props.printc.bind(this),
            day: this.props.day,
            modal : false,
            deleteMessageModal: false,
            tutorId: null,
            tutorCourse: null,
        };
        this.setCard = this.setCard.bind(this);
        this.toggleGridModal = this.toggleGridModal.bind(this);
        this.toggleDeleteMessageModal = this.toggleDeleteMessageModal.bind(this);
        this.setTutorId = this.setTutorId.bind(this);
        this.setTutorCourse = this.setTutorCourse.bind(this);
  	}

    toggleGridModal() {
        this.setState({
            modal : ! this.state.modal
        })
    }

    toggleDeleteMessageModal() {
        this.setState({
            deleteMessageModal: !this.state.deleteMessageModal
        })
    }

  	setCard(index, card) {
        console.log("in setCard");
        let cards = this.state.cards;
        cards[index] = card;
        console.log("cards");
        console.log(cards);
        this.props.setContainerDataList(this.props.id - 1, cards);
    }

    deleteCard(index) {
        console.log("in deleteCard");
        this.state.cards.splice(index, 1);
        console.log(this.state.cards);
        this.props.printc();
        this.props.setContainerDataList(this.props.id - 1, this.state.cards);
        this.props.printc();
        console.log("exiting deleteCard");
    }

    handleSubmit(e){
        console.log(e);
    };

    setTutorId(id) {
        this.setState({
            tutorId : id
        })
    }

    setTutorCourse(courses) {
        this.setState({
            tutorCourse : courses
        })
    }

	pushCard(card) {
        console.log("in pushCard");
		this.setState(update(this.state, {
			cards: {
				$push: [ card ]
			}
		}));

        this.props.printc();
        this.props.setContainerDataList(this.props.id - 1, this.state.cards);
        this.props.printc();
        console.log("exiting pushCard");
	}

	removeCard(index) {
        console.log("in removeCard");
		this.setState(update(this.state, {
			cards: {
				$splice: [
					[index, 1]
				]
			}
		}));

		console.log(this.state.cards);
        this.props.printc();
        this.props.setContainerDataList(this.props.id - 1, this.state.cards);
        this.props.printc();
        console.log("exiting removeCard");
	}

    moveCard(dragIndex, hoverIndex) {
        console.log("in moveCard");
        const { cards } = this.state;
        const dragCard = cards[dragIndex];

        this.setState(update(this.state, {
            cards: {
                $splice: [
                    [dragIndex, 1],
                    [hoverIndex, 0, dragCard]
                ]
            }
        }));

        this.props.printc();
        this.props.setContainerDataList(this.props.id - 1, this.state.cards);
        this.props.printc();
        console.log("exiting moveCard");
    }

    render(){
        const { cards } = this.state;
        const { canDrop, isOver, connectDropTarget } = this.props;
        const isActive = canDrop && isOver;
        const style = {
            width: "100%",
            height: "100%"
        };

        const backgroundColor = isActive ? 'lightgreen' : '#FFF';

        return connectDropTarget(

                {cards.map((card, i) => {
                    return (
                        <Card
                            key={card.id}
                            index={i}
                            listId={this.props.id}
                            card={card}
                            setCard={this.setCard}
                            day={this.state.day}
                            deleteCard={this.deleteCard.bind(this)}
                            removeCard={this.removeCard.bind(this)}
                            moveCard={this.moveCard.bind(this)}
                            tutorData={this.props.tutorData}
                            toggleDeleteMessageModal={this.toggleDeleteMessageModal}
                            />
                    );
                })}

                <button type="button" className="btn btn-success btn-block" onClick={this.toggleGridModal}
                        style={{background: "#c5050c", "textAlign": "center"}} > Add Assignment </button>

                <Modal isOpen={this.state.modal} toggle={this.toggleGridModal}>
                    <ModalHeader toggle={this.toggleGridModal} >

Shift {this.state.day}

                    </ModalHeader>
                    <ModalBody>
                        <Provider store={store}>

Add Tutor Assignment

Select a tutor available for this shift

                                    <Form model="user" onSubmit={this.handleSubmit}>
                                        <TutorDropDown model="user.category" tutorData={this.props.tutorData}
                                                       shiftId={this.props.shiftId} setTutorId={this.setTutorId}/>
                                    </Form>

Select a course for the tutor

                                    <Form model="user" onSubmit={this.handleSubmit}>
                                        <CourseDropDown model="user.category" tutorData={this.props.tutorData}
                                                        tutorId={this.state.tutorId}
                                                        setTutorCourse={this.setTutorCourse}/>
                                    </Form>

                        </Provider>
                    </ModalBody>
                    <ModalFooter>
                        <button type="button" className="btn btn-success btn-block" onClick={this.savePopUp}
                                style={{"textAlign": "center"}} > Save </button>
                        <button type="button" className="btn btn-success btn-block" onClick={this.deleteCard.bind(this)}
                                style={{"textAlign": "center"}} > Cancel </button>
                    </ModalFooter>
                </Modal>

                <Modal isOpen={this.state.deleteMessageModal} toggle={this.toggleDeleteMessageModal}>
                    <ModalHeader toggle={this.toggleDeleteMessageModal} >

                            Shift Deletion

                    </ModalHeader>
                    <ModalBody>

 Shift Successfully Deleted

                    </ModalBody>
                </Modal>

        );
    }
}

const cardTarget = {
	drop(props, monitor, component ) {
		const { id } = props;
		const sourceObj = monitor.getItem();
		if ( id !== sourceObj.listId ) component.pushCard(sourceObj.card);
		return {
			listId: id
		};
	}
};

module.exports = DropTarget("CARD", cardTarget, (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
    canDrop: monitor.canDrop()
}))(Container);
<|endoftext|>


<commit_before>var AbstractMapper, Interrupt, Mirroring,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

AbstractMapper = require("./abstract-mapper");

Interrupt = require("../common/types").Interrupt;

Mirroring = require("../common/types").Mirroring;

function MMC3(cartridge) {
  return MMC3.__super__.constructor.call(this, "MMC3", cartridge);
}

extend(MMC3, AbstractMapper);

MMC3.dependencies = ["cpu", "ppu", "cpuMemory", "ppuMemory"];

MMC3.prototype.inject = function(cpu, ppu, cpuMemory, ppuMemory) {
  MMC3.__super__.inject.call(this, cpuMemory, ppuMemory);
  this.cpu = cpu;
  return this.ppu = ppu;
};

MMC3.prototype.init = function(cartridge) {
  MMC3.__super__.init.call(this, cartridge);
  this.hasPRGRAM = true;
  return this.alternateMode = false;
};

MMC3.prototype.reset = function() {
  this.resetMapping();
  return this.resetRegisters();
};

MMC3.prototype.resetMapping = function() {
  this.mapPRGROMBank32K(0, -1);
  this.mapPRGRAMBank8K(0, 0);
  if (!this.hasCHRRAM) {
    this.mapCHRROMBank8K(0, 0);
  }
  if (this.hasCHRRAM) {
    return this.mapCHRRAMBank8K(0, 0);
  }
};

MMC3.prototype.resetRegisters = function() {
  this.command = 0;
  this.irqCounter = 0;
  this.irqLatch = 0;
  this.irqReload = 0;
  this.irqEnabled = 0;
  return this.irqDelay = 0;
};

MMC3.prototype.write = function(address, value) {
  switch (address & 0xE001) {
    case 0x8000:
      return this.command = value;
    case 0x8001:
      return this.writeBankSelect(value);
    case 0xA000:
      return this.writeMirroring(value);
    case 0xA001:
      return this.writePRGRAMEnable(value);
    case 0xC000:
      return this.irqLatch = value;
    case 0xC001:
      return this.writeIRQReload();
    case 0xE000:
      return this.writeIRQEnable(false);
    case 0xE001:
      return this.writeIRQEnable(true);
  }
};

MMC3.prototype.writeBankSelect = function(value) {
  switch (this.command & 7) {
    case 0:
    case 1:
      if (!this.hasCHRRAM) {
        return this.switchDoubleCHRROMBanks(value);
      }
      break;
    case 2:
    case 3:
    case 4:
    case 5:
      if (!this.hasCHRRAM) {
        return this.switchSingleCHRROMBanks(value);
      }
      break;
    case 6:
      return this.switchPRGROMBanks0And2(value);
    case 7:
      return this.switchPRGROMBank1(value);
  }
};

MMC3.prototype.writeMirroring = function(value) {
  if (this.mirroring !== Mirroring.FOUR_SCREEN) {
    return this.switchMirroring(value);
  }
};

MMC3.prototype.writePRGRAMEnable = function(value) {};

MMC3.prototype.writeIRQReload = function() {
  if (this.alternateMode) {
    this.irqReload = true;
  }
  return this.irqCounter = 0;
};

MMC3.prototype.writeIRQEnable = function(enabled) {
  this.irqEnabled = enabled;
  if (!enabled) {
    return this.cpu.clearInterrupt(Interrupt.IRQ_EXT);
  }
};

MMC3.prototype.switchDoubleCHRROMBanks = function(target) {
  var source;
  source = (this.command & 0x80) >>> 6 | this.command & 0x01;
  return this.mapCHRROMBank2K(source, target >>> 1);
};

MMC3.prototype.switchSingleCHRROMBanks = function(target) {
  var source;
  source = (~this.command & 0x80) >>> 5 | (this.command - 2) & 0x03;
  return this.mapCHRROMBank1K(source, target);
};

MMC3.prototype.switchPRGROMBanks0And2 = function(target) {
  var sourceA, sourceB;
  sourceA = (this.command & 0x40) >>> 5;
  sourceB = (~this.command & 0x40) >>> 5;
  this.mapPRGROMBank8K(sourceA, target);
  return this.mapPRGROMBank8K(sourceB, -2);
};

MMC3.prototype.switchPRGROMBank1 = function(target) {
  return this.mapPRGROMBank8K(1, target);
};

MMC3.prototype.switchMirroring = function(value) {
  if (value & 1) {
    return this.setHorizontalMirroring();
  } else {
    return this.setVerticalMirroring();
  }
};

MMC3.prototype.tick = function() {
  if (this.ppu.addressBus & 0x1000) {
    if (!this.irqDelay) {
      this.updateIRQCounter();
    }
    return this.irqDelay = 7;
  } else if (this.irqDelay) {
    return this.irqDelay--;
  }
};

MMC3.prototype.updateIRQCounter = function() {
  var irqCounterOld;
  irqCounterOld = this.irqCounter;
  if (!this.irqCounter || this.irqReload) {
    this.irqCounter = this.irqLatch;
  } else {
    this.irqCounter--;
  }
  if (this.irqEnabled && !this.irqCounter && (!this.alternateMode || !irqCounterOld || this.irqReload)) {
    this.cpu.activateInterrupt(Interrupt.IRQ_EXT);
  }
  return this.irqReload = false;
};

module.exports = MMC3;
<commit_msg>Fixed uninitialized PRG RAM in MMC3.<commit_after>var AbstractMapper, Interrupt, Mirroring,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

AbstractMapper = require("./abstract-mapper");

Interrupt = require("../common/types").Interrupt;

Mirroring = require("../common/types").Mirroring;

function MMC3(cartridge) {
  return MMC3.__super__.constructor.call(this, "MMC3", cartridge);
}

extend(MMC3, AbstractMapper);

MMC3.dependencies = ["cpu", "ppu", "cpuMemory", "ppuMemory"];

MMC3.prototype.inject = function(cpu, ppu, cpuMemory, ppuMemory) {
  MMC3.__super__.inject.call(this, cpuMemory, ppuMemory);
  this.cpu = cpu;
  return this.ppu = ppu;
};

MMC3.prototype.init = function(cartridge) {
  MMC3.__super__.init.call(this, cartridge);
  this.hasPRGRAM = true;
  this.prgRAMSize = 0x2000;
  return this.alternateMode = false;
};

MMC3.prototype.reset = function() {
  this.resetMapping();
  return this.resetRegisters();
};

MMC3.prototype.resetMapping = function() {
  this.mapPRGROMBank32K(0, -1);
  this.mapPRGRAMBank8K(0, 0);
  if (!this.hasCHRRAM) {
    this.mapCHRROMBank8K(0, 0);
  }
  if (this.hasCHRRAM) {
    return this.mapCHRRAMBank8K(0, 0);
  }
};

MMC3.prototype.resetRegisters = function() {
  this.command = 0;
  this.irqCounter = 0;
  this.irqLatch = 0;
  this.irqReload = 0;
  this.irqEnabled = 0;
  return this.irqDelay = 0;
};

MMC3.prototype.write = function(address, value) {
  switch (address & 0xE001) {
    case 0x8000:
      return this.command = value;
    case 0x8001:
      return this.writeBankSelect(value);
    case 0xA000:
      return this.writeMirroring(value);
    case 0xA001:
      return this.writePRGRAMEnable(value);
    case 0xC000:
      return this.irqLatch = value;
    case 0xC001:
      return this.writeIRQReload();
    case 0xE000:
      return this.writeIRQEnable(false);
    case 0xE001:
      return this.writeIRQEnable(true);
  }
};

MMC3.prototype.writeBankSelect = function(value) {
  switch (this.command & 7) {
    case 0:
    case 1:
      if (!this.hasCHRRAM) {
        return this.switchDoubleCHRROMBanks(value);
      }
      break;
    case 2:
    case 3:
    case 4:
    case 5:
      if (!this.hasCHRRAM) {
        return this.switchSingleCHRROMBanks(value);
      }
      break;
    case 6:
      return this.switchPRGROMBanks0And2(value);
    case 7:
      return this.switchPRGROMBank1(value);
  }
};

MMC3.prototype.writeMirroring = function(value) {
  if (this.mirroring !== Mirroring.FOUR_SCREEN) {
    return this.switchMirroring(value);
  }
};

MMC3.prototype.writePRGRAMEnable = function(value) {};

MMC3.prototype.writeIRQReload = function() {
  if (this.alternateMode) {
    this.irqReload = true;
  }
  return this.irqCounter = 0;
};

MMC3.prototype.writeIRQEnable = function(enabled) {
  this.irqEnabled = enabled;
  if (!enabled) {
    return this.cpu.clearInterrupt(Interrupt.IRQ_EXT);
  }
};

MMC3.prototype.switchDoubleCHRROMBanks = function(target) {
  var source;
  source = (this.command & 0x80) >>> 6 | this.command & 0x01;
  return this.mapCHRROMBank2K(source, target >>> 1);
};

MMC3.prototype.switchSingleCHRROMBanks = function(target) {
  var source;
  source = (~this.command & 0x80) >>> 5 | (this.command - 2) & 0x03;
  return this.mapCHRROMBank1K(source, target);
};

MMC3.prototype.switchPRGROMBanks0And2 = function(target) {
  var sourceA, sourceB;
  sourceA = (this.command & 0x40) >>> 5;
  sourceB = (~this.command & 0x40) >>> 5;
  this.mapPRGROMBank8K(sourceA, target);
  return this.mapPRGROMBank8K(sourceB, -2);
};

MMC3.prototype.switchPRGROMBank1 = function(target) {
  return this.mapPRGROMBank8K(1, target);
};

MMC3.prototype.switchMirroring = function(value) {
  if (value & 1) {
    return this.setHorizontalMirroring();
  } else {
    return this.setVerticalMirroring();
  }
};

MMC3.prototype.tick = function() {
  if (this.ppu.addressBus & 0x1000) {
    if (!this.irqDelay) {
      this.updateIRQCounter();
    }
    return this.irqDelay = 7;
  } else if (this.irqDelay) {
    return this.irqDelay--;
  }
};

MMC3.prototype.updateIRQCounter = function() {
  var irqCounterOld;
  irqCounterOld = this.irqCounter;
  if (!this.irqCounter || this.irqReload) {
    this.irqCounter = this.irqLatch;
  } else {
    this.irqCounter--;
  }
  if (this.irqEnabled && !this.irqCounter && (!this.alternateMode || !irqCounterOld || this.irqReload)) {
    this.cpu.activateInterrupt(Interrupt.IRQ_EXT);
  }
  return this.irqReload = false;
};

module.exports = MMC3;
<|endoftext|>


<commit_before>'use strict';

/**
 *  @fileoverview Database helper functions
 *
 *  @author  Snugug
 *
 */
const helpers = {};

helpers.timestamp = () => {
  return new Date().toISOString().slice(0, 19).replace('T', ' ');
};

module.exports = helpers;
<commit_msg>:fire: Remove unused helpers<commit_after><|endoftext|>


<commit_before>odoo.define('website_sale.tour_shop_mail', function (require) {
'use strict';

var base = require('web_editor.base');
var rpc = require('web.rpc');
var tour = require('web_tour.tour');

tour.register('shop_mail', {
    test: true,
    url: '/',
    wait_for: base.ready(),
},
[
    {
        content: "Change the domain of the websites and go to shop",
        trigger: 'body',
        run: function () {
            // We change the domain of the website to test that the email that
            // will be sent uses the correct domain for its links.
            var def1 = rpc.query({
                'model': 'website',
                'method': 'write',
                'args': [[1], {
                    'domain': "my-test-domain.com",
                }],
            });
            // We need to change the domain of all the websites otherwise the
            // website selector will return the website 2 since the domain we
            // set on website 1 doesn't actually match our test server.
            var def2 = rpc.query({
                'model': 'website',
                'method': 'write',
                'args': [[2], {
                    'domain': "https://domain-not-used.fr",
                }],
            });
            $.when(def1, def2).then(function (data) {
                window.location.href = '/shop?search=Acoustic Bloc Screens';
            });
        },
    },
    {
        content: "select Acoustic Bloc Screens",
        trigger: '.oe_product_cart a:containsExact("Acoustic Bloc Screens")',
    },
    {
        content: "click add to cart",
        trigger: '#product_details #add_to_cart',
    },
    {
        content: "check product is in cart, get cart id, go to backend",
        trigger: 'td.td-product_name:contains("Acoustic Bloc Screens")',
        run: function () {
            rpc.query({
                'model': 'website',
                'method': 'sale_get_order',
                'args': [[$('html').data('website-id')]],
            }).then(function (data) {
                var orderId = parseInt(data.match(/sale\.order\((\d+),\)/)[1]);
                window.location.href = "/web#action=sale.action_orders&view_type=form&id=" + orderId;
            });
        },
    },
    {
        content: "click confirm",
        trigger: '.btn[name="action_confirm"]',
    },
    {
        content: "click send by email",
        trigger: '.btn[name="action_quotation_send"]',
        extra_trigger: '.o_statusbar_status .btn-primary:contains("Sales Order")',
    },
    {
        content: "click Send email",
        trigger: '.btn[name="action_send_mail"]',
    },
    {
        content: "wait mail to be sent, and go see it",
        trigger: '.o_thread_message_content:contains("Here is"):contains("the order")',
        run: function () {
            window.location.href = "/web#action=mail.action_view_mail_mail&view_type=list";
        },
    },
    {
        content: "click on the first email",
        trigger: '.o_data_cell:contains("YourCompany Order")',
    },
    {
        content: "check it's the correct email, and the URL is correct too",
        trigger: 'iframe p:contains("Here is"):contains("the order")',
        extra_trigger: 'iframe a[href^="http://my-test-domain.com"]',
    },
]);
});
<commit_msg>[FIX] website_sale: adapt test to demo data update<commit_after>odoo.define('website_sale.tour_shop_mail', function (require) {
'use strict';

var base = require('web_editor.base');
var rpc = require('web.rpc');
var tour = require('web_tour.tour');

tour.register('shop_mail', {
    test: true,
    url: '/',
    wait_for: base.ready(),
},
[
    {
        content: "Change the domain of the websites and go to shop",
        trigger: 'body',
        run: function () {
            // We change the domain of the website to test that the email that
            // will be sent uses the correct domain for its links.
            var def1 = rpc.query({
                'model': 'website',
                'method': 'write',
                'args': [[1], {
                    'domain': "my-test-domain.com",
                }],
            });
            // We need to change the domain of all the websites otherwise the
            // website selector will return the website 2 since the domain we
            // set on website 1 doesn't actually match our test server.
            var def2 = rpc.query({
                'model': 'website',
                'method': 'write',
                'args': [[2], {
                    'domain': "https://domain-not-used.fr",
                }],
            });
            $.when(def1, def2).then(function (data) {
                window.location.href = '/shop?search=Acoustic Bloc Screens';
            });
        },
    },
    {
        content: "select Acoustic Bloc Screens",
        trigger: '.oe_product_cart a:containsExact("Acoustic Bloc Screens")',
    },
    {
        content: "click add to cart",
        trigger: '#product_details #add_to_cart',
    },
    {
        content: "check product is in cart, get cart id, go to backend",
        trigger: 'td.td-product_name:contains("Acoustic Bloc Screens")',
        run: function () {
            rpc.query({
                'model': 'website',
                'method': 'sale_get_order',
                'args': [[$('html').data('website-id')]],
            }).then(function (data) {
                var orderId = parseInt(data.match(/sale\.order\((\d+),\)/)[1]);
                window.location.href = "/web#action=sale.action_orders&view_type=form&id=" + orderId;
            });
        },
    },
    {
        content: "click confirm",
        trigger: '.btn[name="action_confirm"]',
    },
    {
        content: "click send by email",
        trigger: '.btn[name="action_quotation_send"]',
        extra_trigger: '.o_statusbar_status .btn-primary:contains("Sales Order")',
    },
    {
        content: "click Send email",
        trigger: '.btn[name="action_send_mail"]',
    },
    {
        content: "wait mail to be sent, and go see it",
        trigger: '.o_thread_message_content:contains("Here is"):contains("the order")',
        run: function () {
            window.location.href = "/web#action=mail.action_view_mail_mail&view_type=list";
        },
    },
    {
        content: "click on the first email",
        trigger: '.o_data_cell:contains("(Ref SO")',
    },
    {
        content: "check it's the correct email, and the URL is correct too",
        trigger: 'iframe p:contains("Here is"):contains("the order")',
        extra_trigger: 'iframe a[href^="http://my-test-domain.com"]',
    },
]);
});
<|endoftext|>