UNPKG

devil

Version:

Debugger, profiler and runtime with embedded WebKit DevTools client.

33,631 lines 1.65 MB
var _importedScripts = {};
function loadResource(url) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, false);
    try {
        xhr.send(null);
    } catch (e) {
        console.error(url + " -> " + new Error().stack);
        throw e;
    }
    return xhr.responseText;
}
function normalizePath(path) {
    if (path.indexOf("..") === -1 && path.indexOf('.') === -1)
        return path;
    var normalizedSegments = [];
    var segments = path.split("/");
    for (var i = 0; i < segments.length; i++) {
        var segment = segments[i];
        if (segment === ".")
            continue; else if (segment === "..")
            normalizedSegments.pop(); else if (segment)
            normalizedSegments.push(segment);
    }
    var normalizedPath = normalizedSegments.join("/");
    if (normalizedPath[normalizedPath.length - 1] === "/")
        return normalizedPath;
    if (path[0] === "/" && normalizedPath)
        normalizedPath = "/" + normalizedPath;
    if ((path[path.length - 1] === "/") || (segments[segments.length - 1] === ".") || (segments[segments.length - 1] === ".."))
        normalizedPath = normalizedPath + "/";
    return normalizedPath;
}
function importScript(scriptName) {
    var sourceURL = self._importScriptPathPrefix + scriptName;
    var schemaIndex = sourceURL.indexOf("://") + 3;
    sourceURL = sourceURL.substring(0, schemaIndex) + normalizePath(sourceURL.substring(schemaIndex));
    if (_importedScripts[sourceURL])
        return;
    _importedScripts[sourceURL] = true;
    var scriptSource = loadResource(sourceURL);
    if (!scriptSource)
        throw"empty response arrived for script '" + sourceURL + "'";
    var oldPrefix = self._importScriptPathPrefix;
    self._importScriptPathPrefix += scriptName.substring(0, scriptName.lastIndexOf("/") + 1);
    try {
        self.eval(scriptSource + "\n//# sourceURL=" + sourceURL);
    } finally {
        self._importScriptPathPrefix = oldPrefix;
    }
}
(function () {
    var baseUrl = location.origin + location.pathname;
    self._importScriptPathPrefix = baseUrl.substring(0, baseUrl.lastIndexOf("/") + 1);
})();
var loadScript = importScript;
var Runtime = function (descriptors) {
    this._modules = [];
    this._modulesMap = {};
    this._extensions = [];
    this._cachedTypeClasses = {};
    this._descriptorsMap = {};
    for (var i = 0; i < descriptors.length; ++i)
        this._descriptorsMap[descriptors[i]["name"]] = descriptors[i];
}
Runtime.startWorker = function (moduleName) {
    return new Worker(moduleName + "/_module.js");
}
Runtime.prototype = {
    registerModules: function (configuration) {
        for (var i = 0; i < configuration.length; ++i)
            this._registerModule(configuration[i]);
    }, _registerModule: function (moduleName) {
        if (!this._descriptorsMap[moduleName]) {
            var content = loadResource(moduleName + "/module.json");
            if (!content)
                throw new Error("Module is not defined: " + moduleName + " " + new Error().stack);
            var module = (self.eval("(" + content + ")"));
            module["name"] = moduleName;
            this._descriptorsMap[moduleName] = module;
        }
        var module = new Runtime.Module(this, this._descriptorsMap[moduleName]);
        this._modules.push(module);
        this._modulesMap[moduleName] = module;
    }, loadModule: function (moduleName) {
        this._modulesMap[moduleName]._load();
    }, _checkExtensionApplicability: function (extension, predicate) {
        if (!predicate)
            return false;
        var contextTypes = (extension.descriptor().contextTypes);
        if (!contextTypes)
            return true;
        for (var i = 0; i < contextTypes.length; ++i) {
            var contextType = this._resolve(contextTypes[i]);
            var isMatching = !!contextType && predicate(contextType);
            if (isMatching)
                return true;
        }
        return false;
    }, isExtensionApplicableToContext: function (extension, context) {
        if (!context)
            return true;
        return this._checkExtensionApplicability(extension, isInstanceOf);
        function isInstanceOf(targetType) {
            return context instanceof targetType;
        }
    }, isExtensionApplicableToContextTypes: function (extension, currentContextTypes) {
        if (!extension.descriptor().contextTypes)
            return true;
        for (var i = 0; i < currentContextTypes.length; ++i)
            currentContextTypes[i]["__applicable"] = true;
        var result = this._checkExtensionApplicability(extension, currentContextTypes ? isContextTypeKnown : null);
        for (var i = 0; i < currentContextTypes.length; ++i)
            delete currentContextTypes[i]["__applicable"];
        return result;
        function isContextTypeKnown(targetType) {
            return !!targetType["__applicable"];
        }
    }, extensions: function (type, context) {
        function filter(extension) {
            if (extension._type !== type && extension._typeClass() !== type)
                return false;
            return !context || extension.isApplicable(context);
        }

        return this._extensions.filter(filter);
    }, extension: function (type, context) {
        return this.extensions(type, context)[0] || null;
    }, instances: function (type, context) {
        function instantiate(extension) {
            return extension.instance();
        }

        return this.extensions(type, context).filter(instantiate).map(instantiate);
    }, instance: function (type, context) {
        var extension = this.extension(type, context);
        return extension ? extension.instance() : null;
    }, orderComparator: function (type, nameProperty, orderProperty) {
        var extensions = this.extensions(type);
        var orderForName = {};
        for (var i = 0; i < extensions.length; ++i) {
            var descriptor = extensions[i].descriptor();
            orderForName[descriptor[nameProperty]] = descriptor[orderProperty];
        }
        function result(name1, name2) {
            if (name1 in orderForName && name2 in orderForName)
                return orderForName[name1] - orderForName[name2];
            if (name1 in orderForName)
                return -1;
            if (name2 in orderForName)
                return 1;
            return compare(name1, name2);
        }

        function compare(left, right) {
            if (left > right)
                return 1;
            if (left < right)
                return -1;
            return 0;
        }

        return result;
    }, _resolve: function (typeName) {
        if (!this._cachedTypeClasses[typeName]) {
            var path = typeName.split(".");
            var object = window;
            for (var i = 0; object && (i < path.length); ++i)
                object = object[path[i]];
            if (object)
                this._cachedTypeClasses[typeName] = (object);
        }
        return this._cachedTypeClasses[typeName];
    }
}
Runtime.ModuleDescriptor = function () {
    this.name;
    this.extensions;
    this.dependencies;
    this.scripts;
}
Runtime.ExtensionDescriptor = function () {
    this.type;
    this.className;
    this.contextTypes;
}
Runtime.Module = function (manager, descriptor) {
    this._manager = manager;
    this._descriptor = descriptor;
    this._name = descriptor.name;
    var extensions = (descriptor.extensions);
    for (var i = 0; extensions && i < extensions.length; ++i)
        this._manager._extensions.push(new Runtime.Extension(this, extensions[i]));
    this._loaded = false;
}
Runtime.Module.prototype = {
    name: function () {
        return this._name;
    }, _load: function () {
        if (this._loaded)
            return;
        if (this._isLoading) {
            var oldStackTraceLimit = Error.stackTraceLimit;
            Error.stackTraceLimit = 50;
            console.assert(false, "Module " + this._name + " is loaded from itself: " + new Error().stack);
            Error.stackTraceLimit = oldStackTraceLimit;
            return;
        }
        this._isLoading = true;
        var dependencies = this._descriptor.dependencies;
        for (var i = 0; dependencies && i < dependencies.length; ++i)
            this._manager.loadModule(dependencies[i]);
        if (this._descriptor.scripts)
            loadScript(this._name + "/_module.js");
        this._isLoading = false;
        this._loaded = true;
    }
}
Runtime.Extension = function (module, descriptor) {
    this._module = module;
    this._descriptor = descriptor;
    this._type = descriptor.type;
    this._hasTypeClass = this._type.charAt(0) === "@";
    this._className = descriptor.className || null;
}
Runtime.Extension.prototype = {
    descriptor: function () {
        return this._descriptor;
    }, module: function () {
        return this._module;
    }, _typeClass: function () {
        if (!this._hasTypeClass)
            return null;
        return this._module._manager._resolve(this._type.substring(1));
    }, isApplicable: function (context) {
        return this._module._manager.isExtensionApplicableToContext(this, context);
    }, instance: function () {
        if (!this._className)
            return null;
        if (!this._instance) {
            this._module._load();
            var constructorFunction = window.eval(this._className);
            if (!(constructorFunction instanceof Function))
                return null;
            this._instance = new constructorFunction();
        }
        return this._instance;
    }
}
var runtime;
Object.isEmpty = function (obj) {
    for (var i in obj)
        return false;
    return true;
}
Object.values = function (obj) {
    var result = Object.keys(obj);
    var length = result.length;
    for (var i = 0; i < length; ++i)
        result[i] = obj[result[i]];
    return result;
}
function mod(m, n) {
    return ((m % n) + n) % n;
}
String.prototype.findAll = function (string) {
    var matches = [];
    var i = this.indexOf(string);
    while (i !== -1) {
        matches.push(i);
        i = this.indexOf(string, i + string.length);
    }
    return matches;
}
String.prototype.lineEndings = function () {
    if (!this._lineEndings) {
        this._lineEndings = this.findAll("\n");
        this._lineEndings.push(this.length);
    }
    return this._lineEndings;
}
String.prototype.lineCount = function () {
    var lineEndings = this.lineEndings();
    return lineEndings.length;
}
String.prototype.lineAt = function (lineNumber) {
    var lineEndings = this.lineEndings();
    var lineStart = lineNumber > 0 ? lineEndings[lineNumber - 1] + 1 : 0;
    var lineEnd = lineEndings[lineNumber];
    var lineContent = this.substring(lineStart, lineEnd);
    if (lineContent.length > 0 && lineContent.charAt(lineContent.length - 1) === "\r")
        lineContent = lineContent.substring(0, lineContent.length - 1);
    return lineContent;
}
String.prototype.escapeCharacters = function (chars) {
    var foundChar = false;
    for (var i = 0; i < chars.length; ++i) {
        if (this.indexOf(chars.charAt(i)) !== -1) {
            foundChar = true;
            break;
        }
    }
    if (!foundChar)
        return String(this);
    var result = "";
    for (var i = 0; i < this.length; ++i) {
        if (chars.indexOf(this.charAt(i)) !== -1)
            result += "\\";
        result += this.charAt(i);
    }
    return result;
}
String.regexSpecialCharacters = function () {
    return "^[]{}()\\.^$*+?|-,";
}
String.prototype.escapeForRegExp = function () {
    return this.escapeCharacters(String.regexSpecialCharacters());
}
String.prototype.escapeHTML = function () {
    return this.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
String.prototype.collapseWhitespace = function () {
    return this.replace(/[\s\xA0]+/g, " ");
}
String.prototype.trimMiddle = function (maxLength) {
    if (this.length <= maxLength)
        return String(this);
    var leftHalf = maxLength >> 1;
    var rightHalf = maxLength - leftHalf - 1;
    return this.substr(0, leftHalf) + "\u2026" + this.substr(this.length - rightHalf, rightHalf);
}
String.prototype.trimEnd = function (maxLength) {
    if (this.length <= maxLength)
        return String(this);
    return this.substr(0, maxLength - 1) + "\u2026";
}
String.prototype.trimURL = function (baseURLDomain) {
    var result = this.replace(/^(https|http|file):\/\//i, "");
    if (baseURLDomain)
        result = result.replace(new RegExp("^" + baseURLDomain.escapeForRegExp(), "i"), "");
    return result;
}
String.prototype.toTitleCase = function () {
    return this.substring(0, 1).toUpperCase() + this.substring(1);
}
String.prototype.compareTo = function (other) {
    if (this > other)
        return 1;
    if (this < other)
        return -1;
    return 0;
}
function sanitizeHref(href) {
    return href && href.trim().toLowerCase().startsWith("javascript:") ? null : href;
}
String.prototype.removeURLFragment = function () {
    var fragmentIndex = this.indexOf("#");
    if (fragmentIndex == -1)
        fragmentIndex = this.length;
    return this.substring(0, fragmentIndex);
}
String.prototype.startsWith = function (substring) {
    return !this.lastIndexOf(substring, 0);
}
String.prototype.endsWith = function (substring) {
    return this.indexOf(substring, this.length - substring.length) !== -1;
}
String.prototype.hashCode = function () {
    var result = 0;
    for (var i = 0; i < this.length; ++i)
        result = (result * 3 + this.charCodeAt(i)) | 0;
    return result;
}
String.prototype.isDigitAt = function (index) {
    var c = this.charCodeAt(index);
    return 48 <= c && c <= 57;
}
String.naturalOrderComparator = function (a, b) {
    var chunk = /^\d+|^\D+/;
    var chunka, chunkb, anum, bnum;
    while (1) {
        if (a) {
            if (!b)
                return 1;
        } else {
            if (b)
                return -1; else
                return 0;
        }
        chunka = a.match(chunk)[0];
        chunkb = b.match(chunk)[0];
        anum = !isNaN(chunka);
        bnum = !isNaN(chunkb);
        if (anum && !bnum)
            return -1;
        if (bnum && !anum)
            return 1;
        if (anum && bnum) {
            var diff = chunka - chunkb;
            if (diff)
                return diff;
            if (chunka.length !== chunkb.length) {
                if (!+chunka && !+chunkb)
                    return chunka.length - chunkb.length; else
                    return chunkb.length - chunka.length;
            }
        } else if (chunka !== chunkb)
            return (chunka < chunkb) ? -1 : 1;
        a = a.substring(chunka.length);
        b = b.substring(chunkb.length);
    }
}
Number.constrain = function (num, min, max) {
    if (num < min)
        num = min; else if (num > max)
        num = max;
    return num;
}
Number.gcd = function (a, b) {
    if (b === 0)
        return a; else
        return Number.gcd(b, a % b);
}
Number.toFixedIfFloating = function (value) {
    if (!value || isNaN(value))
        return value;
    var number = Number(value);
    return number % 1 ? number.toFixed(3) : String(number);
}
Date.prototype.toISO8601Compact = function () {
    function leadZero(x) {
        return (x > 9 ? "" : "0") + x;
    }

    return this.getFullYear() +
    leadZero(this.getMonth() + 1) +
    leadZero(this.getDate()) + "T" +
    leadZero(this.getHours()) +
    leadZero(this.getMinutes()) +
    leadZero(this.getSeconds());
}
Date.prototype.toConsoleTime = function () {
    function leadZero2(x) {
        return (x > 9 ? "" : "0") + x;
    }

    function leadZero3(x) {
        return (Array(4 - x.toString().length)).join('0') + x;
    }

    return this.getFullYear() + "-" +
    leadZero2(this.getMonth() + 1) + "-" +
    leadZero2(this.getDate()) + " " +
    leadZero2(this.getHours()) + ":" +
    leadZero2(this.getMinutes()) + ":" +
    leadZero2(this.getSeconds()) + "." +
    leadZero3(this.getMilliseconds());
}
Object.defineProperty(Array.prototype, "remove", {
    value: function (value, firstOnly) {
        var index = this.indexOf(value);
        if (index === -1)
            return;
        if (firstOnly) {
            this.splice(index, 1);
            return;
        }
        for (var i = index + 1, n = this.length; i < n; ++i) {
            if (this[i] !== value)
                this[index++] = this[i];
        }
        this.length = index;
    }
});
Object.defineProperty(Array.prototype, "keySet", {
    value: function () {
        var keys = {};
        for (var i = 0; i < this.length; ++i)
            keys[this[i]] = true;
        return keys;
    }
});
Object.defineProperty(Array.prototype, "pushAll", {
    value: function (array) {
        Array.prototype.push.apply(this, array);
    }
});
Object.defineProperty(Array.prototype, "rotate", {
    value: function (index) {
        var result = [];
        for (var i = index; i < index + this.length; ++i)
            result.push(this[i % this.length]);
        return result;
    }
});
Object.defineProperty(Array.prototype, "sortNumbers", {
    value: function () {
        function numericComparator(a, b) {
            return a - b;
        }

        this.sort(numericComparator);
    }
});
Object.defineProperty(Uint32Array.prototype, "sort", {value: Array.prototype.sort});
(function () {
    var partition = {
        value: function (comparator, left, right, pivotIndex) {
            function swap(array, i1, i2) {
                var temp = array[i1];
                array[i1] = array[i2];
                array[i2] = temp;
            }

            var pivotValue = this[pivotIndex];
            swap(this, right, pivotIndex);
            var storeIndex = left;
            for (var i = left; i < right; ++i) {
                if (comparator(this[i], pivotValue) < 0) {
                    swap(this, storeIndex, i);
                    ++storeIndex;
                }
            }
            swap(this, right, storeIndex);
            return storeIndex;
        }
    };
    Object.defineProperty(Array.prototype, "partition", partition);
    Object.defineProperty(Uint32Array.prototype, "partition", partition);
    var sortRange = {
        value: function (comparator, leftBound, rightBound, sortWindowLeft, sortWindowRight) {
            function quickSortRange(array, comparator, left, right, sortWindowLeft, sortWindowRight) {
                if (right <= left)
                    return;
                var pivotIndex = Math.floor(Math.random() * (right - left)) + left;
                var pivotNewIndex = array.partition(comparator, left, right, pivotIndex);
                if (sortWindowLeft < pivotNewIndex)
                    quickSortRange(array, comparator, left, pivotNewIndex - 1, sortWindowLeft, sortWindowRight);
                if (pivotNewIndex < sortWindowRight)
                    quickSortRange(array, comparator, pivotNewIndex + 1, right, sortWindowLeft, sortWindowRight);
            }

            if (leftBound === 0 && rightBound === (this.length - 1) && sortWindowLeft === 0 && sortWindowRight >= rightBound)
                this.sort(comparator); else
                quickSortRange(this, comparator, leftBound, rightBound, sortWindowLeft, sortWindowRight);
            return this;
        }
    }
    Object.defineProperty(Array.prototype, "sortRange", sortRange);
    Object.defineProperty(Uint32Array.prototype, "sortRange", sortRange);
})();
Object.defineProperty(Array.prototype, "stableSort", {
    value: function (comparator) {
        function defaultComparator(a, b) {
            return a < b ? -1 : (a > b ? 1 : 0);
        }

        comparator = comparator || defaultComparator;
        var indices = new Array(this.length);
        for (var i = 0; i < this.length; ++i)
            indices[i] = i;
        var self = this;

        function indexComparator(a, b) {
            var result = comparator(self[a], self[b]);
            return result ? result : a - b;
        }

        indices.sort(indexComparator);
        for (var i = 0; i < this.length; ++i) {
            if (indices[i] < 0 || i === indices[i])
                continue;
            var cyclical = i;
            var saved = this[i];
            while (true) {
                var next = indices[cyclical];
                indices[cyclical] = -1;
                if (next === i) {
                    this[cyclical] = saved;
                    break;
                } else {
                    this[cyclical] = this[next];
                    cyclical = next;
                }
            }
        }
        return this;
    }
});
Object.defineProperty(Array.prototype, "qselect", {
    value: function (k, comparator) {
        if (k < 0 || k >= this.length)
            return;
        if (!comparator)
            comparator = function (a, b) {
                return a - b;
            }
        var low = 0;
        var high = this.length - 1;
        for (; ;) {
            var pivotPosition = this.partition(comparator, low, high, Math.floor((high + low) / 2));
            if (pivotPosition === k)
                return this[k]; else if (pivotPosition > k)
                high = pivotPosition - 1; else
                low = pivotPosition + 1;
        }
    }
});
Object.defineProperty(Array.prototype, "lowerBound", {
    value: function (object, comparator, left, right) {
        function defaultComparator(a, b) {
            return a < b ? -1 : (a > b ? 1 : 0);
        }

        comparator = comparator || defaultComparator;
        var l = left || 0;
        var r = right !== undefined ? right : this.length;
        while (l < r) {
            var m = (l + r) >> 1;
            if (comparator(object, this[m]) > 0)
                l = m + 1; else
                r = m;
        }
        return r;
    }
});
Object.defineProperty(Array.prototype, "upperBound", {
    value: function (object, comparator, left, right) {
        function defaultComparator(a, b) {
            return a < b ? -1 : (a > b ? 1 : 0);
        }

        comparator = comparator || defaultComparator;
        var l = left || 0;
        var r = right !== undefined ? right : this.length;
        while (l < r) {
            var m = (l + r) >> 1;
            if (comparator(object, this[m]) >= 0)
                l = m + 1; else
                r = m;
        }
        return r;
    }
});
Object.defineProperty(Uint32Array.prototype, "lowerBound", {value: Array.prototype.lowerBound});
Object.defineProperty(Uint32Array.prototype, "upperBound", {value: Array.prototype.upperBound});
Object.defineProperty(Float64Array.prototype, "lowerBound", {value: Array.prototype.lowerBound});
Object.defineProperty(Array.prototype, "binaryIndexOf", {
    value: function (value, comparator) {
        var index = this.lowerBound(value, comparator);
        return index < this.length && comparator(value, this[index]) === 0 ? index : -1;
    }
});
Object.defineProperty(Array.prototype, "select", {
    value: function (field) {
        var result = new Array(this.length);
        for (var i = 0; i < this.length; ++i)
            result[i] = this[i][field];
        return result;
    }
});
Object.defineProperty(Array.prototype, "peekLast", {
    value: function () {
        return this[this.length - 1];
    }
});
(function () {
    function mergeOrIntersect(array1, array2, comparator, mergeNotIntersect) {
        var result = [];
        var i = 0;
        var j = 0;
        while (i < array1.length && j < array2.length) {
            var compareValue = comparator(array1[i], array2[j]);
            if (mergeNotIntersect || !compareValue)
                result.push(compareValue <= 0 ? array1[i] : array2[j]);
            if (compareValue <= 0)
                i++;
            if (compareValue >= 0)
                j++;
        }
        if (mergeNotIntersect) {
            while (i < array1.length)
                result.push(array1[i++]);
            while (j < array2.length)
                result.push(array2[j++]);
        }
        return result;
    }

    Object.defineProperty(Array.prototype, "intersectOrdered", {
        value: function (array, comparator) {
            return mergeOrIntersect(this, array, comparator, false);
        }
    });
    Object.defineProperty(Array.prototype, "mergeOrdered", {
        value: function (array, comparator) {
            return mergeOrIntersect(this, array, comparator, true);
        }
    });
}());
function insertionIndexForObjectInListSortedByFunction(object, list, comparator, insertionIndexAfter) {
    if (insertionIndexAfter)
        return list.upperBound(object, comparator); else
        return list.lowerBound(object, comparator);
}
String.sprintf = function (format, var_arg) {
    return String.vsprintf(format, Array.prototype.slice.call(arguments, 1));
}
String.tokenizeFormatString = function (format, formatters) {
    var tokens = [];
    var substitutionIndex = 0;

    function addStringToken(str) {
        tokens.push({type: "string", value: str});
    }

    function addSpecifierToken(specifier, precision, substitutionIndex) {
        tokens.push({type: "specifier", specifier: specifier, precision: precision, substitutionIndex: substitutionIndex});
    }

    var index = 0;
    for (var precentIndex = format.indexOf("%", index); precentIndex !== -1; precentIndex = format.indexOf("%", index)) {
        addStringToken(format.substring(index, precentIndex));
        index = precentIndex + 1;
        if (format[index] === "%") {
            addStringToken("%");
            ++index;
            continue;
        }
        if (format.isDigitAt(index)) {
            var number = parseInt(format.substring(index), 10);
            while (format.isDigitAt(index))
                ++index;
            if (number > 0 && format[index] === "$") {
                substitutionIndex = (number - 1);
                ++index;
            }
        }
        var precision = -1;
        if (format[index] === ".") {
            ++index;
            precision = parseInt(format.substring(index), 10);
            if (isNaN(precision))
                precision = 0;
            while (format.isDigitAt(index))
                ++index;
        }
        if (!(format[index]in formatters)) {
            addStringToken(format.substring(precentIndex, index + 1));
            ++index;
            continue;
        }
        addSpecifierToken(format[index], precision, substitutionIndex);
        ++substitutionIndex;
        ++index;
    }
    addStringToken(format.substring(index));
    return tokens;
}
String.standardFormatters = {
    d: function (substitution) {
        return !isNaN(substitution) ? substitution : 0;
    }, f: function (substitution, token) {
        if (substitution && token.precision > -1)
            substitution = substitution.toFixed(token.precision);
        return !isNaN(substitution) ? substitution : (token.precision > -1 ? Number(0).toFixed(token.precision) : 0);
    }, s: function (substitution) {
        return substitution;
    }
}
String.vsprintf = function (format, substitutions) {
    return String.format(format, substitutions, String.standardFormatters, "", function (a, b) {
        return a + b;
    }).formattedResult;
}
String.format = function (format, substitutions, formatters, initialValue, append) {
    if (!format || !substitutions || !substitutions.length)
        return {formattedResult: append(initialValue, format), unusedSubstitutions: substitutions};
    function prettyFunctionName() {
        return "String.format(\"" + format + "\", \"" + substitutions.join("\", \"") + "\")";
    }

    function warn(msg) {
        console.warn(prettyFunctionName() + ": " + msg);
    }

    function error(msg) {
        console.error(prettyFunctionName() + ": " + msg);
    }

    var result = initialValue;
    var tokens = String.tokenizeFormatString(format, formatters);
    var usedSubstitutionIndexes = {};
    for (var i = 0; i < tokens.length; ++i) {
        var token = tokens[i];
        if (token.type === "string") {
            result = append(result, token.value);
            continue;
        }
        if (token.type !== "specifier") {
            error("Unknown token type \"" + token.type + "\" found.");
            continue;
        }
        if (token.substitutionIndex >= substitutions.length) {
            error("not enough substitution arguments. Had " + substitutions.length + " but needed " + (token.substitutionIndex + 1) + ", so substitution was skipped.");
            result = append(result, "%" + (token.precision > -1 ? token.precision : "") + token.specifier);
            continue;
        }
        usedSubstitutionIndexes[token.substitutionIndex] = true;
        if (!(token.specifier in formatters)) {
            warn("unsupported format character \u201C" + token.specifier + "\u201D. Treating as a string.");
            result = append(result, substitutions[token.substitutionIndex]);
            continue;
        }
        result = append(result, formatters[token.specifier](substitutions[token.substitutionIndex], token));
    }
    var unusedSubstitutions = [];
    for (var i = 0; i < substitutions.length; ++i) {
        if (i in usedSubstitutionIndexes)
            continue;
        unusedSubstitutions.push(substitutions[i]);
    }
    return {formattedResult: result, unusedSubstitutions: unusedSubstitutions};
}
function createSearchRegex(query, caseSensitive, isRegex) {
    var regexFlags = caseSensitive ? "g" : "gi";
    var regexObject;
    if (isRegex) {
        try {
            regexObject = new RegExp(query, regexFlags);
        } catch (e) {
        }
    }
    if (!regexObject)
        regexObject = createPlainTextSearchRegex(query, regexFlags);
    return regexObject;
}
function createPlainTextSearchRegex(query, flags) {
    var regexSpecialCharacters = String.regexSpecialCharacters();
    var regex = "";
    for (var i = 0; i < query.length; ++i) {
        var c = query.charAt(i);
        if (regexSpecialCharacters.indexOf(c) != -1)
            regex += "\\";
        regex += c;
    }
    return new RegExp(regex, flags || "");
}
function countRegexMatches(regex, content) {
    var text = content;
    var result = 0;
    var match;
    while (text && (match = regex.exec(text))) {
        if (match[0].length > 0)
            ++result;
        text = text.substring(match.index + 1);
    }
    return result;
}
function numberToStringWithSpacesPadding(value, symbolsCount) {
    var numberString = value.toString();
    var paddingLength = Math.max(0, symbolsCount - numberString.length);
    var paddingString = Array(paddingLength + 1).join("\u00a0");
    return paddingString + numberString;
}
var createObjectIdentifier = function () {
    return "_" + ++createObjectIdentifier._last;
}
createObjectIdentifier._last = 0;
var Set = function () {
    this._set = {};
    this._size = 0;
}
Set.fromArray = function (array) {
    var result = new Set();
    array.forEach(function (item) {
        result.add(item);
    });
    return result;
}
Set.prototype = {
    add: function (item) {
        var objectIdentifier = item.__identifier;
        if (!objectIdentifier) {
            objectIdentifier = createObjectIdentifier();
            item.__identifier = objectIdentifier;
        }
        if (!this._set[objectIdentifier])
            ++this._size;
        this._set[objectIdentifier] = item;
    }, remove: function (item) {
        if (this._set[item.__identifier]) {
            --this._size;
            delete this._set[item.__identifier];
            return true;
        }
        return false;
    }, values: function () {
        var result = new Array(this._size);
        var i = 0;
        for (var objectIdentifier in this._set)
            result[i++] = this._set[objectIdentifier];
        return result;
    }, contains: function (item) {
        return !!this._set[item.__identifier];
    }, size: function () {
        return this._size;
    }, clear: function () {
        this._set = {};
        this._size = 0;
    }
}
var Map = function () {
    this._map = {};
    this._size = 0;
}
Map.prototype = {
    put: function (key, value) {
        var objectIdentifier = key.__identifier;
        if (!objectIdentifier) {
            objectIdentifier = createObjectIdentifier();
            key.__identifier = objectIdentifier;
        }
        if (!this._map[objectIdentifier])
            ++this._size;
        this._map[objectIdentifier] = [key, value];
    }, remove: function (key) {
        var result = this._map[key.__identifier];
        if (!result)
            return undefined;
        --this._size;
        delete this._map[key.__identifier];
        return result[1];
    }, keys: function () {
        return this._list(0);
    }, values: function () {
        return this._list(1);
    }, _list: function (index) {
        var result = new Array(this._size);
        var i = 0;
        for (var objectIdentifier in this._map)
            result[i++] = this._map[objectIdentifier][index];
        return result;
    }, get: function (key) {
        var entry = this._map[key.__identifier];
        return entry ? entry[1] : undefined;
    }, contains: function (key) {
        var entry = this._map[key.__identifier];
        return !!entry;
    }, size: function () {
        return this._size;
    }, clear: function () {
        this._map = {};
        this._size = 0;
    }
}
var StringMap = function () {
    this._map = {};
    this._size = 0;
}
StringMap.prototype = {
    put: function (key, value) {
        if (key === "__proto__") {
            if (!this._hasProtoKey) {
                ++this._size;
                this._hasProtoKey = true;
            }
            this._protoValue = value;
            return;
        }
        if (!Object.prototype.hasOwnProperty.call(this._map, key))
            ++this._size;
        this._map[key] = value;
    }, remove: function (key) {
        var result;
        if (key === "__proto__") {
            if (!this._hasProtoKey)
                return undefined;
            --this._size;
            delete this._hasProtoKey;
            result = this._protoValue;
            delete this._protoValue;
            return result;
        }
        if (!Object.prototype.hasOwnProperty.call(this._map, key))
            return undefined;
        --this._size;
        result = this._map[key];
        delete this._map[key];
        return result;
    }, keys: function () {
        var result = Object.keys(this._map) || [];
        if (this._hasProtoKey)
            result.push("__proto__");
        return result;
    }, values: function () {
        var result = Object.values(this._map);
        if (this._hasProtoKey)
            result.push(this._protoValue);
        return result;
    }, get: function (key) {
        if (key === "__proto__")
            return this._protoValue;
        if (!Object.prototype.hasOwnProperty.call(this._map, key))
            return undefined;
        return this._map[key];
    }, contains: function (key) {
        var result;
        if (key === "__proto__")
            return this._hasProtoKey;
        return Object.prototype.hasOwnProperty.call(this._map, key);
    }, size: function () {
        return this._size;
    }, clear: function () {
        this._map = {};
        this._size = 0;
        delete this._hasProtoKey;
        delete this._protoValue;
    }
}
var StringMultimap = function () {
    StringMap.call(this);
}
StringMultimap.prototype = {
    put: function (key, value) {
        if (key === "__proto__") {
            if (!this._hasProtoKey) {
                ++this._size;
                this._hasProtoKey = true;
                this._protoValue = new Set();
            }
            this._protoValue.add(value);
            return;
        }
        if (!Object.prototype.hasOwnProperty.call(this._map, key)) {
            ++this._size;
            this._map[key] = new Set();
        }
        this._map[key].add(value);
    }, get: function (key) {
        var result = StringMap.prototype.get.call(this, key);
        if (!result)
            result = new Set();
        return result;
    }, remove: function (key, value) {
        var values = this.get(key);
        values.remove(value);
        if (!values.size())
            StringMap.prototype.remove.call(this, key)
    }, removeAll: function (key) {
        StringMap.prototype.remove.call(this, key);
    }, values: function () {
        var result = [];
        var keys = this.keys();
        for (var i = 0; i < keys.length; ++i)
            result.pushAll(this.get(keys[i]).values());
        return result;
    }, __proto__: StringMap.prototype
}
var StringSet = function () {
    this._map = new StringMap();
}
StringSet.fromArray = function (array) {
    var result = new StringSet();
    array.forEach(function (item) {
        result.add(item);
    });
    return result;
}
StringSet.prototype = {
    add: function (value) {
        this._map.put(value, true);
    }, remove: function (value) {
        return !!this._map.remove(value);
    }, values: function () {
        return this._map.keys();
    }, contains: function (value) {
        return this._map.contains(value);
    }, size: function () {
        return this._map.size();
    }, clear: function () {
        this._map.clear();
    }
}
function loadXHR(url, async, callback) {
    function onReadyStateChanged() {
        if (xhr.readyState !== XMLHttpRequest.DONE)
            return;
        if (xhr.status === 200) {
            callback(xhr.responseText);
            return;
        }
        callback(null);
    }

    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, async);
    if (async)
        xhr.onreadystatechange = onReadyStateChanged;
    xhr.send(null);
    if (!async) {
        if (xhr.status === 200 || xhr.status === 0)
            return xhr.responseText;
        return null;
    }
    return null;
}
function CallbackBarrier() {
    this._pendingIncomingCallbacksCount = 0;
}
CallbackBarrier.prototype = {
    createCallback: function (userCallback) {
        console.assert(!this._outgoingCallback, "CallbackBarrier.createCallback() is called after CallbackBarrier.callWhenDone()");
        ++this._pendingIncomingCallbacksCount;
        return this._incomingCallback.bind(this, userCallback);
    }, callWhenDone: function (callback) {
        console.assert(!this._outgoingCallback, "CallbackBarrier.callWhenDone() is called multiple times");
        this._outgoingCallback = callback;
        if (!this._pendingIncomingCallbacksCount)
            this._outgoingCallback();
    }, _incomingCallback: function (userCallback) {
        console.assert(this._pendingIncomingCallbacksCount > 0);
        if (userCallback) {
            var args = Array.prototype.slice.call(arguments, 1);
            userCallback.apply(null, args);
        }
        if (!--this._pendingIncomingCallbacksCount && this._outgoingCallback)
            this._outgoingCallback();
    }
}
function suppressUnused(value) {
}
function WeakReference(targetObject) {
    this._targetObject = targetObject;
}
WeakReference.prototype = {
    get: function () {
        return this._targetObject;
    }, clear: function () {
        this._targetObject = null;
    }
};
self.setImmediate = (function () {
    var callbacks = [];

    function run() {
        var cbList = callbacks.slice();
        callbacks.length = 0;
        cbList.forEach(function (callback) {
            callback();
        });
    };
    return function setImmediate(callback) {
        if (!callbacks.length)
            new Promise(function (resolve, reject) {
                resolve(null);
            }).then(run);
        callbacks.push(callback);
    };
})();
var allDescriptors = [{
    "extensions": [{"className": "WebInspector.AuditsPanel", "order": 6, "type": "@WebInspector.Panel", "name": "audits", "title": "Audits"}],
    "name": "audits",
    "scripts": []
}, {
    "extensions": [{"className": "WebInspector.ConsolePanel", "order": 20, "type": "@WebInspector.Panel", "name": "console", "title": "Console"}, {
        "className": "WebInspector.ConsolePanel.WrapperView",
        "order": "0",
        "type": "drawer-view",
        "name": "console",
        "title": "Console"
    }, {"className": "WebInspector.ConsolePanel.ConsoleRevealer", "contextTypes": ["WebInspector.Console"], "type": "@WebInspector.Revealer"}, {
        "className": "WebInspector.ConsoleView.ShowConsoleActionDelegate",
        "bindings": [{"shortcut": "Ctrl+`"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "console.show"
    }, {"section": "Console", "settingType": "checkbox", "type": "ui-setting", "settingName": "monitoringXHREnabled", "title": "Log XMLHttpRequests"}, {
        "section": "Console",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "preserveConsoleLog",
        "title": "Preserve log upon navigation"
    }, {"section": "Console", "settingType": "checkbox", "type": "ui-setting", "settingName": "consoleTimestampsEnabled", "title": "Show timestamps"}], "name": "console", "scripts": []
}, {
    "extensions": [{"name": "devices", "title": "Devices", "className": "WebInspector.DevicesView", "experiment": "devicesPanel", "type": "drawer-view", "order": "12"}],
    "name": "devices",
    "scripts": []
}, {
    "extensions": [{"className": "WebInspector.DocumentationView.ContextMenuProvider", "contextTypes": ["WebInspector.CodeMirrorTextEditor"], "type": "@WebInspector.ContextMenu.Provider"}],
    "name": "documentation",
    "scripts": []
}, {
    "extensions": [{"className": "WebInspector.ElementsPanel", "order": 0, "type": "@WebInspector.Panel", "name": "elements", "title": "Elements"}, {
        "className": "WebInspector.ElementsPanel.ContextMenuProvider",
        "contextTypes": ["WebInspector.RemoteObject", "WebInspector.DOMNode", "WebInspector.DeferredDOMNode"],
        "type": "@WebInspector.ContextMenu.Provider"
    }, {"className": "WebInspector.ElementsTreeOutline.Renderer", "contextTypes": ["WebInspector.DOMNode"], "type": "@WebInspector.Renderer"}, {
        "className": "WebInspector.ElementsPanel.DOMNodeRevealer",
        "contextTypes": ["WebInspector.DOMNode", "WebInspector.DeferredDOMNode"],
        "type": "@WebInspector.Revealer"
    }, {"className": "WebInspector.ElementsPanel.NodeRemoteObjectRevealer", "contextTypes": ["WebInspector.RemoteObject"], "type": "@WebInspector.Revealer"}, {
        "className": "WebInspector.ElementsPanel.NodeRemoteObjectInspector",
        "contextTypes": ["WebInspector.RemoteObject"],
        "type": "@WebInspector.NodeRemoteObjectInspector"
    }, {
        "title": "Color format:",
        "section": "Elements",
        "settingName": "colorFormat",
        "settingType": "select",
        "type": "ui-setting",
        "options": [["As authored", "original"], ["HEX: #DAC0DE", "hex", true], ["RGB: rgb(128, 255, 255)", "rgb", true], ["HSL: hsl(300, 80%, 90%)", "hsl", true]]
    }, {"section": "Elements", "settingType": "checkbox", "type": "ui-setting", "settingName": "showUserAgentStyles", "title": "Show user agent styles"}, {
        "section": "Elements",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "showUAShadowDOM",
        "title": "Show user agent shadow DOM"
    }, {"section": "Elements", "settingType": "checkbox", "type": "ui-setting", "settingName": "domWordWrap", "title": "Word wrap"}, {
        "section": "Elements",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "showMetricsRulers",
        "title": "Show rulers"
    }], "name": "elements", "scripts": []
}, {"dependencies": ["sources"], "extensions": [{"className": "WebInspector.ExtensionServer", "type": "@WebInspector.ExtensionServerAPI"}], "name": "extensions", "scripts": []}, {
    "dependencies": ["timeline"],
    "extensions": [{"className": "WebInspector.LayersPanel", "order": 7, "type": "@WebInspector.Panel", "name": "layers", "title": "Layers"}, {
        "className": "WebInspector.LayersPanel.LayerTreeRevealer",
        "contextTypes": ["WebInspector.DeferredLayerTree"],
        "type": "@WebInspector.Revealer"
    }],
    "name": "layers",
    "scripts": []
}, {
    "extensions": [{
        "className": "WebInspector.HandlerRegistry.ContextMenuProvider",
        "contextTypes": ["WebInspector.UISourceCode", "WebInspector.Resource", "WebInspector.NetworkRequest", "Node"],
        "type": "@WebInspector.ContextMenu.Provider"
    }, {
        "className": "WebInspector.Main.ReloadActionDelegate",
        "bindings": [{"platform": "windows,linux", "shortcut": "F5 Ctrl+R"}, {"platform": "mac", "shortcut": "Meta+R"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "main.reload"
    }, {
        "className": "WebInspector.Main.HardReloadActionDelegate",
        "bindings": [{"platform": "windows,linux", "shortcut": "Shift+F5 Ctrl+F5 Ctrl+Shift+F5 Shift+Ctrl+R"}, {"platform": "mac", "shortcut": "Shift+Meta+R"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "main.hard-reload"
    }, {
        "className": "WebInspector.InspectorView.DrawerToggleActionDelegate",
        "bindings": [{"shortcut": "Esc"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "main.toggle-drawer"
    }, {
        "className": "WebInspector.Main.DebugReloadActionDelegate",
        "bindings": [{"shortcut": "Alt+R"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "main.debug-reload"
    }, {
        "className": "WebInspector.InspectElementModeController.ToggleSearchActionDelegate",
        "bindings": [{"platform": "windows,linux", "shortcut": "Ctrl+Shift+C"}, {"platform": "mac", "shortcut": "Meta+Shift+C"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "main.toggle-element-search"
    }, {
        "className": "WebInspector.Main.ZoomInActionDelegate",
        "bindings": [{"platform": "windows,linux", "shortcut": "Ctrl+Plus Ctrl+Shift+Plus Ctrl+NumpadPlus Ctrl+Shift+NumpadPlus"}, {"platform": "mac", "shortcut": "Meta+Plus Meta+Shift+Plus Meta+NumpadPlus Meta+Shift+NumpadPlus"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "main.zoom-in"
    }, {
        "className": "WebInspector.Main.ZoomOutActionDelegate",
        "bindings": [{"platform": "windows,linux", "shortcut": "Ctrl+Minus Ctrl+Shift+Minus Ctrl+NumpadMinus Ctrl+Shift+NumpadMinus"}, {"platform": "mac", "shortcut": "Meta+Minus Meta+Shift+Minus Meta+NumpadMinus Meta+Shift+NumpadMinus"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "main.zoom-out"
    }, {
        "className": "WebInspector.Main.ZoomResetActionDelegate",
        "bindings": [{"platform": "windows,linux", "shortcut": "Ctrl+0 Ctrl+Numpad0"}, {"platform": "mac", "shortcut": "Meta+0 Meta+Numpad0"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "main.zoom-reset"
    }, {
        "className": "WebInspector.AdvancedApp.ToggleDeviceModeActionDelegate",
        "bindings": [{"platform": "windows,linux", "shortcut": "Shift+Ctrl+M"}, {"platform": "mac", "shortcut": "Shift+Meta+M"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "main.toggle-device-mode"
    }, {"className": "WebInspector.OverridesView", "order": "10", "type": "drawer-view", "name": "emulation", "title": "Emulation"}, {
        "className": "WebInspector.RenderingOptions.View",
        "order": "11",
        "type": "drawer-view",
        "name": "rendering",
        "title": "Rendering"
    }, {"className": "WebInspector.OverridesView.Revealer", "contextTypes": ["WebInspector.OverridesSupport"], "type": "@WebInspector.Revealer"}, {
        "className": "WebInspector.InspectElementModeController.ToggleButtonProvider",
        "actionId": "main.toggle-element-search",
        "type": "@WebInspector.StatusBarItem.Provider",
        "location": "toolbar-left",
        "order": 0
    }, {"className": "WebInspector.AdvancedApp.EmulationButtonProvider", "type": "@WebInspector.StatusBarItem.Provider", "order": 1, "location": "toolbar-left"}, {
        "className": "WebInspector.AdvancedApp.DeviceCounter",
        "type": "@WebInspector.StatusBarItem.Provider",
        "order": 0,
        "location": "toolbar-right"
    }, {"className": "WebInspector.Main.WarningErrorCounter", "type": "@WebInspector.StatusBarItem.Provider", "order": 1, "location": "toolbar-right"}, {
        "className": "WebInspector.InspectorView.ToggleDrawerButtonProvider",
        "type": "@WebInspector.StatusBarItem.Provider",
        "order": 2,
        "location": "toolbar-right"
    }, {"className": "WebInspector.DockController.ButtonProvider", "type": "@WebInspector.StatusBarItem.Provider", "order": 4, "location": "toolbar-right"}, {
        "className": "WebInspector.ScreencastApp.StatusBarButtonProvider",
        "type": "@WebInspector.StatusBarItem.Provider",
        "order": 5,
        "location": "toolbar-right"
    }, {"settingType": "checkbox", "type": "ui-setting", "settingName": "cacheDisabled", "title": "Disable cache (while DevTools is open)"}, {
        "section": "Appearance",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "splitVerticallyWhenDockedToRight",
        "title": "Split panels vertically when docked to right"
    }, {"className": "WebInspector.Main.ShortcutPanelSwitchSettingDelegate", "section": "Appearance", "type": "ui-setting", "settingType": "custom"}, {
        "section": "Appearance",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "disableOverridesWarning",
        "title": "Don't show emulation warnings"
    }, {"className": "WebInspector.HandlerRegistry.OpenAnchorLocationSettingDelegate", "section": "Extensions", "type": "ui-setting", "settingType": "custom"}], "name": "main"
}, {
    "dependencies": ["source_frame"],
    "extensions": [{"className": "WebInspector.NetworkPanel", "order": 1, "type": "@WebInspector.Panel", "name": "network", "title": "Network"}, {
        "className": "WebInspector.NetworkPanel.ContextMenuProvider",
        "contextTypes": ["WebInspector.NetworkRequest", "WebInspector.Resource", "WebInspector.UISourceCode"],
        "type": "@WebInspector.ContextMenu.Provider"
    }, {"className": "WebInspector.NetworkPanel.RequestRevealer", "contextTypes": ["WebInspector.NetworkRequest"], "type": "@WebInspector.Revealer"}],
    "name": "network",
    "scripts": []
}, {
    "extensions": [{"className": "WebInspector.ProfilesPanel", "order": 4, "type": "@WebInspector.Panel", "name": "profiles", "title": "Profiles"}, {
        "className": "WebInspector.ProfilesPanel.ContextMenuProvider",
        "contextTypes": ["WebInspector.RemoteObject"],
        "type": "@WebInspector.ContextMenu.Provider"
    }, {"section": "Profiler", "settingType": "checkbox", "type": "ui-setting", "settingName": "showAdvancedHeapSnapshotProperties", "title": "Show advanced heap snapshot properties"}, {
        "section": "Profiler",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "recordAllocationStacks",
        "title": "Record heap allocation stack traces"
    }, {"section": "Profiler", "settingType": "checkbox", "type": "ui-setting", "settingName": "highResolutionCpuProfiling", "title": "High resolution CPU profiling"}], "name": "profiler", "scripts": []
}, {
    "dependencies": ["source_frame"],
    "extensions": [{"className": "WebInspector.ResourcesPanel", "order": 5, "type": "@WebInspector.Panel", "name": "resources", "title": "Resources"}, {
        "className": "WebInspector.ResourcesPanel.ResourceRevealer",
        "contextTypes": ["WebInspector.Resource"],
        "type": "@WebInspector.Revealer"
    }],
    "name": "resources",
    "scripts": []
}, {
    "extensions": [{"className": "WebInspector.SettingsController.SettingsScreenActionDelegate", "bindings": [{"shortcut": "F1 Shift+?"}], "type": "@WebInspector.ActionDelegate", "actionId": "settings.show"}, {
        "title": "Settings",
        "elementClass": "settings-status-bar-item",
        "actionId": "settings.show",
        "type": "@WebInspector.StatusBarItem.Provider",
        "order": 3,
        "location": "toolbar-right"
    }, {"className": "WebInspector.SettingsScreen.SkipStackFramePatternSettingDelegate", "section": "Sources", "type": "ui-setting", "settingType": "custom"}], "name": "settings", "scripts": []
}, {
    "extensions": [{"className": "WebInspector.CodeMirrorUtils", "type": "@WebInspector.InplaceEditor"}, {
        "className": "WebInspector.CodeMirrorUtils.TokenizerFactory",
        "type": "@WebInspector.TokenizerFactory"
    }, {
        "title": "Default indentation:",
        "section": "Sources",
        "settingName": "textEditorIndent",
        "settingType": "select",
        "type": "ui-setting",
        "options": [["2 spaces", "  "], ["4 spaces", "    "], ["8 spaces", "        "], ["Tab character", "\t"]]
    }], "name": "source_frame", "scripts": []
}, {
    "dependencies": ["source_frame"],
    "extensions": [{"className": "WebInspector.SourcesPanel", "order": 2, "type": "@WebInspector.Panel", "name": "sources", "title": "Sources"}, {
        "className": "WebInspector.AdvancedSearchView",
        "order": "1",
        "type": "drawer-view",
        "name": "sources.search",
        "title": "Search"
    }, {
        "className": "WebInspector.SourcesPanel.ContextMenuProvider",
        "contextTypes": ["WebInspector.UISourceCode", "WebInspector.RemoteObject"],
        "type": "@WebInspector.ContextMenu.Provider"
    }, {
        "className": "WebInspector.SourcesPanel.TogglePauseActionDelegate",
        "contextTypes": ["WebInspector.SourcesPanel", "WebInspector.ShortcutRegistry.ForwardedShortcut"],
        "bindings": [{"platform": "windows,linux", "shortcut": "F8 Ctrl+\\"}, {"platform": "mac", "shortcut": "F8 Meta+\\"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "debugger.toggle-pause"
    }, {
        "className": "WebInspector.AdvancedSearchView.ToggleDrawerViewActionDelegate",
        "bindings": [{"platform": "mac", "shortcut": "Meta+Alt+F"}, {"platform": "windows,linux", "shortcut": "Ctrl+Shift+F"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "sources.search.toggle"
    }, {"className": "WebInspector.SourcesPanel.UILocationRevealer", "contextTypes": ["WebInspector.UILocation"], "type": "@WebInspector.Revealer"}, {
        "className": "WebInspector.SourcesPanel.UISourceCodeRevealer",
        "contextTypes": ["WebInspector.UISourceCode"],
        "type": "@WebInspector.Revealer"
    }, {"className": "WebInspector.InplaceFormatterEditorAction", "type": "@WebInspector.SourcesView.EditorAction"}, {
        "className": "WebInspector.ScriptFormatterEditorAction",
        "type": "@WebInspector.SourcesView.EditorAction"
    }, {"className": "WebInspector.SourcesNavigatorView", "order": 1, "type": "navigator-view", "name": "sources", "title": "Sources"}, {
        "className": "WebInspector.ContentScriptsNavigatorView",
        "order": 2,
        "type": "navigator-view",
        "name": "contentScripts",
        "title": "Content scripts"
    }, {"className": "WebInspector.SnippetsNavigatorView", "order": 3, "type": "navigator-view", "name": "snippets", "title": "Snippets"}, {
        "className": "WebInspector.SourcesPanel.ShowGoToSourceDialogActionDelegate",
        "bindings": [{"platform": "mac", "shortcut": "Meta+O Meta+P"}, {"platform": "windows,linux", "shortcut": "Ctrl+O Ctrl+P"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "sources.go-to-source"
    }, {
        "className": "WebInspector.SourcesView.SwitchFileActionDelegate",
        "contextTypes": ["WebInspector.SourcesView"],
        "bindings": [{"shortcut": "Alt+O"}],
        "type": "@WebInspector.ActionDelegate",
        "actionId": "sources.switch-file"
    }, {"className": "WebInspector.SourcesPanel.DisableJavaScriptSettingDelegate", "type": "ui-setting", "settingName": "javaScriptDisabled", "settingType": "custom"}, {
        "section": "Sources",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "searchInContentScripts",
        "title": "Search in content scripts"
    }, {"section": "Sources", "settingType": "checkbox", "type": "ui-setting", "settingName": "jsSourceMapsEnabled", "title": "Enable JavaScript source maps"}, {
        "section": "Sources",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "textEditorAutoDetectIndent",
        "title": "Detect indentation"
    }, {"section": "Sources", "settingType": "checkbox", "type": "ui-setting", "settingName": "textEditorAutocompletion", "title": "Autocompletion"}, {
        "section": "Sources",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "textEditorBracketMatching",
        "title": "Bracket matching"
    }, {"section": "Sources", "settingType": "checkbox", "type": "ui-setting", "settingName": "showWhitespacesInEditor", "title": "Show whitespace characters"}, {
        "section": "Sources",
        "settingType": "checkbox",
        "type": "ui-setting",
        "settingName": "cssSourceMapsEnabled",
        "title": "Enable CSS source maps"
    }, {"parentSettingName": "cssSourceMapsEnabled", "settingType": "checkbox", "type": "ui-setting", "settingName": "cssReloadEnabled", "title": "Auto-reload generated CSS"}],
    "name": "sources",
    "scripts": []
}, {"extensions": [{"className": "WebInspector.TimelinePanel", "order": 3, "type": "@WebInspector.Panel", "name": "timeline", "title": "Timeline"}], "name": "timeline", "scripts": []}];
self.WebInspector = {_queryParamsObject: {}}
WebInspector.queryParam = function (name) {
    return WebInspector._queryParamsObject.hasOwnProperty(name) ? WebInspector._queryParamsObject[name] : null;
}
{
    (function parseQueryParameters() {
        var queryParams = location.search;
        if (!queryParams)
            return;
        var params = queryParams.substring(1).split("&");
        for (var i = 0; i < params.length; ++i) {
            var pair = params[i].split("=");
            WebInspector._queryParamsObject[pair[0]] = pair[1];
        }
        var settingsParam = WebInspector.queryParam("settings");
        if (settingsParam) {
            try {
                var settings = JSON.parse(window.decodeURI(settingsParam));
                for (var key in settings)
                    window.localStorage[key] = settings[key];
            } catch (e) {
            }
        }
    })();
}
WebInspector.Object = function () {
}
WebInspector.Object.prototype = {
    addEventListener: function (eventType, listener, thisObject) {
        if (!listener)
            console.assert(false);
        if (!this._listeners)
            this._listeners = {};
        if (!this._listeners[eventType])
            this._listeners[eventType] = [];
        this._listeners[eventType].push({thisObject: thisObject, listener: listener});
    }, removeEventListener: function (eventType, listener, thisObject) {
        console.assert(listener);
        if (!this._listeners || !this._listeners[eventType])
            return;
        var listeners = this._listeners[eventType];
        for (var i = 0; i < listeners.length; ++i) {
            if (listeners[i].listener === listener && listeners[i].thisObject === thisObject)
                listeners.splice(i--, 1);
        }
        if (!listeners.length)
            delete this._listeners[eventType];
    }, removeAllListeners: function () {
        delete this._listeners;
    }, hasEventListeners: function (eventType) {
        if (!this._listeners || !this._listeners[eventType])
            return false;
        return true;
    }, dispatchEventToListeners: function (eventType, eventData) {
        if (!this._listeners || !this._listeners[eventType])
            return false;
        var event = new WebInspector.Event(this, eventType, eventData);
        var listeners = this._listeners[eventType].slice(0);
        for (var i = 0; i < listeners.length; ++i) {
            listeners[i].listener.call(listeners[i].thisObject, event);
            if (event._stoppedPropagation)
                break;
        }
        return event.defaultPrevented;
    }
}
WebInspector.Event = function (target, type, data) {
    this.target = target;
    this.type = type;
    this.data = data;
    this.defaultPrevented = false;
    this._stoppedPropagation = false;
}
WebInspector.Event.prototype = {
    stopPropagation: function () {
        this._stoppedPropagation = true;
    }, preventDefault: function () {
        this.defaultPrevented = true;
    }, consume: function (preventDefault) {
        this.stopPropagation();
        if (preventDefault)
            this.preventDefault();
    }
}
WebInspector.EventTarget = function () {
}
WebInspector.EventTarget.prototype = {
    addEventListener: function (eventType, listener, thisObject) {
    }, removeEventListener: function (eventType, listener, thisObject) {
    }, removeAllListeners: function () {
    }, hasEventListeners: function (eventType) {
    }, dispatchEventToListeners: function (eventType, eventData) {
    },
}
WebInspector.NotificationService = function () {
}
WebInspector.NotificationService.prototype = {__proto__: WebInspector.Object.prototype}
WebInspector.NotificationService.Events = {InspectorUILoadedForTests: "InspectorUILoadedForTests", SelectedNodeChanged: "SelectedNodeChanged"}
WebInspector.notifications = new WebInspector.NotificationService();
WebInspector.UIString = function (string, vararg) {
    return String.vsprintf(string, Array.prototype.slice.call(arguments, 1));
}
WebInspector.Console = function () {
    this._messages = [];
}
WebInspector.Console.Events = {MessageAdded: "messageAdded"}
WebInspector.Console.MessageLevel = {Log: "log", Warning: "warning", Error: "error"}
WebInspector.Console.Message = function (text, level, timestamp, show) {
    this.text = text;
    this.level = level;
    this.timestamp = (typeof timestamp === "number") ? timestamp : Date.now();
    this.show = show;
}
WebInspector.Console.UIDelegate = function () {
}
WebInspector.Console.UIDelegate.prototype = {
    showConsole: function () {
    }
}
WebInspector.Console.prototype = {
    setUIDelegate: function (uiDelegate) {
        this._uiDelegate = uiDelegate;
    }, addMessage: function (text, level, show) {
        var message = new WebInspector.Console.Message(text, level || WebInspector.Console.MessageLevel.Log, Date.now(), show || false);
        this._messages.push(message);
        this.dispatchEventToListeners(WebInspector.Console.Events.MessageAdded, message);
    }, log: function (text) {
        this.addMessage(text, WebInspector.Console.MessageLevel.Log);
    }, warn: function (text) {
        this.addMessage(text, WebInspector.Console.MessageLevel.Warning);
    }, error: function (text) {
        this.addMessage(text, WebInspector.Console.MessageLevel.Error, true);
    }, messages: function () {
        return this._messages;
    }, show: function () {
        if (this._uiDelegate)
            this._uiDelegate.showConsole();
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.console = new WebInspector.Console();
WebInspector.ParsedURL = function (url) {
    this.isValid = false;
    this.url = url;
    this.scheme = "";
    this.host = "";
    this.port = "";
    this.path = "";
    this.queryParams = "";
    this.fragment = "";
    this.folderPathComponents = "";
    this.lastPathComponent = "";
    var match = url.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^\/:]*)(?::([\d]+))?(?:(\/[^#]*)(?:#(.*))?)?$/i);
    if (match) {
        this.isValid = true;
        this.scheme = match[1].toLowerCase();
        this.host = match[2];
        this.port = match[3];
        this.path = match[4] || "/";
        this.fragment = match[5];
    } else {
        if (this.url.startsWith("data:")) {
            this.scheme = "data";
            return;
        }
        if (this.url === "about:blank") {
            this.scheme = "about";
            return;
        }
        this.path = this.url;
    }
    var path = this.path;
    var indexOfQuery = path.indexOf("?");
    if (indexOfQuery !== -1) {
        this.queryParams = path.substring(indexOfQuery + 1)
        path = path.substring(0, indexOfQuery);
    }
    var lastSlashIndex = path.lastIndexOf("/");
    if (lastSlashIndex !== -1) {
        this.folderPathComponents = path.substring(0, lastSlashIndex);
        this.lastPathComponent = path.substring(lastSlashIndex + 1);
    } else
        this.lastPathComponent = path;
}
WebInspector.ParsedURL.splitURL = function (url) {
    var parsedURL = new WebInspector.ParsedURL(url);
    var origin;
    var folderPath;
    var name;
    if (parsedURL.isValid) {
        origin = parsedURL.scheme + "://" + parsedURL.host;
        if (parsedURL.port)
            origin += ":" + parsedURL.port;
        folderPath = parsedURL.folderPathComponents;
        name = parsedURL.lastPathComponent;
        if (parsedURL.queryParams)
            name += "?" + parsedURL.queryParams;
    } else {
        origin = "";
        folderPath = "";
        name = url;
    }
    var result = [origin];
    var splittedPath = folderPath.split("/");
    for (var i = 1; i < splittedPath.length; ++i) {
        if (!splittedPath[i])
            continue;
        result.push(splittedPath[i]);
    }
    result.push(name);
    return result;
}
WebInspector.ParsedURL.completeURL = function (baseURL, href) {
    if (href) {
        var trimmedHref = href.trim();
        if (trimmedHref.startsWith("data:") || trimmedHref.startsWith("blob:") || trimmedHref.startsWith("javascript:"))
            return href;
        var parsedHref = trimmedHref.asParsedURL();
        if (parsedHref && parsedHref.scheme)
            return trimmedHref;
    } else {
        return baseURL;
    }
    var parsedURL = baseURL.asParsedURL();
    if (parsedURL) {
        if (parsedURL.isDataURL())
            return href;
        var path = href;
        var query = path.indexOf("?");
        var postfix = "";
        if (query !== -1) {
            postfix = path.substring(query);
            path = path.substring(0, query);
        } else {
            var fragment = path.indexOf("#");
            if (fragment !== -1) {
                postfix = path.substring(fragment);
                path = path.substring(0, fragment);
            }
        }
        if (!path) {
            var basePath = parsedURL.path;
            if (postfix.charAt(0) === "?") {
                var baseQuery = parsedURL.path.indexOf("?");
                if (baseQuery !== -1)
                    basePath = basePath.substring(0, baseQuery);
            }
            return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + basePath + postfix;
        } else if (path.charAt(0) !== "/") {
            var prefix = parsedURL.path;
            var prefixQuery = prefix.indexOf("?");
            if (prefixQuery !== -1)
                prefix = prefix.substring(0, prefixQuery);
            prefix = prefix.substring(0, prefix.lastIndexOf("/")) + "/";
            path = prefix + path;
        } else if (path.length > 1 && path.charAt(1) === "/") {
            return parsedURL.scheme + ":" + path + postfix;
        }
        return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + normalizePath(path) + postfix;
    }
    return null;
}
WebInspector.ParsedURL.prototype = {
    get displayName() {
        if (this._displayName)
            return this._displayName;
        if (this.isDataURL())
            return this.dataURLDisplayName();
        if (this.isAboutBlank())
            return this.url;
        this._displayName = this.lastPathComponent;
        if (!this._displayName)
            this._displayName = (this.host || "") + "/";
        if (this._displayName === "/")
            this._displayName = this.url;
        return this._displayName;
    }, dataURLDisplayName: function () {
        if (this._dataURLDisplayName)
            return this._dataURLDisplayName;
        if (!this.isDataURL())
            return "";
        this._dataURLDisplayName = this.url.trimEnd(20);
        return this._dataURLDisplayName;
    }, isAboutBlank: function () {
        return this.url === "about:blank";
    }, isDataURL: function () {
        return this.scheme === "data";
    }
}
String.prototype.asParsedURL = function () {
    var parsedURL = new WebInspector.ParsedURL(this.toString());
    if (parsedURL.isValid)
        return parsedURL;
    return null;
}
WebInspector.Color = function (rgba, format, originalText) {
    this._rgba = rgba;
    this._originalText = originalText || null;
    this._format = format || null;
    if (typeof this._rgba[3] === "undefined")
        this._rgba[3] = 1;
    for (var i = 0; i < 4; ++i) {
        if (this._rgba[i] < 0)
            this._rgba[i] = 0;
        if (this._rgba[i] > 1)
            this._rgba[i] = 1;
    }
}
WebInspector.Color.parse = function (text) {
    var value = text.toLowerCase().replace(/\s+/g, "");
    var simple = /^(?:#([0-9a-f]{3,6})|rgb\(([^)]+)\)|(\w+)|hsl\(([^)]+)\))$/i;
    var match = value.match(simple);
    if (match) {
        if (match[1]) {
            var hex = match[1].toUpperCase();
            var format;
            if (hex.length === 3) {
                format = WebInspector.Color.Format.ShortHEX;
                hex = hex.charAt(0) + hex.charAt(0) + hex.charAt(1) + hex.charAt(1) + hex.charAt(2) + hex.charAt(2);
            } else
                format = WebInspector.Color.Format.HEX;
            var r = parseInt(hex.substring(0, 2), 16);
            var g = parseInt(hex.substring(2, 4), 16);
            var b = parseInt(hex.substring(4, 6), 16);
            return new WebInspector.Color([r / 255, g / 255, b / 255, 1], format, text);
        }
        if (match[2]) {
            var rgbString = match[2].split(/\s*,\s*/);
            var rgba = [WebInspector.Color._parseRgbNumeric(rgbString[0]), WebInspector.Color._parseRgbNumeric(rgbString[1]), WebInspector.Color._parseRgbNumeric(rgbString[2]), 1];
            return new WebInspector.Color(rgba, WebInspector.Color.Format.RGB, text);
        }
        if (match[3]) {
            var nickname = match[3].toLowerCase();
            if (nickname in WebInspector.Color.Nicknames) {
                var rgba = WebInspector.Color.Nicknames[nickname];
                var color = WebInspector.Color.fromRGBA(rgba);
                color._format = WebInspector.Color.Format.Nickname;
                color._originalText = nickname;
                return color;
            }
            return null;
        }
        if (match[4]) {
            var hslString = match[4].replace(/%/g, "").split(/\s*,\s*/);
            var hsla = [WebInspector.Color._parseHueNumeric(hslString[0]), WebInspector.Color._parseSatLightNumeric(hslString[1]), WebInspector.Color._parseSatLightNumeric(hslString[2]), 1];
            var rgba = WebInspector.Color._hsl2rgb(hsla);
            return new WebInspector.Color(rgba, WebInspector.Color.Format.HSL, text);
        }
        return null;
    }
    var advanced = /^(?:rgba\(([^)]+)\)|hsla\(([^)]+)\))$/;
    match = value.match(advanced);
    if (match) {
        if (match[1]) {
            var rgbaString = match[1].split(/\s*,\s*/);
            var rgba = [WebInspector.Color._parseRgbNumeric(rgbaString[0]), WebInspector.Color._parseRgbNumeric(rgbaString[1]), WebInspector.Color._parseRgbNumeric(rgbaString[2]), WebInspector.Color._parseAlphaNumeric(rgbaString[3])];
            return new WebInspector.Color(rgba, WebInspector.Color.Format.RGBA, text);
        }
        if (match[2]) {
            var hslaString = match[2].replace(/%/g, "").split(/\s*,\s*/);
            var hsla = [WebInspector.Color._parseHueNumeric(hslaString[0]), WebInspector.Color._parseSatLightNumeric(hslaString[1]), WebInspector.Color._parseSatLightNumeric(hslaString[2]), WebInspector.Color._parseAlphaNumeric(hslaString[3])];
            var rgba = WebInspector.Color._hsl2rgb(hsla);
            return new WebInspector.Color(rgba, WebInspector.Color.Format.HSLA, text);
        }
    }
    return null;
}
WebInspector.Color.fromRGBA = function (rgba) {
    return new WebInspector.Color([rgba[0] / 255, rgba[1] / 255, rgba[2] / 255, rgba[3]]);
}
WebInspector.Color.fromHSVA = function (hsva) {
    var h = hsva[0];
    var s = hsva[1];
    var v = hsva[2];
    var t = (2 - s) * v;
    if (v === 0 || s === 0)
        s = 0; else
        s *= v / (t < 1 ? t : 2 - t);
    var hsla = [h, s, t / 2, hsva[3]];
    return new WebInspector.Color(WebInspector.Color._hsl2rgb(hsla), WebInspector.Color.Format.HSLA);
}
WebInspector.Color.prototype = {
    format: function () {
        return this._format;
    }, hsla: function () {
        if (this._hsla)
            return this._hsla;
        var r = this._rgba[0];
        var g = this._rgba[1];
        var b = this._rgba[2];
        var max = Math.max(r, g, b);
        var min = Math.min(r, g, b);
        var diff = max - min;
        var add = max + min;
        if (min === max)
            var h = 0; else if (r === max)
            var h = ((1 / 6 * (g - b) / diff) + 1) % 1; else if (g === max)
            var h = (1 / 6 * (b - r) / diff) + 1 / 3; else
            var h = (1 / 6 * (r - g) / diff) + 2 / 3;
        var l = 0.5 * add;
        if (l === 0)
            var s = 0; else if (l === 1)
            var s = 1; else if (l <= 0.5)
            var s = diff / add; else
            var s = diff / (2 - add);
        this._hsla = [h, s, l, this._rgba[3]];
        return this._hsla;
    }, hsva: function () {
        var hsla = this.hsla();
        var h = hsla[0];
        var s = hsla[1];
        var l = hsla[2];
        s *= l < 0.5 ? l : 1 - l;
        return [h, s !== 0 ? 2 * s / (l + s) : 0, (l + s), hsla[3]];
    }, hasAlpha: function () {
        return this._rgba[3] !== 1;
    }, canBeShortHex: function () {
        if (this.hasAlpha())
            return false;
        for (var i = 0; i < 3; ++i) {
            var c = Math.round(this._rgba[i] * 255);
            if (c % 17)
                return false;
        }
        return true;
    }, toString: function (format) {
        if (!format)
            format = this._format;
        function toRgbValue(value) {
            return Math.round(value * 255);
        }

        function toHexValue(value) {
            var hex = Math.round(value * 255).toString(16);
            return hex.length === 1 ? "0" + hex : hex;
        }

        function toShortHexValue(value) {
            return (Math.round(value * 255) / 17).toString(16);
        }

        switch (format) {
            case WebInspector.Color.Format.Original:
                return this._originalText;
            case WebInspector.Color.Format.RGB:
                if (this.hasAlpha())
                    return null;
                return String.sprintf("rgb(%d, %d, %d)", toRgbValue(this._rgba[0]), toRgbValue(this._rgba[1]), toRgbValue(this._rgba[2]));
            case WebInspector.Color.Format.RGBA:
                return String.sprintf("rgba(%d, %d, %d, %f)", toRgbValue(this._rgba[0]), toRgbValue(this._rgba[1]), toRgbValue(this._rgba[2]), this._rgba[3]);
            case WebInspector.Color.Format.HSL:
                if (this.hasAlpha())
                    return null;
                var hsl = this.hsla();
                return String.sprintf("hsl(%d, %d%, %d%)", Math.round(hsl[0] * 360), Math.round(hsl[1] * 100), Math.round(hsl[2] * 100));
            case WebInspector.Color.Format.HSLA:
                var hsla = this.hsla();
                return String.sprintf("hsla(%d, %d%, %d%, %f)", Math.round(hsla[0] * 360), Math.round(hsla[1] * 100), Math.round(hsla[2] * 100), hsla[3]);
            case WebInspector.Color.Format.HEX:
                if (this.hasAlpha())
                    return null;
                return String.sprintf("#%s%s%s", toHexValue(this._rgba[0]), toHexValue(this._rgba[1]), toHexValue(this._rgba[2])).toUpperCase();
            case WebInspector.Color.Format.ShortHEX:
                if (!this.canBeShortHex())
                    return null;
                return String.sprintf("#%s%s%s", toShortHexValue(this._rgba[0]), toShortHexValue(this._rgba[1]), toShortHexValue(this._rgba[2])).toUpperCase();
            case WebInspector.Color.Format.Nickname:
                return this.nickname();
        }
        return this._originalText;
    }, _canonicalRGBA: function () {
        var rgba = new Array(3);
        for (var i = 0; i < 3; ++i)
            rgba[i] = Math.round(this._rgba[i] * 255);
        if (this._rgba[3] !== 1)
            rgba.push(this._rgba[3]);
        return rgba;
    }, nickname: function () {
        if (!WebInspector.Color._rgbaToNickname) {
            WebInspector.Color._rgbaToNickname = {};
            for (var nickname in WebInspector.Color.Nicknames) {
                var rgba = WebInspector.Color.Nicknames[nickname];
                WebInspector.Color._rgbaToNickname[rgba] = nickname;
            }
        }
        return WebInspector.Color._rgbaToNickname[this._canonicalRGBA()] || null;
    }, toProtocolRGBA: function () {
        var rgba = this._canonicalRGBA();
        var result = {r: rgba[0], g: rgba[1], b: rgba[2]};
        if (rgba[3] !== 1)
            result.a = rgba[3];
        return result;
    }, invert: function () {
        var rgba = [];
        rgba[0] = 1 - this._rgba[0];
        rgba[1] = 1 - this._rgba[1];
        rgba[2] = 1 - this._rgba[2];
        rgba[3] = this._rgba[3];
        return new WebInspector.Color(rgba);
    }, setAlpha: function (alpha) {
        var rgba = this._rgba.slice();
        rgba[3] = alpha;
        return new WebInspector.Color(rgba);
    }
}
WebInspector.Color._parseRgbNumeric = function (value) {
    var parsed = parseInt(value, 10);
    if (value.indexOf("%") !== -1)
        parsed /= 100; else
        parsed /= 255;
    return parsed;
}
WebInspector.Color._parseHueNumeric = function (value) {
    return isNaN(value) ? 0 : (parseFloat(value) / 360) % 1;
}
WebInspector.Color._parseSatLightNumeric = function (value) {
    return parseFloat(value) / 100;
}
WebInspector.Color._parseAlphaNumeric = function (value) {
    return isNaN(value) ? 0 : parseFloat(value);
}
WebInspector.Color._hsl2rgb = function (hsl) {
    var h = hsl[0];
    var s = hsl[1];
    var l = hsl[2];

    function hue2rgb(p, q, h) {
        if (h < 0)
            h += 1; else if (h > 1)
            h -= 1;
        if ((h * 6) < 1)
            return p + (q - p) * h * 6; else if ((h * 2) < 1)
            return q; else if ((h * 3) < 2)
            return p + (q - p) * ((2 / 3) - h) * 6; else
            return p;
    }

    if (s < 0)
        s = 0;
    if (l <= 0.5)
        var q = l * (1 + s); else
        var q = l + s - (l * s);
    var p = 2 * l - q;
    var tr = h + (1 / 3);
    var tg = h;
    var tb = h - (1 / 3);
    var r = hue2rgb(p, q, tr);
    var g = hue2rgb(p, q, tg);
    var b = hue2rgb(p, q, tb);
    return [r, g, b, hsl[3]];
}
WebInspector.Color.Nicknames = {
    "aliceblue": [240, 248, 255],
    "antiquewhite": [250, 235, 215],
    "aquamarine": [127, 255, 212],
    "azure": [240, 255, 255],
    "beige": [245, 245, 220],
    "bisque": [255, 228, 196],
    "black": [0, 0, 0],
    "blanchedalmond": [255, 235, 205],
    "blue": [0, 0, 255],
    "blueviolet": [138, 43, 226],
    "brown": [165, 42, 42],
    "burlywood": [222, 184, 135],
    "cadetblue": [95, 158, 160],
    "chartreuse": [127, 255, 0],
    "chocolate": [210, 105, 30],
    "coral": [255, 127, 80],
    "cornflowerblue": [100, 149, 237],
    "cornsilk": [255, 248, 220],
    "crimson": [237, 20, 61],
    "cyan": [0, 255, 255],
    "darkblue": [0, 0, 139],
    "darkcyan": [0, 139, 139],
    "darkgoldenrod": [184, 134, 11],
    "darkgray": [169, 169, 169],
    "darkgrey": [169, 169, 169],
    "darkgreen": [0, 100, 0],
    "darkkhaki": [189, 183, 107],
    "darkmagenta": [139, 0, 139],
    "darkolivegreen": [85, 107, 47],
    "darkorange": [255, 140, 0],
    "darkorchid": [153, 50, 204],
    "darkred": [139, 0, 0],
    "darksalmon": [233, 150, 122],
    "darkseagreen": [143, 188, 143],
    "darkslateblue": [72, 61, 139],
    "darkslategray": [47, 79, 79],
    "darkslategrey": [47, 79, 79],
    "darkturquoise": [0, 206, 209],
    "darkviolet": [148, 0, 211],
    "deeppink": [255, 20, 147],
    "deepskyblue": [0, 191, 255],
    "dimgray": [105, 105, 105],
    "dimgrey": [105, 105, 105],
    "dodgerblue": [30, 144, 255],
    "firebrick": [178, 34, 34],
    "floralwhite": [255, 250, 240],
    "forestgreen": [34, 139, 34],
    "gainsboro": [220, 220, 220],
    "ghostwhite": [248, 248, 255],
    "gold": [255, 215, 0],
    "goldenrod": [218, 165, 32],
    "gray": [128, 128, 128],
    "grey": [128, 128, 128],
    "green": [0, 128, 0],
    "greenyellow": [173, 255, 47],
    "honeydew": [240, 255, 240],
    "hotpink": [255, 105, 180],
    "indianred": [205, 92, 92],
    "indigo": [75, 0, 130],
    "ivory": [255, 255, 240],
    "khaki": [240, 230, 140],
    "lavender": [230, 230, 250],
    "lavenderblush": [255, 240, 245],
    "lawngreen": [124, 252, 0],
    "lemonchiffon": [255, 250, 205],
    "lightblue": [173, 216, 230],
    "lightcoral": [240, 128, 128],
    "lightcyan": [224, 255, 255],
    "lightgoldenrodyellow": [250, 250, 210],
    "lightgreen": [144, 238, 144],
    "lightgray": [211, 211, 211],
    "lightgrey": [211, 211, 211],
    "lightpink": [255, 182, 193],
    "lightsalmon": [255, 160, 122],
    "lightseagreen": [32, 178, 170],
    "lightskyblue": [135, 206, 250],
    "lightslategray": [119, 136, 153],
    "lightslategrey": [119, 136, 153],
    "lightsteelblue": [176, 196, 222],
    "lightyellow": [255, 255, 224],
    "lime": [0, 255, 0],
    "limegreen": [50, 205, 50],
    "linen": [250, 240, 230],
    "magenta": [255, 0, 255],
    "maroon": [128, 0, 0],
    "mediumaquamarine": [102, 205, 170],
    "mediumblue": [0, 0, 205],
    "mediumorchid": [186, 85, 211],
    "mediumpurple": [147, 112, 219],
    "mediumseagreen": [60, 179, 113],
    "mediumslateblue": [123, 104, 238],
    "mediumspringgreen": [0, 250, 154],
    "mediumturquoise": [72, 209, 204],
    "mediumvioletred": [199, 21, 133],
    "midnightblue": [25, 25, 112],
    "mintcream": [245, 255, 250],
    "mistyrose": [255, 228, 225],
    "moccasin": [255, 228, 181],
    "navajowhite": [255, 222, 173],
    "navy": [0, 0, 128],
    "oldlace": [253, 245, 230],
    "olive": [128, 128, 0],
    "olivedrab": [107, 142, 35],
    "orange": [255, 165, 0],
    "orangered": [255, 69, 0],
    "orchid": [218, 112, 214],
    "palegoldenrod": [238, 232, 170],
    "palegreen": [152, 251, 152],
    "paleturquoise": [175, 238, 238],
    "palevioletred": [219, 112, 147],
    "papayawhip": [255, 239, 213],
    "peachpuff": [255, 218, 185],
    "peru": [205, 133, 63],
    "pink": [255, 192, 203],
    "plum": [221, 160, 221],
    "powderblue": [176, 224, 230],
    "purple": [128, 0, 128],
    "rebeccapurple": [102, 51, 153],
    "red": [255, 0, 0],
    "rosybrown": [188, 143, 143],
    "royalblue": [65, 105, 225],
    "saddlebrown": [139, 69, 19],
    "salmon": [250, 128, 114],
    "sandybrown": [244, 164, 96],
    "seagreen": [46, 139, 87],
    "seashell": [255, 245, 238],
    "sienna": [160, 82, 45],
    "silver": [192, 192, 192],
    "skyblue": [135, 206, 235],
    "slateblue": [106, 90, 205],
    "slategray": [112, 128, 144],
    "slategrey": [112, 128, 144],
    "snow": [255, 250, 250],
    "springgreen": [0, 255, 127],
    "steelblue": [70, 130, 180],
    "tan": [210, 180, 140],
    "teal": [0, 128, 128],
    "thistle": [216, 191, 216],
    "tomato": [255, 99, 71],
    "turquoise": [64, 224, 208],
    "violet": [238, 130, 238],
    "wheat": [245, 222, 179],
    "white": [255, 255, 255],
    "whitesmoke": [245, 245, 245],
    "yellow": [255, 255, 0],
    "yellowgreen": [154, 205, 50],
    "transparent": [0, 0, 0, 0],
};
WebInspector.Color.PageHighlight = {
    Content: WebInspector.Color.fromRGBA([111, 168, 220, .66]),
    ContentLight: WebInspector.Color.fromRGBA([111, 168, 220, .5]),
    ContentOutline: WebInspector.Color.fromRGBA([9, 83, 148]),
    Padding: WebInspector.Color.fromRGBA([147, 196, 125, .55]),
    PaddingLight: WebInspector.Color.fromRGBA([147, 196, 125, .4]),
    Border: WebInspector.Color.fromRGBA([255, 229, 153, .66]),
    BorderLight: WebInspector.Color.fromRGBA([255, 229, 153, .5]),
    Margin: WebInspector.Color.fromRGBA([246, 178, 107, .66]),
    MarginLight: WebInspector.Color.fromRGBA([246, 178, 107, .5]),
    EventTarget: WebInspector.Color.fromRGBA([255, 196, 196, .66]),
    Shape: WebInspector.Color.fromRGBA([96, 82, 177, 0.8]),
    ShapeMargin: WebInspector.Color.fromRGBA([96, 82, 127, .6])
}
WebInspector.Color.Format = {Original: "original", Nickname: "nickname", HEX: "hex", ShortHEX: "shorthex", RGB: "rgb", RGBA: "rgba", HSL: "hsl", HSLA: "hsla"}
WebInspector.TextRange = function (startLine, startColumn, endLine, endColumn) {
    this.startLine = startLine;
    this.startColumn = startColumn;
    this.endLine = endLine;
    this.endColumn = endColumn;
}
WebInspector.TextRange.createFromLocation = function (line, column) {
    return new WebInspector.TextRange(line, column, line, column);
}
WebInspector.TextRange.fromObject = function (serializedTextRange) {
    return new WebInspector.TextRange(serializedTextRange.startLine, serializedTextRange.startColumn, serializedTextRange.endLine, serializedTextRange.endColumn);
}
WebInspector.TextRange.comparator = function (range1, range2) {
    return range1.compareTo(range2);
}
WebInspector.TextRange.prototype = {
    isEmpty: function () {
        return this.startLine === this.endLine && this.startColumn === this.endColumn;
    }, immediatelyPrecedes: function (range) {
        if (!range)
            return false;
        return this.endLine === range.startLine && this.endColumn === range.startColumn;
    }, immediatelyFollows: function (range) {
        if (!range)
            return false;
        return range.immediatelyPrecedes(this);
    }, follows: function (range) {
        return (range.endLine === this.startLine && range.endColumn <= this.startColumn) || range.endLine < this.startLine;
    }, get linesCount() {
        return this.endLine - this.startLine;
    }, collapseToEnd: function () {
        return new WebInspector.TextRange(this.endLine, this.endColumn, this.endLine, this.endColumn);
    }, collapseToStart: function () {
        return new WebInspector.TextRange(this.startLine, this.startColumn, this.startLine, this.startColumn);
    }, normalize: function () {
        if (this.startLine > this.endLine || (this.startLine === this.endLine && this.startColumn > this.endColumn))
            return new WebInspector.TextRange(this.endLine, this.endColumn, this.startLine, this.startColumn); else
            return this.clone();
    }, clone: function () {
        return new WebInspector.TextRange(this.startLine, this.startColumn, this.endLine, this.endColumn);
    }, serializeToObject: function () {
        var serializedTextRange = {};
        serializedTextRange.startLine = this.startLine;
        serializedTextRange.startColumn = this.startColumn;
        serializedTextRange.endLine = this.endLine;
        serializedTextRange.endColumn = this.endColumn;
        return serializedTextRange;
    }, compareTo: function (other) {
        if (this.startLine > other.startLine)
            return 1;
        if (this.startLine < other.startLine)
            return -1;
        if (this.startColumn > other.startColumn)
            return 1;
        if (this.startColumn < other.startColumn)
            return -1;
        return 0;
    }, equal: function (other) {
        return this.startLine === other.startLine && this.endLine === other.endLine && this.startColumn === other.startColumn && this.endColumn === other.endColumn;
    }, shift: function (lineOffset) {
        return new WebInspector.TextRange(this.startLine + lineOffset, this.startColumn, this.endLine + lineOffset, this.endColumn);
    }, rebaseAfterTextEdit: function (originalRange, editedRange) {
        console.assert(originalRange.startLine === editedRange.startLine);
        console.assert(originalRange.startColumn === editedRange.startColumn);
        var rebase = this.clone();
        if (!this.follows(originalRange))
            return rebase;
        var lineDelta = editedRange.endLine - originalRange.endLine;
        var columnDelta = editedRange.endColumn - originalRange.endColumn;
        rebase.startLine += lineDelta;
        rebase.endLine += lineDelta;
        if (rebase.startLine === editedRange.endLine)
            rebase.startColumn += columnDelta;
        if (rebase.endLine === editedRange.endLine)
            rebase.endColumn += columnDelta;
        return rebase;
    }, toString: function () {
        return JSON.stringify(this);
    }
}
WebInspector.SourceRange = function (offset, length) {
    this.offset = offset;
    this.length = length;
}
WebInspector.Throttler = function (timeout) {
    this._timeout = timeout;
    this._isRunningProcess = false;
    this._asSoonAsPossible = false;
    this._process = null;
}
WebInspector.Throttler.prototype = {
    _processCompleted: function () {
        this._isRunningProcess = false;
        if (this._process)
            this._innerSchedule(false);
    }, _onTimeout: function () {
        delete this._processTimeout;
        this._asSoonAsPossible = false;
        this._isRunningProcess = true;
        var process = this._process;
        this._process = null;
        process(this._processCompleted.bind(this));
    }, schedule: function (process, asSoonAsPossible) {
        this._process = process;
        var force = !!asSoonAsPossible && !this._asSoonAsPossible;
        this._asSoonAsPossible = this._asSoonAsPossible || !!asSoonAsPossible;
        this._innerSchedule(force);
    }, _innerSchedule: function (force) {
        if (this._isRunningProcess)
            return;
        if (this._processTimeout && !force)
            return;
        if (this._processTimeout)
            this._clearTimeout(this._processTimeout);
        var timeout = this._asSoonAsPossible ? 0 : this._timeout;
        this._processTimeout = this._setTimeout(this._onTimeout.bind(this), timeout);
    }, _clearTimeout: function (timeoutId) {
        clearTimeout(timeoutId);
    }, _setTimeout: function (operation, timeout) {
        return setTimeout(operation, timeout);
    }
}
WebInspector.Throttler.FinishCallback;
WebInspector.Geometry = {};
WebInspector.Geometry._Eps = 1e-5;
WebInspector.Geometry.Vector = function (x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
}
WebInspector.Geometry.Vector.prototype = {
    length: function () {
        return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
    }, normalize: function () {
        var length = this.length();
        if (length <= WebInspector.Geometry._Eps)
            return;
        this.x /= length;
        this.y /= length;
        this.z /= length;
    }
}
WebInspector.Geometry.EulerAngles = function (alpha, beta, gamma) {
    this.alpha = alpha;
    this.beta = beta;
    this.gamma = gamma;
}
WebInspector.Geometry.EulerAngles.fromRotationMatrix = function (rotationMatrix) {
    var beta = Math.atan2(rotationMatrix.m23, rotationMatrix.m33);
    var gamma = Math.atan2(-rotationMatrix.m13, Math.sqrt(rotationMatrix.m11 * rotationMatrix.m11 + rotationMatrix.m12 * rotationMatrix.m12));
    var alpha = Math.atan2(rotationMatrix.m12, rotationMatrix.m11);
    return new WebInspector.Geometry.EulerAngles(WebInspector.Geometry.radToDeg(alpha), WebInspector.Geometry.radToDeg(beta), WebInspector.Geometry.radToDeg(gamma));
}
WebInspector.Geometry.scalarProduct = function (u, v) {
    return u.x * v.x + u.y * v.y + u.z * v.z;
}
WebInspector.Geometry.crossProduct = function (u, v) {
    var x = u.y * v.z - u.z * v.y;
    var y = u.z * v.x - u.x * v.z;
    var z = u.x * v.y - u.y * v.x;
    return new WebInspector.Geometry.Vector(x, y, z);
}
WebInspector.Geometry.subtract = function (u, v) {
    var x = u.x - v.x;
    var y = u.y - v.y;
    var z = u.z - v.z;
    return new WebInspector.Geometry.Vector(x, y, z);
}
WebInspector.Geometry.multiplyVectorByMatrixAndNormalize = function (v, m) {
    var t = v.x * m.m14 + v.y * m.m24 + v.z * m.m34 + m.m44;
    var x = (v.x * m.m11 + v.y * m.m21 + v.z * m.m31 + m.m41) / t;
    var y = (v.x * m.m12 + v.y * m.m22 + v.z * m.m32 + m.m42) / t;
    var z = (v.x * m.m13 + v.y * m.m23 + v.z * m.m33 + m.m43) / t;
    return new WebInspector.Geometry.Vector(x, y, z);
}
WebInspector.Geometry.calculateAngle = function (u, v) {
    var uLength = u.length();
    var vLength = v.length();
    if (uLength <= WebInspector.Geometry._Eps || vLength <= WebInspector.Geometry._Eps)
        return 0;
    var cos = WebInspector.Geometry.scalarProduct(u, v) / uLength / vLength;
    if (Math.abs(cos) > 1)
        return 0;
    return WebInspector.Geometry.radToDeg(Math.acos(cos));
}
WebInspector.Geometry.radToDeg = function (rad) {
    return rad * 180 / Math.PI;
}
function Size(width, height) {
    this.width = width;
    this.height = height;
}
Size.prototype.isEqual = function (size) {
    return !!size && this.width === size.width && this.height === size.height;
};
Size.prototype.widthToMax = function (size) {
    return new Size(Math.max(this.width, (typeof size === "number" ? size : size.width)), this.height);
};
Size.prototype.addWidth = function (size) {
    return new Size(this.width + (typeof size === "number" ? size : size.width), this.height);
};
Size.prototype.heightToMax = function (size) {
    return new Size(this.width, Math.max(this.height, (typeof size === "number" ? size : size.height)));
};
Size.prototype.addHeight = function (size) {
    return new Size(this.width, this.height + (typeof size === "number" ? size : size.height));
};
WebInspector.Settings = function () {
    this._eventSupport = new WebInspector.Object();
    this._registry = ({});
    this.colorFormat = this.createSetting("colorFormat", "original");
    this.consoleHistory = this.createSetting("consoleHistory", []);
    this.domWordWrap = this.createSetting("domWordWrap", true);
    this.eventListenersFilter = this.createSetting("eventListenersFilter", "all");
    this.lastViewedScriptFile = this.createSetting("lastViewedScriptFile", "application");
    this.monitoringXHREnabled = this.createSetting("monitoringXHREnabled", false);
    this.preserveConsoleLog = this.createSetting("preserveConsoleLog", false);
    this.consoleTimestampsEnabled = this.createSetting("consoleTimestampsEnabled", false);
    this.resourcesLargeRows = this.createSetting("resourcesLargeRows", true);
    this.resourcesSortOptions = this.createSetting("resourcesSortOptions", {timeOption: "responseTime", sizeOption: "transferSize"});
    this.resourceViewTab = this.createSetting("resourceViewTab", "preview");
    this.showInheritedComputedStyleProperties = this.createSetting("showInheritedComputedStyleProperties", false);
    this.showUserAgentStyles = this.createSetting("showUserAgentStyles", true);
    this.watchExpressions = this.createSetting("watchExpressions", []);
    this.breakpoints = this.createSetting("breakpoints", []);
    this.eventListenerBreakpoints = this.createSetting("eventListenerBreakpoints", []);
    this.domBreakpoints = this.createSetting("domBreakpoints", []);
    this.xhrBreakpoints = this.createSetting("xhrBreakpoints", []);
    this.jsSourceMapsEnabled = this.createSetting("sourceMapsEnabled", true);
    this.cssSourceMapsEnabled = this.createSetting("cssSourceMapsEnabled", true);
    this.cacheDisabled = this.createSetting("cacheDisabled", false);
    this.showUAShadowDOM = this.createSetting("showUAShadowDOM", false);
    this.savedURLs = this.createSetting("savedURLs", {});
    this.javaScriptDisabled = this.createSetting("javaScriptDisabled", false);
    this.showAdvancedHeapSnapshotProperties = this.createSetting("showAdvancedHeapSnapshotProperties", false);
    this.recordAllocationStacks = this.createSetting("recordAllocationStacks", false);
    this.highResolutionCpuProfiling = this.createSetting("highResolutionCpuProfiling", false);
    this.searchInContentScripts = this.createSetting("searchInContentScripts", false);
    this.textEditorIndent = this.createSetting("textEditorIndent", "    ");
    this.textEditorAutoDetectIndent = this.createSetting("textEditorAutoIndentIndent", true);
    this.textEditorAutocompletion = this.createSetting("textEditorAutocompletion", true);
    this.textEditorBracketMatching = this.createSetting("textEditorBracketMatching", true);
    this.cssReloadEnabled = this.createSetting("cssReloadEnabled", false);
    this.timelineLiveUpdate = this.createSetting("timelineLiveUpdate", true);
    this.showMetricsRulers = this.createSetting("showMetricsRulers", false);
    this.workerInspectorWidth = this.createSetting("workerInspectorWidth", 600);
    this.workerInspectorHeight = this.createSetting("workerInspectorHeight", 600);
    this.messageURLFilters = this.createSetting("messageURLFilters", {});
    this.networkHideDataURL = this.createSetting("networkHideDataURL", false);
    this.networkResourceTypeFilters = this.createSetting("networkResourceTypeFilters", {});
    this.messageLevelFilters = this.createSetting("messageLevelFilters", {});
    this.splitVerticallyWhenDockedToRight = this.createSetting("splitVerticallyWhenDockedToRight", true);
    this.visiblePanels = this.createSetting("visiblePanels", {});
    this.shortcutPanelSwitch = this.createSetting("shortcutPanelSwitch", false);
    this.showWhitespacesInEditor = this.createSetting("showWhitespacesInEditor", false);
    this.skipStackFramesPattern = this.createRegExpSetting("skipStackFramesPattern", "");
    this.pauseOnExceptionEnabled = this.createSetting("pauseOnExceptionEnabled", false);
    this.pauseOnCaughtException = this.createSetting("pauseOnCaughtException", false);
    this.enableAsyncStackTraces = this.createSetting("enableAsyncStackTraces", false);
    this.showMediaQueryInspector = this.createSetting("showMediaQueryInspector", false);
    this.disableOverridesWarning = this.createSetting("disableOverridesWarning", false);
    this.showPaintRects = this.createSetting("showPaintRects", false);
    this.showDebugBorders = this.createSetting("showDebugBorders", false);
    this.showFPSCounter = this.createSetting("showFPSCounter", false);
    this.continuousPainting = this.createSetting("continuousPainting", false);
    this.showScrollBottleneckRects = this.createSetting("showScrollBottleneckRects", false);
}
WebInspector.Settings.prototype = {
    createSetting: function (key, defaultValue) {
        if (!this._registry[key])
            this._registry[key] = new WebInspector.Setting(key, defaultValue, this._eventSupport, window.localStorage);
        return this._registry[key];
    }, createRegExpSetting: function (key, defaultValue, regexFlags) {
        if (!this._registry[key])
            this._registry[key] = new WebInspector.RegExpSetting(key, defaultValue, this._eventSupport, window.localStorage, regexFlags);
        return this._registry[key];
    }
}
WebInspector.Setting = function (name, defaultValue, eventSupport, storage) {
    this._name = name;
    this._defaultValue = defaultValue;
    this._eventSupport = eventSupport;
    this._storage = storage;
}
WebInspector.Setting.prototype = {
    addChangeListener: function (listener, thisObject) {
        this._eventSupport.addEventListener(this._name, listener, thisObject);
    }, removeChangeListener: function (listener, thisObject) {
        this._eventSupport.removeEventListener(this._name, listener, thisObject);
    }, get name() {
        return this._name;
    }, get: function () {
        if (typeof this._value !== "undefined")
            return this._value;
        this._value = this._defaultValue;
        if (this._storage && this._name in this._storage) {
            try {
                this._value = JSON.parse(this._storage[this._name]);
            } catch (e) {
                delete this._storage[this._name];
            }
        }
        return this._value;
    }, set: function (value) {
        this._value = value;
        if (this._storage) {
            try {
                this._storage[this._name] = JSON.stringify(value);
            } catch (e) {
                console.error("Error saving setting with name:" + this._name);
            }
        }
        this._eventSupport.dispatchEventToListeners(this._name, value);
    }
}
WebInspector.RegExpSetting = function (name, defaultValue, eventSupport, storage, regexFlags) {
    WebInspector.Setting.call(this, name, defaultValue ? [{pattern: defaultValue}] : [], eventSupport, storage);
    this._regexFlags = regexFlags;
}
WebInspector.RegExpSetting.prototype = {
    get: function () {
        var result = [];
        var items = this.getAsArray();
        for (var i = 0; i < items.length; ++i) {
            var item = items[i];
            if (item.pattern && !item.disabled)
                result.push(item.pattern);
        }
        return result.join("|");
    }, getAsArray: function () {
        return WebInspector.Setting.prototype.get.call(this);
    }, set: function (value) {
        this.setAsArray([{pattern: value}]);
    }, setAsArray: function (value) {
        delete this._regex;
        WebInspector.Setting.prototype.set.call(this, value);
    }, asRegExp: function () {
        if (typeof this._regex !== "undefined")
            return this._regex;
        this._regex = null;
        try {
            var pattern = this.get();
            if (pattern)
                this._regex = new RegExp(pattern, this._regexFlags || "");
        } catch (e) {
        }
        return this._regex;
    }, __proto__: WebInspector.Setting.prototype
}
WebInspector.ExperimentsSettings = function (experimentsEnabled) {
    this._experimentsEnabled = experimentsEnabled;
    this._setting = WebInspector.settings.createSetting("experiments", {});
    this._experiments = [];
    this._enabledForTest = {};
    this.applyCustomStylesheet = this._createExperiment("applyCustomStylesheet", "Allow custom UI themes");
    this.canvasInspection = this._createExperiment("canvasInspection ", "Canvas inspection");
    this.devicesPanel = this._createExperiment("devicesPanel", "Devices panel");
    this.disableAgentsWhenProfile = this._createExperiment("disableAgentsWhenProfile", "Disable other agents and UI when profiler is active", true);
    this.dockToLeft = this._createExperiment("dockToLeft", "Dock to left", true);
    this.documentation = this._createExperiment("documentation", "Documentation for JS and CSS", true);
    this.fileSystemInspection = this._createExperiment("fileSystemInspection", "FileSystem inspection");
    this.gpuTimeline = this._createExperiment("gpuTimeline", "GPU data on timeline", true);
    this.layersPanel = this._createExperiment("layersPanel", "Layers panel");
    this.timelineOnTraceEvents = this._createExperiment("timelineOnTraceEvents", "Timeline on trace events");
    this.paintProfiler = this._createExperiment("paintProfiler", "Paint profiler");
    this.timelinePowerProfiler = this._createExperiment("timelinePowerProfiler", "Timeline power profiler");
    this.timelineJSCPUProfile = this._createExperiment("timelineJSCPUProfile", "Timeline with JS sampling");
    this._cleanUpSetting();
}
WebInspector.ExperimentsSettings.prototype = {
    get experiments() {
        return this._experiments.slice();
    }, get experimentsEnabled() {
        return this._experimentsEnabled;
    }, _createExperiment: function (experimentName, experimentTitle, hidden) {
        var experiment = new WebInspector.Experiment(this, experimentName, experimentTitle, !!hidden);
        this._experiments.push(experiment);
        return experiment;
    }, isEnabled: function (experimentName) {
        if (this._enabledForTest[experimentName])
            return true;
        if (!this.experimentsEnabled)
            return false;
        var experimentsSetting = this._setting.get();
        return experimentsSetting[experimentName];
    }, setEnabled: function (experimentName, enabled) {
        var experimentsSetting = this._setting.get();
        experimentsSetting[experimentName] = enabled;
        this._setting.set(experimentsSetting);
    }, _enableForTest: function (experimentName) {
        this._enabledForTest[experimentName] = true;
    }, _cleanUpSetting: function () {
        var experimentsSetting = this._setting.get();
        var cleanedUpExperimentSetting = {};
        for (var i = 0; i < this._experiments.length; ++i) {
            var experimentName = this._experiments[i].name;
            if (experimentsSetting[experimentName])
                cleanedUpExperimentSetting[experimentName] = true;
        }
        this._setting.set(cleanedUpExperimentSetting);
    }
}
WebInspector.Experiment = function (experimentsSettings, name, title, hidden) {
    this._name = name;
    this._title = title;
    this._hidden = hidden;
    this._experimentsSettings = experimentsSettings;
}
WebInspector.Experiment.prototype = {
    get name() {
        return this._name;
    }, get title() {
        return this._title;
    }, get hidden() {
        return this._hidden;
    }, isEnabled: function () {
        return this._experimentsSettings.isEnabled(this._name);
    }, setEnabled: function (enabled) {
        this._experimentsSettings.setEnabled(this._name, enabled);
    }, enableForTest: function () {
        this._experimentsSettings._enableForTest(this._name);
    }
}
WebInspector.VersionController = function () {
}
WebInspector.VersionController.currentVersion = 9;
WebInspector.VersionController.prototype = {
    updateVersion: function () {
        var versionSetting = WebInspector.settings.createSetting("inspectorVersion", 0);
        var currentVersion = WebInspector.VersionController.currentVersion;
        var oldVersion = versionSetting.get();
        var methodsToRun = this._methodsToRunToUpdateVersion(oldVersion, currentVersion);
        for (var i = 0; i < methodsToRun.length; ++i)
            this[methodsToRun[i]].call(this);
        versionSetting.set(currentVersion);
    }, _methodsToRunToUpdateVersion: function (oldVersion, currentVersion) {
        var result = [];
        for (var i = oldVersion; i < currentVersion; ++i)
            result.push("_updateVersionFrom" + i + "To" + (i + 1));
        return result;
    }, _updateVersionFrom0To1: function () {
        this._clearBreakpointsWhenTooMany(WebInspector.settings.breakpoints, 500000);
    }, _updateVersionFrom1To2: function () {
        var versionSetting = WebInspector.settings.createSetting("previouslyViewedFiles", []);
        versionSetting.set([]);
    }, _updateVersionFrom2To3: function () {
        var fileSystemMappingSetting = WebInspector.settings.createSetting("fileSystemMapping", {});
        fileSystemMappingSetting.set({});
        if (window.localStorage)
            delete window.localStorage["fileMappingEntries"];
    }, _updateVersionFrom3To4: function () {
        var advancedMode = WebInspector.settings.createSetting("showHeaSnapshotObjectsHiddenProperties", false).get();
        WebInspector.settings.showAdvancedHeapSnapshotProperties.set(advancedMode);
    }, _updateVersionFrom4To5: function () {
        if (!window.localStorage)
            return;
        var settingNames = {
            "FileSystemViewSidebarWidth": "fileSystemViewSplitViewState",
            "canvasProfileViewReplaySplitLocation": "canvasProfileViewReplaySplitViewState",
            "canvasProfileViewSplitLocation": "canvasProfileViewSplitViewState",
            "elementsSidebarWidth": "elementsPanelSplitViewState",
            "StylesPaneSplitRatio": "stylesPaneSplitViewState",
            "heapSnapshotRetainersViewSize": "heapSnapshotSplitViewState",
            "InspectorView.splitView": "InspectorView.splitViewState",
            "InspectorView.screencastSplitView": "InspectorView.screencastSplitViewState",
            "Inspector.drawerSplitView": "Inspector.drawerSplitViewState",
            "layerDetailsSplitView": "layerDetailsSplitViewState",
            "networkSidebarWidth": "networkPanelSplitViewState",
            "sourcesSidebarWidth": "sourcesPanelSplitViewState",
            "scriptsPanelNavigatorSidebarWidth": "sourcesPanelNavigatorSplitViewState",
            "sourcesPanelSplitSidebarRatio": "sourcesPanelDebuggerSidebarSplitViewState",
            "timeline-details": "timelinePanelDetailsSplitViewState",
            "timeline-split": "timelinePanelRecorsSplitViewState",
            "timeline-view": "timelinePanelTimelineStackSplitViewState",
            "auditsSidebarWidth": "auditsPanelSplitViewState",
            "layersSidebarWidth": "layersPanelSplitViewState",
            "profilesSidebarWidth": "profilesPanelSplitViewState",
            "resourcesSidebarWidth": "resourcesPanelSplitViewState"
        };
        for (var oldName in settingNames) {
            var newName = settingNames[oldName];
            var oldNameH = oldName + "H";
            var newValue = null;
            var oldSetting = WebInspector.settings.createSetting(oldName, undefined).get();
            if (oldSetting) {
                newValue = newValue || {};
                newValue.vertical = {};
                newValue.vertical.size = oldSetting;
                delete window.localStorage[oldName];
            }
            var oldSettingH = WebInspector.settings.createSetting(oldNameH, undefined).get();
            if (oldSettingH) {
                newValue = newValue || {};
                newValue.horizontal = {};
                newValue.horizontal.size = oldSettingH;
                delete window.localStorage[oldNameH];
            }
            var newSetting = WebInspector.settings.createSetting(newName, {});
            if (newValue)
                newSetting.set(newValue);
        }
    }, _updateVersionFrom5To6: function () {
        if (!window.localStorage)
            return;
        var settingNames = {"debuggerSidebarHidden": "sourcesPanelSplitViewState", "navigatorHidden": "sourcesPanelNavigatorSplitViewState", "WebInspector.Drawer.showOnLoad": "Inspector.drawerSplitViewState"};
        for (var oldName in settingNames) {
            var newName = settingNames[oldName];
            var oldSetting = WebInspector.settings.createSetting(oldName, undefined).get();
            var invert = "WebInspector.Drawer.showOnLoad" === oldName;
            var hidden = !!oldSetting !== invert;
            delete window.localStorage[oldName];
            var showMode = hidden ? "OnlyMain" : "Both";
            var newSetting = WebInspector.settings.createSetting(newName, null);
            var newValue = newSetting.get() || {};
            newValue.vertical = newValue.vertical || {};
            newValue.vertical.showMode = showMode;
            newValue.horizontal = newValue.horizontal || {};
            newValue.horizontal.showMode = showMode;
            newSetting.set(newValue);
        }
    }, _updateVersionFrom6To7: function () {
        if (!window.localStorage)
            return;
        var settingNames = {
            "sourcesPanelNavigatorSplitViewState": "sourcesPanelNavigatorSplitViewState",
            "elementsPanelSplitViewState": "elementsPanelSplitViewState",
            "canvasProfileViewReplaySplitViewState": "canvasProfileViewReplaySplitViewState",
            "stylesPaneSplitViewState": "stylesPaneSplitViewState",
            "sourcesPanelDebuggerSidebarSplitViewState": "sourcesPanelDebuggerSidebarSplitViewState"
        };
        for (var name in settingNames) {
            if (!(name in window.localStorage))
                continue;
            var setting = WebInspector.settings.createSetting(name, undefined);
            var value = setting.get();
            if (!value)
                continue;
            if (value.vertical && value.vertical.size && value.vertical.size < 1)
                value.vertical.size = 0;
            if (value.horizontal && value.horizontal.size && value.horizontal.size < 1)
                value.horizontal.size = 0;
            setting.set(value);
        }
    }, _updateVersionFrom7To8: function () {
        var settingName = "deviceMetrics";
        if (!window.localStorage || !(settingName in window.localStorage))
            return;
        var setting = WebInspector.settings.createSetting(settingName, undefined);
        var value = setting.get();
        if (!value)
            return;
        var components = value.split("x");
        if (components.length >= 3) {
            var width = parseInt(components[0], 10);
            var height = parseInt(components[1], 10);
            var deviceScaleFactor = parseFloat(components[2]);
            if (deviceScaleFactor) {
                components[0] = "" + Math.round(width / deviceScaleFactor);
                components[1] = "" + Math.round(height / deviceScaleFactor);
            }
        }
        value = components.join("x");
        setting.set(value);
    }, _updateVersionFrom8To9: function () {
        if (!window.localStorage)
            return;
        var settingNames = ["skipStackFramesPattern", "workspaceFolderExcludePattern"];
        for (var i = 0; i < settingNames.length; ++i) {
            var settingName = settingNames[i];
            if (!(settingName in window.localStorage))
                continue;
            try {
                var value = JSON.parse(window.localStorage[settingName]);
                if (!value)
                    continue;
                if (typeof value === "string")
                    value = [value];
                for (var j = 0; j < value.length; ++j) {
                    if (typeof value[j] === "string")
                        value[j] = {pattern: value[j]};
                }
                window.localStorage[settingName] = JSON.stringify(value);
            } catch (e) {
            }
        }
    }, _clearBreakpointsWhenTooMany: function (breakpointsSetting, maxBreakpointsCount) {
        if (breakpointsSetting.get().length > maxBreakpointsCount)
            breakpointsSetting.set([]);
    }
}
WebInspector.settings;
WebInspector.experimentsSettings;
WebInspector.PauseOnExceptionStateSetting = function () {
    WebInspector.settings.pauseOnExceptionEnabled.addChangeListener(this._enabledChanged, this);
    WebInspector.settings.pauseOnCaughtException.addChangeListener(this._pauseOnCaughtChanged, this);
    this._name = "pauseOnExceptionStateString";
    this._eventSupport = new WebInspector.Object();
    this._value = this._calculateValue();
}
WebInspector.PauseOnExceptionStateSetting.prototype = {
    addChangeListener: function (listener, thisObject) {
        this._eventSupport.addEventListener(this._name, listener, thisObject);
    }, removeChangeListener: function (listener, thisObject) {
        this._eventSupport.removeEventListener(this._name, listener, thisObject);
    }, get: function () {
        return this._value;
    }, _calculateValue: function () {
        if (!WebInspector.settings.pauseOnExceptionEnabled.get())
            return "none";
        return "all";
    }, _enabledChanged: function (event) {
        this._fireChangedIfNeeded();
    }, _pauseOnCaughtChanged: function (event) {
        this._fireChangedIfNeeded();
    }, _fireChangedIfNeeded: function () {
        var newValue = this._calculateValue();
        if (newValue === this._value)
            return;
        this._value = newValue;
        this._eventSupport.dispatchEventToListeners(this._name, this._value);
    }
}
WebInspector.TextUtils = {
    isStopChar: function (char) {
        return (char > " " && char < "0") || (char > "9" && char < "A") || (char > "Z" && char < "_") || (char > "_" && char < "a") || (char > "z" && char <= "~");
    }, isWordChar: function (char) {
        return !WebInspector.TextUtils.isStopChar(char) && !WebInspector.TextUtils.isSpaceChar(char);
    }, isSpaceChar: function (char) {
        return WebInspector.TextUtils._SpaceCharRegex.test(char);
    }, isWord: function (word) {
        for (var i = 0; i < word.length; ++i) {
            if (!WebInspector.TextUtils.isWordChar(word.charAt(i)))
                return false;
        }
        return true;
    }, isOpeningBraceChar: function (char) {
        return char === "(" || char === "{";
    }, isClosingBraceChar: function (char) {
        return char === ")" || char === "}";
    }, isBraceChar: function (char) {
        return WebInspector.TextUtils.isOpeningBraceChar(char) || WebInspector.TextUtils.isClosingBraceChar(char);
    }, textToWords: function (text, isWordChar) {
        var words = [];
        var startWord = -1;
        for (var i = 0; i < text.length; ++i) {
            if (!isWordChar(text.charAt(i))) {
                if (startWord !== -1)
                    words.push(text.substring(startWord, i));
                startWord = -1;
            } else if (startWord === -1)
                startWord = i;
        }
        if (startWord !== -1)
            words.push(text.substring(startWord));
        return words;
    }, findBalancedCurlyBrackets: function (source, startIndex, lastIndex) {
        lastIndex = lastIndex || source.length;
        startIndex = startIndex || 0;
        var counter = 0;
        var inString = false;
        for (var index = startIndex; index < lastIndex; ++index) {
            var character = source[index];
            if (inString) {
                if (character === "\\")
                    ++index; else if (character === "\"")
                    inString = false;
            } else {
                if (character === "\"")
                    inString = true; else if (character === "{")
                    ++counter; else if (character === "}") {
                    if (--counter === 0)
                        return index + 1;
                }
            }
        }
        return -1;
    }, lineIndent: function (line) {
        var indentation = 0;
        while (indentation < line.length && WebInspector.TextUtils.isSpaceChar(line.charAt(indentation)))
            ++indentation;
        return line.substr(0, indentation);
    }, isUpperCase: function (text) {
        return text === text.toUpperCase();
    }, isLowerCase: function (text) {
        return text === text.toLowerCase();
    }
}
WebInspector.TextUtils._SpaceCharRegex = /\s/;
WebInspector.TextUtils.Indent = {TwoSpaces: "  ", FourSpaces: "    ", EightSpaces: "        ", TabCharacter: "\t"}
WebInspector.Progress = function () {
}
WebInspector.Progress.Events = {Canceled: "Canceled", Done: "Done"}
WebInspector.Progress.prototype = {
    setTotalWork: function (totalWork) {
    }, setTitle: function (title) {
    }, setWorked: function (worked, title) {
    }, worked: function (worked) {
    }, done: function () {
    }, isCanceled: function () {
        return false;
    }, addEventListener: function (eventType, listener, thisObject) {
    }
}
WebInspector.CompositeProgress = function (parent) {
    this._parent = parent;
    this._children = [];
    this._childrenDone = 0;
    this._parent.setTotalWork(1);
    this._parent.setWorked(0);
    parent.addEventListener(WebInspector.Progress.Events.Canceled, this._parentCanceled.bind(this));
}
WebInspector.CompositeProgress.prototype = {
    _childDone: function () {
        if (++this._childrenDone !== this._children.length)
            return;
        this.dispatchEventToListeners(WebInspector.Progress.Events.Done);
        this._parent.done();
    }, _parentCanceled: function () {
        this.dispatchEventToListeners(WebInspector.Progress.Events.Canceled);
        for (var i = 0; i < this._children.length; ++i) {
            this._children[i].dispatchEventToListeners(WebInspector.Progress.Events.Canceled);
        }
    }, createSubProgress: function (weight) {
        var child = new WebInspector.SubProgress(this, weight);
        this._children.push(child);
        return child;
    }, _update: function () {
        var totalWeights = 0;
        var done = 0;
        for (var i = 0; i < this._children.length; ++i) {
            var child = this._children[i];
            if (child._totalWork)
                done += child._weight * child._worked / child._totalWork;
            totalWeights += child._weight;
        }
        this._parent.setWorked(done / totalWeights);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.SubProgress = function (composite, weight) {
    this._composite = composite;
    this._weight = weight || 1;
    this._worked = 0;
}
WebInspector.SubProgress.prototype = {
    isCanceled: function () {
        return this._composite._parent.isCanceled();
    }, setTitle: function (title) {
        this._composite._parent.setTitle(title);
    }, done: function () {
        this.setWorked(this._totalWork);
        this._composite._childDone();
        this.dispatchEventToListeners(WebInspector.Progress.Events.Done);
    }, setTotalWork: function (totalWork) {
        this._totalWork = totalWork;
        this._composite._update();
    }, setWorked: function (worked, title) {
        this._worked = worked;
        if (typeof title !== "undefined")
            this.setTitle(title);
        this._composite._update();
    }, worked: function (worked) {
        this.setWorked(this._worked + (worked || 1));
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.Renderer = function () {
}
WebInspector.Renderer.prototype = {
    render: function (object) {
    }
}
WebInspector.Revealer = function () {
}
WebInspector.Revealer.reveal = function (revealable, lineNumber) {
    if (!revealable)
        return;
    var revealer = self.runtime.instance(WebInspector.Revealer, revealable);
    if (revealer)
        revealer.reveal(revealable, lineNumber);
}
WebInspector.Revealer.prototype = {
    reveal: function (object, lineNumber) {
    }
}
WebInspector.NodeRemoteObjectInspector = function () {
}
WebInspector.NodeRemoteObjectInspector.prototype = {
    inspectNodeObject: function (object) {
    }
}
WebInspector.Lock = function () {
    this._count = 0;
}
WebInspector.Lock.Events = {StateChanged: "StateChanged"}
WebInspector.Lock.prototype = {
    isAcquired: function () {
        return !!this._count;
    }, acquire: function () {
        if (++this._count === 1)
            this.dispatchEventToListeners(WebInspector.Lock.Events.StateChanged);
    }, release: function () {
        --this._count;
        if (this._count < 0) {
            console.error("WebInspector.Lock acquire/release calls are unbalanced " + new Error().stack);
            return;
        }
        if (!this._count)
            this.dispatchEventToListeners(WebInspector.Lock.Events.StateChanged);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.CompletionDictionary = function () {
}
WebInspector.CompletionDictionary.prototype = {
    addWord: function (word) {
    }, removeWord: function (word) {
    }, hasWord: function (word) {
    }, wordsWithPrefix: function (prefix) {
    }, wordCount: function (word) {
    }, reset: function () {
    }
}
WebInspector.SampleCompletionDictionary = function () {
    this._words = {};
}
WebInspector.SampleCompletionDictionary.prototype = {
    addWord: function (word) {
        if (!this._words[word])
            this._words[word] = 1; else
            ++this._words[word];
    }, removeWord: function (word) {
        if (!this._words[word])
            return;
        if (this._words[word] === 1)
            delete this._words[word]; else
            --this._words[word];
    }, wordsWithPrefix: function (prefix) {
        var words = [];
        for (var i in this._words) {
            if (i.startsWith(prefix))
                words.push(i);
        }
        return words;
    }, hasWord: function (word) {
        return !!this._words[word];
    }, wordCount: function (word) {
        return this._words[word] ? this._words[word] : 0;
    }, reset: function () {
        this._words = {};
    }
}
Node.prototype.rangeOfWord = function (offset, stopCharacters, stayWithinNode, direction) {
    var startNode;
    var startOffset = 0;
    var endNode;
    var endOffset = 0;
    if (!stayWithinNode)
        stayWithinNode = this;
    if (!direction || direction === "backward" || direction === "both") {
        var node = this;
        while (node) {
            if (node === stayWithinNode) {
                if (!startNode)
                    startNode = stayWithinNode;
                break;
            }
            if (node.nodeType === Node.TEXT_NODE) {
                var start = (node === this ? (offset - 1) : (node.nodeValue.length - 1));
                for (var i = start; i >= 0; --i) {
                    if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
                        startNode = node;
                        startOffset = i + 1;
                        break;
                    }
                }
            }
            if (startNode)
                break;
            node = node.traversePreviousNode(stayWithinNode);
        }
        if (!startNode) {
            startNode = stayWithinNode;
            startOffset = 0;
        }
    } else {
        startNode = this;
        startOffset = offset;
    }
    if (!direction || direction === "forward" || direction === "both") {
        node = this;
        while (node) {
            if (node === stayWithinNode) {
                if (!endNode)
                    endNode = stayWithinNode;
                break;
            }
            if (node.nodeType === Node.TEXT_NODE) {
                var start = (node === this ? offset : 0);
                for (var i = start; i < node.nodeValue.length; ++i) {
                    if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
                        endNode = node;
                        endOffset = i;
                        break;
                    }
                }
            }
            if (endNode)
                break;
            node = node.traverseNextNode(stayWithinNode);
        }
        if (!endNode) {
            endNode = stayWithinNode;
            endOffset = stayWithinNode.nodeType === Node.TEXT_NODE ? stayWithinNode.nodeValue.length : stayWithinNode.childNodes.length;
        }
    } else {
        endNode = this;
        endOffset = offset;
    }
    var result = this.ownerDocument.createRange();
    result.setStart(startNode, startOffset);
    result.setEnd(endNode, endOffset);
    return result;
}
Node.prototype.traverseNextTextNode = function (stayWithin) {
    var node = this.traverseNextNode(stayWithin);
    if (!node)
        return null;
    while (node && node.nodeType !== Node.TEXT_NODE)
        node = node.traverseNextNode(stayWithin);
    return node;
}
Node.prototype.rangeBoundaryForOffset = function (offset) {
    var node = this.traverseNextTextNode(this);
    while (node && offset > node.nodeValue.length) {
        offset -= node.nodeValue.length;
        node = node.traverseNextTextNode(this);
    }
    if (!node)
        return {container: this, offset: 0};
    return {container: node, offset: offset};
}
Element.prototype.positionAt = function (x, y, relativeTo) {
    var shift = {x: 0, y: 0};
    if (relativeTo)
        shift = relativeTo.boxInWindow(this.ownerDocument.defaultView);
    if (typeof x === "number")
        this.style.setProperty("left", (shift.x + x) + "px"); else
        this.style.removeProperty("left");
    if (typeof y === "number")
        this.style.setProperty("top", (shift.y + y) + "px"); else
        this.style.removeProperty("top");
}
Element.prototype.isScrolledToBottom = function () {
    return Math.abs(this.scrollTop + this.clientHeight - this.scrollHeight) <= 1;
}
function removeSubsequentNodes(fromNode, toNode) {
    for (var node = fromNode; node && node !== toNode;) {
        var nodeToRemove = node;
        node = node.nextSibling;
        nodeToRemove.remove();
    }
}
function Constraints(minimum, preferred) {
    this.minimum = minimum;
    this.preferred = preferred || minimum;
    if (this.minimum.width > this.preferred.width || this.minimum.height > this.preferred.height)
        throw new Error("Minimum size is greater than preferred.");
}
Constraints.prototype.isEqual = function (constraints) {
    return !!constraints && this.minimum.isEqual(constraints.minimum) && this.preferred.isEqual(constraints.preferred);
}
Constraints.prototype.widthToMax = function (value) {
    if (typeof value === "number")
        return new Constraints(this.minimum.widthToMax(value), this.preferred.widthToMax(value));
    return new Constraints(this.minimum.widthToMax(value.minimum), this.preferred.widthToMax(value.preferred));
}
Constraints.prototype.addWidth = function (value) {
    if (typeof value === "number")
        return new Constraints(this.minimum.addWidth(value), this.preferred.addWidth(value));
    return new Constraints(this.minimum.addWidth(value.minimum), this.preferred.addWidth(value.preferred));
}
Constraints.prototype.heightToMax = function (value) {
    if (typeof value === "number")
        return new Constraints(this.minimum.heightToMax(value), this.preferred.heightToMax(value));
    return new Constraints(this.minimum.heightToMax(value.minimum), this.preferred.heightToMax(value.preferred));
}
Constraints.prototype.addHeight = function (value) {
    if (typeof value === "number")
        return new Constraints(this.minimum.addHeight(value), this.preferred.addHeight(value));
    return new Constraints(this.minimum.addHeight(value.minimum), this.preferred.addHeight(value.preferred));
}
Element.prototype.measurePreferredSize = function (containerElement) {
    containerElement = containerElement || document.body;
    containerElement.appendChild(this);
    this.positionAt(0, 0);
    var result = new Size(this.offsetWidth, this.offsetHeight);
    this.positionAt(undefined, undefined);
    this.remove();
    return result;
}
Element.prototype.containsEventPoint = function (event) {
    var box = this.getBoundingClientRect();
    return box.left < event.x && event.x < box.right && box.top < event.y && event.y < box.bottom;
}
Node.prototype.enclosingNodeOrSelfWithNodeNameInArray = function (nameArray) {
    for (var node = this; node && node !== this.ownerDocument; node = node.parentNode) {
        for (var i = 0; i < nameArray.length; ++i) {
            if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase())
                return node;
        }
    }
    return null;
}
Node.prototype.enclosingNodeOrSelfWithNodeName = function (nodeName) {
    return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);
}
Node.prototype.enclosingNodeOrSelfWithClass = function (className, stayWithin) {
    for (var node = this; node && node !== stayWithin && node !== this.ownerDocument; node = node.parentNode) {
        if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains(className))
            return (node);
    }
    return null;
}
Element.prototype.query = function (query) {
    return this.ownerDocument.evaluate(query, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
Element.prototype.removeChildren = function () {
    if (this.firstChild)
        this.textContent = "";
}
Element.prototype.isInsertionCaretInside = function () {
    var selection = window.getSelection();
    if (!selection.rangeCount || !selection.isCollapsed)
        return false;
    var selectionRange = selection.getRangeAt(0);
    return selectionRange.startContainer.isSelfOrDescendant(this);
}
Document.prototype.createElementWithClass = function (elementName, className) {
    var element = this.createElement(elementName);
    if (className)
        element.className = className;
    return element;
}
Element.prototype.createChild = function (elementName, className) {
    var element = this.ownerDocument.createElementWithClass(elementName, className);
    this.appendChild(element);
    return element;
}
DocumentFragment.prototype.createChild = Element.prototype.createChild;
Element.prototype.createTextChild = function (text) {
    var element = this.ownerDocument.createTextNode(text);
    this.appendChild(element);
    return element;
}
DocumentFragment.prototype.createTextChild = Element.prototype.createTextChild;
Element.prototype.createTextChildren = function (var_args) {
    for (var i = 0, n = arguments.length; i < n; ++i)
        this.createTextChild(arguments[i]);
}
DocumentFragment.prototype.createTextChildren = Element.prototype.createTextChildren;
Element.prototype.appendChildren = function (var_args) {
    for (var i = 0, n = arguments.length; i < n; ++i)
        this.appendChild(arguments[i]);
}
Element.prototype.totalOffsetLeft = function () {
    return this.totalOffset().left;
}
Element.prototype.totalOffsetTop = function () {
    return this.totalOffset().top;
}
Element.prototype.totalOffset = function () {
    var rect = this.getBoundingClientRect();
    return {left: rect.left, top: rect.top};
}
Element.prototype.scrollOffset = function () {
    var curLeft = 0;
    var curTop = 0;
    for (var element = this; element; element = element.scrollParent) {
        curLeft += element.scrollLeft;
        curTop += element.scrollTop;
    }
    return {left: curLeft, top: curTop};
}
function AnchorBox(x, y, width, height) {
    this.x = x || 0;
    this.y = y || 0;
    this.width = width || 0;
    this.height = height || 0;
}
AnchorBox.prototype.relativeTo = function (box) {
    return new AnchorBox(this.x - box.x, this.y - box.y, this.width, this.height);
}
AnchorBox.prototype.relativeToElement = function (element) {
    return this.relativeTo(element.boxInWindow(element.ownerDocument.defaultView));
}
AnchorBox.prototype.equals = function (anchorBox) {
    return !!anchorBox && this.x === anchorBox.x && this.y === anchorBox.y && this.width === anchorBox.width && this.height === anchorBox.height;
}
Element.prototype.offsetRelativeToWindow = function (targetWindow) {
    var elementOffset = new AnchorBox();
    var curElement = this;
    var curWindow = this.ownerDocument.defaultView;
    while (curWindow && curElement) {
        elementOffset.x += curElement.totalOffsetLeft();
        elementOffset.y += curElement.totalOffsetTop();
        if (curWindow === targetWindow)
            break;
        curElement = curWindow.frameElement;
        curWindow = curWindow.parent;
    }
    return elementOffset;
}
Element.prototype.boxInWindow = function (targetWindow) {
    targetWindow = targetWindow || this.ownerDocument.defaultView;
    var anchorBox = this.offsetRelativeToWindow(window);
    anchorBox.width = Math.min(this.offsetWidth, window.innerWidth - anchorBox.x);
    anchorBox.height = Math.min(this.offsetHeight, window.innerHeight - anchorBox.y);
    return anchorBox;
}
Element.prototype.setTextAndTitle = function (text) {
    this.textContent = text;
    this.title = text;
}
KeyboardEvent.prototype.__defineGetter__("data", function () {
    switch (this.type) {
        case"keypress":
            if (!this.ctrlKey && !this.metaKey)
                return String.fromCharCode(this.charCode); else
                return "";
        case"keydown":
        case"keyup":
            if (!this.ctrlKey && !this.metaKey && !this.altKey)
                return String.fromCharCode(this.which); else
                return "";
    }
});
Event.prototype.consume = function (preventDefault) {
    this.stopImmediatePropagation();
    if (preventDefault)
        this.preventDefault();
    this.handled = true;
}
Text.prototype.select = function (start, end) {
    start = start || 0;
    end = end || this.textContent.length;
    if (start < 0)
        start = end + start;
    var selection = this.ownerDocument.defaultView.getSelection();
    selection.removeAllRanges();
    var range = this.ownerDocument.createRange();
    range.setStart(this, start);
    range.setEnd(this, end);
    selection.addRange(range);
    return this;
}
Element.prototype.selectionLeftOffset = function () {
    var selection = window.getSelection();
    if (!selection.containsNode(this, true))
        return null;
    var leftOffset = selection.anchorOffset;
    var node = selection.anchorNode;
    while (node !== this) {
        while (node.previousSibling) {
            node = node.previousSibling;
            leftOffset += node.textContent.length;
        }
        node = node.parentNode;
    }
    return leftOffset;
}
Node.prototype.isAncestor = function (node) {
    if (!node)
        return false;
    var currentNode = node.parentNode;
    while (currentNode) {
        if (this === currentNode)
            return true;
        currentNode = currentNode.parentNode;
    }
    return false;
}
Node.prototype.isDescendant = function (descendant) {
    return !!descendant && descendant.isAncestor(this);
}
Node.prototype.isSelfOrAncestor = function (node) {
    return !!node && (node === this || this.isAncestor(node));
}
Node.prototype.isSelfOrDescendant = function (node) {
    return !!node && (node === this || this.isDescendant(node));
}
Node.prototype.traverseNextNode = function (stayWithin) {
    var node = this.firstChild;
    if (node)
        return node;
    if (stayWithin && this === stayWithin)
        return null;
    node = this.nextSibling;
    if (node)
        return node;
    node = this;
    while (node && !node.nextSibling && (!stayWithin || !node.parentNode || node.parentNode !== stayWithin))
        node = node.parentNode;
    if (!node)
        return null;
    return node.nextSibling;
}
Node.prototype.traversePreviousNode = function (stayWithin) {
    if (stayWithin && this === stayWithin)
        return null;
    var node = this.previousSibling;
    while (node && node.lastChild)
        node = node.lastChild;
    if (node)
        return node;
    return this.parentNode;
}
Node.prototype.setTextContentTruncatedIfNeeded = function (text, placeholder) {
    const maxTextContentLength = 65535;
    if (typeof text === "string" && text.length > maxTextContentLength) {
        this.textContent = typeof placeholder === "string" ? placeholder : text.trimEnd(maxTextContentLength);
        return true;
    }
    this.textContent = text;
    return false;
}
function isEnterKey(event) {
    return event.keyCode !== 229 && event.keyIdentifier === "Enter";
}
function consumeEvent(e) {
    e.consume();
}
function TreeOutline(listNode, nonFocusable) {
    this.children = [];
    this.selectedTreeElement = null;
    this._childrenListNode = listNode;
    this.childrenListElement = this._childrenListNode;
    this._childrenListNode.removeChildren();
    this.expandTreeElementsWhenArrowing = false;
    this.root = true;
    this.hasChildren = false;
    this.expanded = true;
    this.selected = false;
    this.treeOutline = this;
    this.comparator = null;
    this.setFocusable(!nonFocusable);
    this._childrenListNode.addEventListener("keydown", this._treeKeyDown.bind(this), true);
    this._treeElementsMap = new Map();
    this._expandedStateMap = new Map();
    this.element = listNode;
}
TreeOutline.prototype.setFocusable = function (focusable) {
    if (focusable)
        this._childrenListNode.setAttribute("tabIndex", 0); else
        this._childrenListNode.removeAttribute("tabIndex");
}
TreeOutline.prototype.appendChild = function (child) {
    var insertionIndex;
    if (this.treeOutline.comparator)
        insertionIndex = insertionIndexForObjectInListSortedByFunction(child, this.children, this.treeOutline.comparator); else
        insertionIndex = this.children.length;
    this.insertChild(child, insertionIndex);
}
TreeOutline.prototype.insertBeforeChild = function (child, beforeChild) {
    if (!child)
        throw("child can't be undefined or null");
    if (!beforeChild)
        throw("beforeChild can't be undefined or null");
    var childIndex = this.children.indexOf(beforeChild);
    if (childIndex === -1)
        throw("beforeChild not found in this node's children");
    this.insertChild(child, childIndex);
}
TreeOutline.prototype.insertChild = function (child, index) {
    if (!child)
        throw("child can't be undefined or null");
    var previousChild = (index > 0 ? this.children[index - 1] : null);
    if (previousChild) {
        previousChild.nextSibling = child;
        child.previousSibling = previousChild;
    } else {
        child.previousSibling = null;
    }
    var nextChild = this.children[index];
    if (nextChild) {
        nextChild.previousSibling = child;
        child.nextSibling = nextChild;
    } else {
        child.nextSibling = null;
    }
    this.children.splice(index, 0, child);
    this.hasChildren = true;
    child.parent = this;
    child.treeOutline = this.treeOutline;
    child.treeOutline._rememberTreeElement(child);
    var current = child.children[0];
    while (current) {
        current.treeOutline = this.treeOutline;
        current.treeOutline._rememberTreeElement(current);
        current = current.traverseNextTreeElement(false, child, true);
    }
    if (child.hasChildren && typeof(child.treeOutline._expandedStateMap.get(child.representedObject)) !== "undefined")
        child.expanded = child.treeOutline._expandedStateMap.get(child.representedObject);
    if (!this._childrenListNode) {
        this._childrenListNode = this.treeOutline._childrenListNode.ownerDocument.createElement("ol");
        this._childrenListNode.parentTreeElement = this;
        this._childrenListNode.classList.add("children");
        if (this.hidden)
            this._childrenListNode.classList.add("hidden");
    }
    child._attach();
}
TreeOutline.prototype.removeChildAtIndex = function (childIndex) {
    if (childIndex < 0 || childIndex >= this.children.length)
        throw("childIndex out of range");
    var child = this.children[childIndex];
    this.children.splice(childIndex, 1);
    var parent = child.parent;
    if (child.deselect()) {
        if (child.previousSibling)
            child.previousSibling.select(); else if (child.nextSibling)
            child.nextSibling.select(); else
            parent.select();
    }
    if (child.previousSibling)
        child.previousSibling.nextSibling = child.nextSibling;
    if (child.nextSibling)
        child.nextSibling.previousSibling = child.previousSibling;
    if (child.treeOutline) {
        child.treeOutline._forgetTreeElement(child);
        child.treeOutline._forgetChildrenRecursive(child);
    }
    child._detach();
    child.treeOutline = null;
    child.parent = null;
    child.nextSibling = null;
    child.previousSibling = null;
}
TreeOutline.prototype.removeChild = function (child) {
    if (!child)
        throw("child can't be undefined or null");
    var childIndex = this.children.indexOf(child);
    if (childIndex === -1)
        throw("child not found in this node's children");
    this.removeChildAtIndex.call(this, childIndex);
}
TreeOutline.prototype.removeChildren = function () {
    for (var i = 0; i < this.children.length; ++i) {
        var child = this.children[i];
        child.deselect();
        if (child.treeOutline) {
            child.treeOutline._forgetTreeElement(child);
            child.treeOutline._forgetChildrenRecursive(child);
        }
        child._detach();
        child.treeOutline = null;
        child.parent = null;
        child.nextSibling = null;
        child.previousSibling = null;
    }
    this.children = [];
}
TreeOutline.prototype._rememberTreeElement = function (element) {
    if (!this._treeElementsMap.get(element.representedObject))
        this._treeElementsMap.put(element.representedObject, []);
    var elements = this._treeElementsMap.get(element.representedObject);
    if (elements.indexOf(element) !== -1)
        return;
    elements.push(element);
}
TreeOutline.prototype._forgetTreeElement = function (element) {
    if (this._treeElementsMap.get(element.representedObject)) {
        var elements = this._treeElementsMap.get(element.representedObject);
        elements.remove(element, true);
        if (!elements.length)
            this._treeElementsMap.remove(element.representedObject);
    }
}
TreeOutline.prototype._forgetChildrenRecursive = function (parentElement) {
    var child = parentElement.children[0];
    while (child) {
        this._forgetTreeElement(child);
        child = child.traverseNextTreeElement(false, parentElement, true);
    }
}
TreeOutline.prototype.getCachedTreeElement = function (representedObject) {
    if (!representedObject)
        return null;
    var elements = this._treeElementsMap.get(representedObject);
    if (elements && elements.length)
        return elements[0];
    return null;
}
TreeOutline.prototype.findTreeElement = function (representedObject, getParent) {
    if (!representedObject)
        return null;
    var cachedElement = this.getCachedTreeElement(representedObject);
    if (cachedElement)
        return cachedElement;
    var ancestors = [];
    for (var currentObject = getParent(representedObject); currentObject; currentObject = getParent(currentObject)) {
        ancestors.push(currentObject);
        if (this.getCachedTreeElement(currentObject))
            break;
    }
    if (!currentObject)
        return null;
    for (var i = ancestors.length - 1; i >= 0; --i) {
        var treeElement = this.getCachedTreeElement(ancestors[i]);
        if (treeElement)
            treeElement.onpopulate();
    }
    return this.getCachedTreeElement(representedObject);
}
TreeOutline.prototype.treeElementFromPoint = function (x, y) {
    var node = this._childrenListNode.ownerDocument.elementFromPoint(x, y);
    if (!node)
        return null;
    var listNode = node.enclosingNodeOrSelfWithNodeNameInArray(["ol", "li"]);
    if (listNode)
        return listNode.parentTreeElement || listNode.treeElement;
    return null;
}
TreeOutline.prototype._treeKeyDown = function (event) {
    if (event.target !== this._childrenListNode)
        return;
    if (!this.selectedTreeElement || event.shiftKey || event.metaKey || event.ctrlKey)
        return;
    var handled = false;
    var nextSelectedElement;
    if (event.keyIdentifier === "Up" && !event.altKey) {
        nextSelectedElement = this.selectedTreeElement.traversePreviousTreeElement(true);
        while (nextSelectedElement && !nextSelectedElement.selectable)
            nextSelectedElement = nextSelectedElement.traversePreviousTreeElement(!this.expandTreeElementsWhenArrowing);
        handled = nextSelectedElement ? true : false;
    } else if (event.keyIdentifier === "Down" && !event.altKey) {
        nextSelectedElement = this.selectedTreeElement.traverseNextTreeElement(true);
        while (nextSelectedElement && !nextSelectedElement.selectable)
            nextSelectedElement = nextSelectedElement.traverseNextTreeElement(!this.expandTreeElementsWhenArrowing);
        handled = nextSelectedElement ? true : false;
    } else if (event.keyIdentifier === "Left") {
        if (this.selectedTreeElement.expanded) {
            if (event.altKey)
                this.selectedTreeElement.collapseRecursively(); else
                this.selectedTreeElement.collapse();
            handled = true;
        } else if (this.selectedTreeElement.parent && !this.selectedTreeElement.parent.root) {
            handled = true;
            if (this.selectedTreeElement.parent.selectable) {
                nextSelectedElement = this.selectedTreeElement.parent;
                while (nextSelectedElement && !nextSelectedElement.selectable)
                    nextSelectedElement = nextSelectedElement.parent;
                handled = nextSelectedElement ? true : false;
            } else if (this.selectedTreeElement.parent)
                this.selectedTreeElement.parent.collapse();
        }
    } else if (event.keyIdentifier === "Right") {
        if (!this.selectedTreeElement.revealed()) {
            this.selectedTreeElement.reveal();
            handled = true;
        } else if (this.selectedTreeElement.hasChildren) {
            handled = true;
            if (this.selectedTreeElement.expanded) {
                nextSelectedElement = this.selectedTreeElement.children[0];
                while (nextSelectedElement && !nextSelectedElement.selectable)
                    nextSelectedElement = nextSelectedElement.nextSibling;
                handled = nextSelectedElement ? true : false;
            } else {
                if (event.altKey)
                    this.selectedTreeElement.expandRecursively(); else
                    this.selectedTreeElement.expand();
            }
        }
    } else if (event.keyCode === 8 || event.keyCode === 46)
        handled = this.selectedTreeElement.ondelete(); else if (isEnterKey(event))
        handled = this.selectedTreeElement.onenter(); else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Space.code)
        handled = this.selectedTreeElement.onspace();
    if (nextSelectedElement) {
        nextSelectedElement.reveal();
        nextSelectedElement.select(false, true);
    }
    if (handled)
        event.consume(true);
}
TreeOutline.prototype.expand = function () {
}
TreeOutline.prototype.collapse = function () {
}
TreeOutline.prototype.revealed = function () {
    return true;
}
TreeOutline.prototype.reveal = function () {
}
TreeOutline.prototype.select = function () {
}
TreeOutline.prototype.revealAndSelect = function (omitFocus) {
}
function TreeElement(title, representedObject, hasChildren) {
    this._title = title;
    this.representedObject = (representedObject || {});
    this.root = false;
    this._hidden = false;
    this._selectable = true;
    this.expanded = false;
    this.selected = false;
    this.hasChildren = hasChildren;
    this.children = [];
    this.treeOutline = null;
    this.parent = null;
    this.previousSibling = null;
    this.nextSibling = null;
    this._listItemNode = null;
}
TreeElement.prototype = {
    arrowToggleWidth: 10, get selectable() {
        if (this._hidden)
            return false;
        return this._selectable;
    }, set selectable(x) {
        this._selectable = x;
    }, get listItemElement() {
        return this._listItemNode;
    }, get childrenListElement() {
        return this._childrenListNode;
    }, get title() {
        return this._title;
    }, set title(x) {
        this._title = x;
        this._setListItemNodeContent();
    }, get tooltip() {
        return this._tooltip;
    }, set tooltip(x) {
        this._tooltip = x;
        if (this._listItemNode)
            this._listItemNode.title = x ? x : "";
    }, get hasChildren() {
        return this._hasChildren;
    }, set hasChildren(x) {
        if (this._hasChildren === x)
            return;
        this._hasChildren = x;
        if (!this._listItemNode)
            return;
        if (x)
            this._listItemNode.classList.add("parent"); else {
            this._listItemNode.classList.remove("parent");
            this.collapse();
        }
    }, get hidden() {
        return this._hidden;
    }, set hidden(x) {
        if (this._hidden === x)
            return;
        this._hidden = x;
        if (x) {
            if (this._listItemNode)
                this._listItemNode.classList.add("hidden");
            if (this._childrenListNode)
                this._childrenListNode.classList.add("hidden");
        } else {
            if (this._listItemNode)
                this._listItemNode.classList.remove("hidden");
            if (this._childrenListNode)
                this._childrenListNode.classList.remove("hidden");
        }
    }, get shouldRefreshChildren() {
        return this._shouldRefreshChildren;
    }, set shouldRefreshChildren(x) {
        this._shouldRefreshChildren = x;
        if (x && this.expanded)
            this.expand();
    }, _setListItemNodeContent: function () {
        if (!this._listItemNode)
            return;
        if (typeof this._title === "string")
            this._listItemNode.textContent = this._title; else {
            this._listItemNode.removeChildren();
            if (this._title)
                this._listItemNode.appendChild(this._title);
        }
    }
}
TreeElement.prototype.appendChild = TreeOutline.prototype.appendChild;
TreeElement.prototype.insertChild = TreeOutline.prototype.insertChild;
TreeElement.prototype.insertBeforeChild = TreeOutline.prototype.insertBeforeChild;
TreeElement.prototype.removeChild = TreeOutline.prototype.removeChild;
TreeElement.prototype.removeChildAtIndex = TreeOutline.prototype.removeChildAtIndex;
TreeElement.prototype.removeChildren = TreeOutline.prototype.removeChildren;
TreeElement.prototype._attach = function () {
    if (!this._listItemNode || this.parent._shouldRefreshChildren) {
        if (this._listItemNode && this._listItemNode.parentNode)
            this._listItemNode.parentNode.removeChild(this._listItemNode);
        this._listItemNode = this.treeOutline._childrenListNode.ownerDocument.createElement("li");
        this._listItemNode.treeElement = this;
        this._setListItemNodeContent();
        this._listItemNode.title = this._tooltip ? this._tooltip : "";
        if (this.hidden)
            this._listItemNode.classList.add("hidden");
        if (this.hasChildren)
            this._listItemNode.classList.add("parent");
        if (this.expanded)
            this._listItemNode.classList.add("expanded");
        if (this.selected)
            this._listItemNode.classList.add("selected");
        this._listItemNode.addEventListener("mousedown", TreeElement.treeElementMouseDown, false);
        this._listItemNode.addEventListener("selectstart", TreeElement.treeElementSelectStart, false);
        this._listItemNode.addEventListener("click", TreeElement.treeElementToggled, false);
        this._listItemNode.addEventListener("dblclick", TreeElement.treeElementDoubleClicked, false);
        this.onattach();
    }
    var nextSibling = null;
    if (this.nextSibling && this.nextSibling._listItemNode && this.nextSibling._listItemNode.parentNode === this.parent._childrenListNode)
        nextSibling = this.nextSibling._listItemNode;
    this.parent._childrenListNode.insertBefore(this._listItemNode, nextSibling);
    if (this._childrenListNode)
        this.parent._childrenListNode.insertBefore(this._childrenListNode, this._listItemNode.nextSibling);
    if (this.selected)
        this.select();
    if (this.expanded)
        this.expand();
}
TreeElement.prototype._detach = function () {
    if (this._listItemNode && this._listItemNode.parentNode)
        this._listItemNode.parentNode.removeChild(this._listItemNode);
    if (this._childrenListNode && this._childrenListNode.parentNode)
        this._childrenListNode.parentNode.removeChild(this._childrenListNode);
}
TreeElement.treeElementMouseDown = function (event) {
    var element = event.currentTarget;
    if (!element)
        return;
    delete element._selectionStarted;
    if (!element.treeElement || !element.treeElement.selectable)
        return;
    if (element.treeElement.isEventWithinDisclosureTriangle(event))
        return;
    element.treeElement.selectOnMouseDown(event);
}
TreeElement.treeElementSelectStart = function (event) {
    var element = event.currentTarget;
    if (!element)
        return;
    element._selectionStarted = true;
}
TreeElement.treeElementToggled = function (event) {
    var element = event.currentTarget;
    if (!element)
        return;
    if (element._selectionStarted) {
        delete element._selectionStarted
        var selection = window.getSelection();
        if (selection && !selection.isCollapsed && element.isSelfOrAncestor(selection.anchorNode) && element.isSelfOrAncestor(selection.focusNode))
            return;
    }
    if (!element.treeElement)
        return;
    var toggleOnClick = element.treeElement.toggleOnClick && !element.treeElement.selectable;
    var isInTriangle = element.treeElement.isEventWithinDisclosureTriangle(event);
    if (!toggleOnClick && !isInTriangle)
        return;
    if (event.target && event.target.enclosingNodeOrSelfWithNodeName("a"))
        return;
    if (element.treeElement.expanded) {
        if (event.altKey)
            element.treeElement.collapseRecursively(); else
            element.treeElement.collapse();
    } else {
        if (event.altKey)
            element.treeElement.expandRecursively(); else
            element.treeElement.expand();
    }
    event.consume();
}
TreeElement.treeElementDoubleClicked = function (event) {
    var element = event.currentTarget;
    if (!element || !element.treeElement)
        return;
    var handled = element.treeElement.ondblclick.call(element.treeElement, event);
    if (handled)
        return;
    if (element.treeElement.hasChildren && !element.treeElement.expanded)
        element.treeElement.expand();
}
TreeElement.prototype.collapse = function () {
    if (this._listItemNode)
        this._listItemNode.classList.remove("expanded");
    if (this._childrenListNode)
        this._childrenListNode.classList.remove("expanded");
    this.expanded = false;
    if (this.treeOutline)
        this.treeOutline._expandedStateMap.put(this.representedObject, false);
    this.oncollapse();
}
TreeElement.prototype.collapseRecursively = function () {
    var item = this;
    while (item) {
        if (item.expanded)
            item.collapse();
        item = item.traverseNextTreeElement(false, this, true);
    }
}
TreeElement.prototype.expand = function () {
    if (!this.hasChildren || (this.expanded && !this._shouldRefreshChildren && this._childrenListNode))
        return;
    this.expanded = true;
    if (this.treeOutline)
        this.treeOutline._expandedStateMap.put(this.representedObject, true);
    if (this.treeOutline && (!this._childrenListNode || this._shouldRefreshChildren)) {
        if (this._childrenListNode && this._childrenListNode.parentNode)
            this._childrenListNode.parentNode.removeChild(this._childrenListNode);
        this._childrenListNode = this.treeOutline._childrenListNode.ownerDocument.createElement("ol");
        this._childrenListNode.parentTreeElement = this;
        this._childrenListNode.classList.add("children");
        if (this.hidden)
            this._childrenListNode.classList.add("hidden");
        this.onpopulate();
        for (var i = 0; i < this.children.length; ++i)
            this.children[i]._attach();
        delete this._shouldRefreshChildren;
    }
    if (this._listItemNode) {
        this._listItemNode.classList.add("expanded");
        if (this._childrenListNode && this._childrenListNode.parentNode != this._listItemNode.parentNode)
            this.parent._childrenListNode.insertBefore(this._childrenListNode, this._listItemNode.nextSibling);
    }
    if (this._childrenListNode)
        this._childrenListNode.classList.add("expanded");
    this.onexpand();
}
TreeElement.prototype.expandRecursively = function (maxDepth) {
    var item = this;
    var info = {};
    var depth = 0;
    if (isNaN(maxDepth))
        maxDepth = 3;
    while (item) {
        if (depth < maxDepth)
            item.expand();
        item = item.traverseNextTreeElement(false, this, (depth >= maxDepth), info);
        depth += info.depthChange;
    }
}
TreeElement.prototype.hasAncestor = function (ancestor) {
    if (!ancestor)
        return false;
    var currentNode = this.parent;
    while (currentNode) {
        if (ancestor === currentNode)
            return true;
        currentNode = currentNode.parent;
    }
    return false;
}
TreeElement.prototype.reveal = function () {
    var currentAncestor = this.parent;
    while (currentAncestor && !currentAncestor.root) {
        if (!currentAncestor.expanded)
            currentAncestor.expand();
        currentAncestor = currentAncestor.parent;
    }
    this.onreveal();
}
TreeElement.prototype.revealed = function () {
    var currentAncestor = this.parent;
    while (currentAncestor && !currentAncestor.root) {
        if (!currentAncestor.expanded)
            return false;
        currentAncestor = currentAncestor.parent;
    }
    return true;
}
TreeElement.prototype.selectOnMouseDown = function (event) {
    if (this.select(false, true))
        event.consume(true);
}
TreeElement.prototype.select = function (omitFocus, selectedByUser) {
    if (!this.treeOutline || !this.selectable || this.selected)
        return false;
    if (this.treeOutline.selectedTreeElement)
        this.treeOutline.selectedTreeElement.deselect();
    this.selected = true;
    if (!omitFocus)
        this.treeOutline._childrenListNode.focus();
    if (!this.treeOutline)
        return false;
    this.treeOutline.selectedTreeElement = this;
    if (this._listItemNode)
        this._listItemNode.classList.add("selected");
    return this.onselect(selectedByUser);
}
TreeElement.prototype.revealAndSelect = function (omitFocus) {
    this.reveal();
    this.select(omitFocus);
}
TreeElement.prototype.deselect = function (supressOnDeselect) {
    if (!this.treeOutline || this.treeOutline.selectedTreeElement !== this || !this.selected)
        return false;
    this.selected = false;
    this.treeOutline.selectedTreeElement = null;
    if (this._listItemNode)
        this._listItemNode.classList.remove("selected");
    return true;
}
TreeElement.prototype.onpopulate = function () {
}
TreeElement.prototype.onenter = function () {
    return false;
}
TreeElement.prototype.ondelete = function () {
    return false;
}
TreeElement.prototype.onspace = function () {
    return false;
}
TreeElement.prototype.onattach = function () {
}
TreeElement.prototype.onexpand = function () {
}
TreeElement.prototype.oncollapse = function () {
}
TreeElement.prototype.ondblclick = function (e) {
    return false;
}
TreeElement.prototype.onreveal = function () {
}
TreeElement.prototype.onselect = function (selectedByUser) {
    return false;
}
TreeElement.prototype.traverseNextTreeElement = function (skipUnrevealed, stayWithin, dontPopulate, info) {
    if (!dontPopulate && this.hasChildren)
        this.onpopulate();
    if (info)
        info.depthChange = 0;
    var element = skipUnrevealed ? (this.revealed() ? this.children[0] : null) : this.children[0];
    if (element && (!skipUnrevealed || (skipUnrevealed && this.expanded))) {
        if (info)
            info.depthChange = 1;
        return element;
    }
    if (this === stayWithin)
        return null;
    element = skipUnrevealed ? (this.revealed() ? this.nextSibling : null) : this.nextSibling;
    if (element)
        return element;
    element = this;
    while (element && !element.root && !(skipUnrevealed ? (element.revealed() ? element.nextSibling : null) : element.nextSibling) && element.parent !== stayWithin) {
        if (info)
            info.depthChange -= 1;
        element = element.parent;
    }
    if (!element)
        return null;
    return (skipUnrevealed ? (element.revealed() ? element.nextSibling : null) : element.nextSibling);
}
TreeElement.prototype.traversePreviousTreeElement = function (skipUnrevealed, dontPopulate) {
    var element = skipUnrevealed ? (this.revealed() ? this.previousSibling : null) : this.previousSibling;
    if (!dontPopulate && element && element.hasChildren)
        element.onpopulate();
    while (element && (skipUnrevealed ? (element.revealed() && element.expanded ? element.children[element.children.length - 1] : null) : element.children[element.children.length - 1])) {
        if (!dontPopulate && element.hasChildren)
            element.onpopulate();
        element = (skipUnrevealed ? (element.revealed() && element.expanded ? element.children[element.children.length - 1] : null) : element.children[element.children.length - 1]);
    }
    if (element)
        return element;
    if (!this.parent || this.parent.root)
        return null;
    return this.parent;
}
TreeElement.prototype.isEventWithinDisclosureTriangle = function (event) {
    var paddingLeftValue = window.getComputedStyle(this._listItemNode).getPropertyCSSValue("padding-left");
    var computedLeftPadding = paddingLeftValue ? paddingLeftValue.getFloatValue(CSSPrimitiveValue.CSS_PX) : 0;
    var left = this._listItemNode.totalOffsetLeft() + computedLeftPadding;
    return event.pageX >= left && event.pageX <= left + this.arrowToggleWidth && this.hasChildren;
}
WebInspector.SettingsUI = {}
WebInspector.SettingsUI.createSettingCheckbox = function (name, setting, omitParagraphElement, inputElement, tooltip) {
    var input = inputElement || document.createElement("input");
    input.type = "checkbox";
    input.name = name;
    WebInspector.SettingsUI.bindCheckbox(input, setting);
    var label = document.createElement("label");
    label.appendChild(input);
    label.createTextChild(name);
    if (tooltip)
        label.title = tooltip;
    if (omitParagraphElement)
        return label;
    var p = document.createElement("p");
    p.appendChild(label);
    return p;
}
WebInspector.SettingsUI.bindCheckbox = function (input, setting) {
    function settingChanged() {
        if (input.checked !== setting.get())
            input.checked = setting.get();
    }

    setting.addChangeListener(settingChanged);
    settingChanged();
    function inputChanged() {
        if (setting.get() !== input.checked)
            setting.set(input.checked);
    }

    input.addEventListener("change", inputChanged, false);
}
WebInspector.SettingsUI.createSettingInputField = function (label, setting, numeric, maxLength, width, validatorCallback, instant, clearForZero, placeholder) {
    var p = document.createElement("p");
    var labelElement = p.createChild("label");
    labelElement.textContent = label;
    var inputElement = p.createChild("input");
    inputElement.type = "text";
    if (numeric)
        inputElement.className = "numeric";
    if (maxLength)
        inputElement.maxLength = maxLength;
    if (width)
        inputElement.style.width = width;
    inputElement.placeholder = placeholder || "";
    if (validatorCallback || instant) {
        inputElement.addEventListener("change", onInput, false);
        inputElement.addEventListener("input", onInput, false);
    }
    inputElement.addEventListener("keydown", onKeyDown, false);
    var errorMessageLabel;
    if (validatorCallback)
        errorMessageLabel = p.createChild("div", "field-error-message");
    function onInput() {
        if (validatorCallback)
            validate();
        if (instant)
            apply();
    }

    function onKeyDown(event) {
        if (isEnterKey(event))
            apply();
        incrementForArrows(event);
    }

    function incrementForArrows(event) {
        if (!numeric)
            return;
        var increment = event.keyIdentifier === "Up" ? 1 : event.keyIdentifier === "Down" ? -1 : 0;
        if (!increment)
            return;
        if (event.shiftKey)
            increment *= 10;
        var value = inputElement.value;
        if (validatorCallback && validatorCallback(value))
            return;
        value = Number(value);
        if (clearForZero && !value)
            return;
        value += increment;
        if (clearForZero && !value)
            return;
        value = String(value);
        if (validatorCallback && validatorCallback(value))
            return;
        inputElement.value = value;
        apply();
        event.preventDefault();
    }

    function validate() {
        var error = validatorCallback(inputElement.value);
        if (!error)
            error = "";
        inputElement.classList.toggle("error-input", !!error);
        errorMessageLabel.textContent = error;
    }

    if (!instant)
        inputElement.addEventListener("blur", apply, false);
    function apply() {
        if (validatorCallback && validatorCallback(inputElement.value))
            return;
        setting.removeChangeListener(onSettingChange);
        setting.set(numeric ? Number(inputElement.value) : inputElement.value);
        setting.addChangeListener(onSettingChange);
    }

    setting.addChangeListener(onSettingChange);
    function onSettingChange() {
        var value = setting.get();
        if (clearForZero && !value)
            value = "";
        inputElement.value = value;
    }

    onSettingChange();
    if (validatorCallback)
        validate();
    return p;
}
WebInspector.SettingsUI.createCustomSetting = function (name, element) {
    var p = document.createElement("p");
    var fieldsetElement = p.createChild("fieldset");
    fieldsetElement.createChild("label").textContent = name;
    fieldsetElement.appendChild(element);
    return p;
}
WebInspector.SettingsUI.createSettingFieldset = function (setting) {
    var fieldset = document.createElement("fieldset");
    fieldset.disabled = !setting.get();
    setting.addChangeListener(settingChanged);
    return fieldset;
    function settingChanged() {
        fieldset.disabled = !setting.get();
    }
}
WebInspector.SettingsUI.regexValidator = function (text) {
    var regex;
    try {
        regex = new RegExp(text);
    } catch (e) {
    }
    return regex ? null : WebInspector.UIString("Invalid pattern");
}
WebInspector.SettingsUI.createInput = function (parentElement, id, defaultText, eventListener, numeric, size) {
    var element = parentElement.createChild("input");
    element.id = id;
    element.type = "text";
    element.maxLength = 12;
    element.style.width = size || "80px";
    element.value = defaultText;
    element.align = "right";
    if (numeric)
        element.className = "numeric";
    element.addEventListener("input", eventListener, false);
    element.addEventListener("keydown", keyDownListener, false);
    function keyDownListener(event) {
        if (isEnterKey(event))
            eventListener(event);
    }

    return element;
}
WebInspector.UISettingDelegate = function () {
}
WebInspector.UISettingDelegate.prototype = {
    settingElement: function () {
        return null;
    }
}
function windowLoaded() {
    window.removeEventListener("DOMContentLoaded", windowLoaded, false);
    new WebInspector.Toolbox();
}
window.addEventListener("DOMContentLoaded", windowLoaded, false);
WebInspector.Toolbox = function () {
    if (!window.opener)
        return;
    WebInspector.zoomManager = new WebInspector.ZoomManager(window.opener.InspectorFrontendHost);
    WebInspector.overridesSupport = window.opener.WebInspector.overridesSupport;
    WebInspector.settings = window.opener.WebInspector.settings;
    WebInspector.experimentsSettings = window.opener.WebInspector.experimentsSettings;
    WebInspector.targetManager = window.opener.WebInspector.targetManager;
    WebInspector.workspace = window.opener.WebInspector.workspace;
    WebInspector.cssWorkspaceBinding = window.opener.WebInspector.cssWorkspaceBinding;
    WebInspector.Revealer = window.opener.WebInspector.Revealer;
    WebInspector.ContextMenu = window.opener.WebInspector.ContextMenu;
    WebInspector.installPortStyles();
    var delegate = (window.opener.WebInspector["app"]);
    var rootView = new WebInspector.RootView();
    var inspectedPagePlaceholder = new WebInspector.InspectedPagePlaceholder();
    this._responsiveDesignView = new WebInspector.ResponsiveDesignView(inspectedPagePlaceholder);
    this._responsiveDesignView.show(rootView.element);
    rootView.attachToBody();
    delegate.toolboxLoaded(this._responsiveDesignView, inspectedPagePlaceholder);
}
WebInspector.Main = function () {
    var boundListener = windowLoaded.bind(this);

    function windowLoaded() {
        this._loaded();
        window.removeEventListener("DOMContentLoaded", boundListener, false);
    }

    window.addEventListener("DOMContentLoaded", boundListener, false);
}
WebInspector.Main.prototype = {
    _createGlobalStatusBarItems: function () {
        var extensions = self.runtime.extensions(WebInspector.StatusBarItem.Provider);

        function orderComparator(left, right) {
            return left.descriptor()["order"] - right.descriptor()["order"];
        }

        extensions.sort(orderComparator);
        extensions.forEach(function (extension) {
            var item;
            switch (extension.descriptor()["location"]) {
                case"toolbar-left":
                    item = createItem(extension);
                    if (item)
                        WebInspector.inspectorView.appendToLeftToolbar(item);
                    break;
                case"toolbar-right":
                    item = createItem(extension);
                    if (item)
                        WebInspector.inspectorView.appendToRightToolbar(item);
                    break;
            }
            if (item && extension.descriptor()["actionId"]) {
                item.addEventListener("click", function () {
                    WebInspector.actionRegistry.execute(extension.descriptor()["actionId"]);
                });
            }
        });
        function createItem(extension) {
            var descriptor = extension.descriptor();
            if (descriptor.className)
                return extension.instance().item();
            return new WebInspector.StatusBarButton(WebInspector.UIString(descriptor["title"]), descriptor["elementClass"]);
        }
    }, _calculateWorkerInspectorTitle: function () {
        var expression = "location.href";
        if (WebInspector.queryParam("isSharedWorker"))
            expression += " + (this.name ? ' (' + this.name + ')' : '')";
        RuntimeAgent.invoke_evaluate({expression: expression, doNotPauseOnExceptionsAndMuteConsole: true, returnByValue: true}, evalCallback);
        function evalCallback(error, result, wasThrown) {
            if (error || wasThrown) {
                console.error(error);
                return;
            }
            InspectorFrontendHost.inspectedURLChanged(String(result.value));
        }
    }, _loadCompletedForWorkers: function () {
        if (WebInspector.queryParam("workerPaused")) {
            pauseAndResume.call(this);
        } else {
            RuntimeAgent.isRunRequired(isRunRequiredCallback.bind(this));
        }
        function isRunRequiredCallback(error, result) {
            if (result) {
                pauseAndResume.call(this);
            } else if (WebInspector.isWorkerFrontend()) {
                calculateTitle.call(this);
            }
        }

        function pauseAndResume() {
            DebuggerAgent.pause();
            RuntimeAgent.run(calculateTitle.bind(this));
        }

        function calculateTitle() {
            this._calculateWorkerInspectorTitle();
        }
    }, _loaded: function () {
        console.timeStamp("Main._loaded");
        if (WebInspector.queryParam("toolbox")) {
            new WebInspector.Toolbox();
            return;
        }
        document.devtoolsMode = 'on';
        this._createSettings();
        this._createModuleManager();
        this._createAppUI();
    }, _createSettings: function () {
        WebInspector.settings = new WebInspector.Settings();
        WebInspector.experimentsSettings = new WebInspector.ExperimentsSettings(WebInspector.queryParam("experiments") !== null);
        WebInspector.settings.pauseOnExceptionStateString = new WebInspector.PauseOnExceptionStateSetting();
        new WebInspector.VersionController().updateVersion();
    }, _createModuleManager: function () {
        console.timeStamp("Main._createModuleManager");
        self.runtime = new Runtime(allDescriptors);
        var configuration = ["main", "elements", "network", "sources", "timeline", "profiler", "resources", "audits", "console", "source_frame", "extensions", "settings"];
        if (WebInspector.experimentsSettings.layersPanel.isEnabled())
            configuration.push("layers");
        if (WebInspector.experimentsSettings.devicesPanel.isEnabled() && !!WebInspector.queryParam("can_dock"))
            configuration.push("devices");
        if (WebInspector.experimentsSettings.documentation.isEnabled())
            configuration.push("documentation");
        if (WebInspector.isWorkerFrontend())
            configuration = ["main", "sources", "timeline", "profiler", "console", "source_frame", "extensions"];
        self.runtime.registerModules(configuration);
    }, _createAppUI: function () {
        console.timeStamp("Main._createApp");
        WebInspector.installPortStyles();
        if (WebInspector.queryParam("toolbarColor") && WebInspector.queryParam("textColor"))
            WebInspector.setToolbarColors(WebInspector.queryParam("toolbarColor"), WebInspector.queryParam("textColor"));
        InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetToolbarColors, updateToolbarColors);
        function updateToolbarColors(event) {
            WebInspector.setToolbarColors((event.data["backgroundColor"]), (event.data["color"]));
        }

        var canDock = !!WebInspector.queryParam("can_dock");
        WebInspector.zoomManager = new WebInspector.ZoomManager(InspectorFrontendHost);
        WebInspector.inspectorView = new WebInspector.InspectorView();
        WebInspector.ContextMenu.initialize();
        WebInspector.dockController = new WebInspector.DockController(canDock);
        WebInspector.overridesSupport = new WebInspector.OverridesSupport(canDock);
        WebInspector.multitargetConsoleModel = new WebInspector.MultitargetConsoleModel();
        WebInspector.shortcutsScreen = new WebInspector.ShortcutsScreen();
        WebInspector.shortcutsScreen.section(WebInspector.UIString("Console"));
        WebInspector.shortcutsScreen.section(WebInspector.UIString("Elements Panel"));
        if (canDock)
            WebInspector.app = new WebInspector.AdvancedApp(); else if (WebInspector.queryParam("remoteFrontend"))
            WebInspector.app = new WebInspector.ScreencastApp(); else
            WebInspector.app = new WebInspector.SimpleApp();
        WebInspector.dockController.initialize();
        WebInspector.app.createRootView();
        setTimeout(this._createConnection.bind(this), 0);
    }, _createConnection: function () {
        console.timeStamp("Main._createConnection");
        InspectorBackend.loadFromJSONIfNeeded("../protocol.json");
        var workerId = WebInspector.queryParam("dedicatedWorkerId");
        if (workerId) {
            this._connectionEstablished(new WebInspector.ExternalWorkerConnection(workerId));
            return;
        }
        if (WebInspector.queryParam("ws")) {
            var ws = "ws://" + WebInspector.queryParam("ws");
            InspectorBackendClass.WebSocketConnection.Create(ws, this._connectionEstablished.bind(this));
            return;
        }
        if (!InspectorFrontendHost.isHostedMode()) {
            this._connectionEstablished(new InspectorBackendClass.MainConnection());
            return;
        }
        this._connectionEstablished(new InspectorBackendClass.StubConnection());
    }, _connectionEstablished: function (connection) {
        console.timeStamp("Main._connectionEstablished");
        connection.addEventListener(InspectorBackendClass.Connection.Events.Disconnected, onDisconnected);
        function onDisconnected(event) {
            if (WebInspector._disconnectedScreenWithReasonWasShown)
                return;
            new WebInspector.RemoteDebuggingTerminatedScreen(event.data.reason).showModal();
        }

        InspectorBackend.setConnection(connection);
        WebInspector.installPortStyles();
        if (WebInspector.queryParam("toolbarColor") && WebInspector.queryParam("textColor"))
            WebInspector.setToolbarColors(WebInspector.queryParam("toolbarColor"), WebInspector.queryParam("textColor"));
        InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetToolbarColors, updateToolbarColors);
        function updateToolbarColors(event) {
            WebInspector.setToolbarColors((event.data["backgroundColor"]), (event.data["color"]));
        }

        WebInspector.ContextMenu.initialize();
        WebInspector.targetManager.createTarget(WebInspector.UIString("Main"), connection, this._mainTargetCreated.bind(this));
        WebInspector.isolatedFileSystemManager = new WebInspector.IsolatedFileSystemManager();
        WebInspector.workspace = new WebInspector.Workspace(WebInspector.isolatedFileSystemManager.mapping());
        WebInspector.networkWorkspaceBinding = new WebInspector.NetworkWorkspaceBinding(WebInspector.workspace);
        new WebInspector.NetworkUISourceCodeProvider(WebInspector.networkWorkspaceBinding, WebInspector.workspace);
        new WebInspector.PresentationConsoleMessageHelper(WebInspector.workspace);
        WebInspector.cssWorkspaceBinding = new WebInspector.CSSWorkspaceBinding();
        WebInspector.debuggerWorkspaceBinding = new WebInspector.DebuggerWorkspaceBinding(WebInspector.targetManager, WebInspector.workspace, WebInspector.networkWorkspaceBinding);
        WebInspector.fileSystemWorkspaceBinding = new WebInspector.FileSystemWorkspaceBinding(WebInspector.isolatedFileSystemManager, WebInspector.workspace);
        WebInspector.breakpointManager = new WebInspector.BreakpointManager(WebInspector.settings.breakpoints, WebInspector.workspace, WebInspector.targetManager, WebInspector.debuggerWorkspaceBinding);
        WebInspector.scriptSnippetModel = new WebInspector.ScriptSnippetModel(WebInspector.workspace);
        this._executionContextSelector = new WebInspector.ExecutionContextSelector();
        if (!WebInspector.isWorkerFrontend())
            WebInspector.inspectElementModeController = new WebInspector.InspectElementModeController();
        this._createGlobalStatusBarItems();
    }, _mainTargetCreated: function (mainTarget) {
        console.timeStamp("Main._mainTargetCreated");
        this._registerShortcuts();
        WebInspector.workerTargetManager = new WebInspector.WorkerTargetManager(mainTarget, WebInspector.targetManager);
        InspectorBackend.registerInspectorDispatcher(this);
        if (WebInspector.isWorkerFrontend())
            mainTarget.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerDisconnected, onWorkerDisconnected);
        function onWorkerDisconnected() {
            var screen = new WebInspector.WorkerTerminatedScreen();
            var listener = hideScreen.bind(null, screen);
            mainTarget.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, listener);
            function hideScreen(screen) {
                mainTarget.debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, listener);
                screen.hide();
            }

            screen.showModal();
        }

        WebInspector.domBreakpointsSidebarPane = new WebInspector.DOMBreakpointsSidebarPane();
        var autoselectPanel = WebInspector.UIString("a panel chosen automatically");
        var openAnchorLocationSetting = WebInspector.settings.createSetting("openLinkHandler", autoselectPanel);
        WebInspector.openAnchorLocationRegistry = new WebInspector.HandlerRegistry(openAnchorLocationSetting);
        WebInspector.openAnchorLocationRegistry.registerHandler(autoselectPanel, function () {
            return false;
        });
        WebInspector.Linkifier.setLinkHandler(new WebInspector.HandlerRegistry.LinkHandler());
        new WebInspector.WorkspaceController(WebInspector.workspace);
        new WebInspector.RenderingOptions();
        new WebInspector.Main.PauseListener();
        new WebInspector.Main.InspectedNodeRevealer();
        this._addMainEventListeners(document);
        WebInspector.extensionServerProxy.setFrontendReady();
        InspectorAgent.enable(inspectorAgentEnableCallback);
        function inspectorAgentEnableCallback() {
            console.timeStamp("Main.inspectorAgentEnableCallback");
            WebInspector.app.presentUI(mainTarget);
            console.timeStamp("Main.inspectorAgentEnableCallbackPresentUI");
            WebInspector.notifications.dispatchEventToListeners(WebInspector.NotificationService.Events.InspectorUILoadedForTests);
        }

        WebInspector.actionRegistry = new WebInspector.ActionRegistry();
        WebInspector.shortcutRegistry = new WebInspector.ShortcutRegistry(WebInspector.actionRegistry);
        WebInspector.ShortcutsScreen.registerShortcuts();
        this._registerForwardedShortcuts();
        this._registerMessageSinkListener();
        this._loadCompletedForWorkers();
        InspectorFrontendAPI.loadCompleted();
    }, _registerForwardedShortcuts: function () {
        var forwardedActions = ["main.reload", "main.hard-reload"];
        var actionKeys = WebInspector.shortcutRegistry.keysForActions(forwardedActions).map(WebInspector.KeyboardShortcut.keyCodeAndModifiersFromKey);
        actionKeys.push({keyCode: WebInspector.KeyboardShortcut.Keys.F8.code});
        InspectorFrontendHost.setWhitelistedShortcuts(JSON.stringify(actionKeys));
    }, _registerMessageSinkListener: function () {
        WebInspector.console.addEventListener(WebInspector.Console.Events.MessageAdded, messageAdded);
        function messageAdded(event) {
            var message = (event.data);
            if (message.show)
                WebInspector.console.show();
        }
    }, _documentClick: function (event) {
        var anchor = event.target.enclosingNodeOrSelfWithNodeName("a");
        if (!anchor || !anchor.href)
            return;
        event.consume(true);
        if (anchor.target === "_blank") {
            InspectorFrontendHost.openInNewTab(anchor.href);
            return;
        }
        function followLink() {
            if (WebInspector.isBeingEdited(event.target))
                return;
            if (WebInspector.openAnchorLocationRegistry.dispatch({url: anchor.href, lineNumber: anchor.lineNumber}))
                return;
            var uiSourceCode = WebInspector.workspace.uiSourceCodeForURL(anchor.href);
            if (uiSourceCode) {
                WebInspector.Revealer.reveal(uiSourceCode.uiLocation(anchor.lineNumber || 0, anchor.columnNumber || 0));
                return;
            }
            var resource = WebInspector.resourceForURL(anchor.href);
            if (resource) {
                WebInspector.Revealer.reveal(resource);
                return;
            }
            var request = WebInspector.networkLog.requestForURL(anchor.href);
            if (request) {
                WebInspector.Revealer.reveal(request);
                return;
            }
            InspectorFrontendHost.openInNewTab(anchor.href);
        }

        if (WebInspector.followLinkTimeout)
            clearTimeout(WebInspector.followLinkTimeout);
        if (anchor.preventFollowOnDoubleClick) {
            if (event.detail === 1)
                WebInspector.followLinkTimeout = setTimeout(followLink, 333);
            return;
        }
        followLink();
    }, _registerShortcuts: function () {
        var shortcut = WebInspector.KeyboardShortcut;
        var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("All Panels"));
        var keys = [shortcut.makeDescriptor("[", shortcut.Modifiers.CtrlOrMeta), shortcut.makeDescriptor("]", shortcut.Modifiers.CtrlOrMeta)];
        section.addRelatedKeys(keys, WebInspector.UIString("Go to the panel to the left/right"));
        keys = [shortcut.makeDescriptor("[", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Alt), shortcut.makeDescriptor("]", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Alt)];
        section.addRelatedKeys(keys, WebInspector.UIString("Go back/forward in panel history"));
        var toggleConsoleLabel = WebInspector.UIString("Show console");
        section.addKey(shortcut.makeDescriptor(shortcut.Keys.Tilde, shortcut.Modifiers.Ctrl), toggleConsoleLabel);
        section.addKey(shortcut.makeDescriptor(shortcut.Keys.Esc), WebInspector.UIString("Toggle drawer"));
        if (WebInspector.overridesSupport.responsiveDesignAvailable())
            section.addKey(shortcut.makeDescriptor("M", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Shift), WebInspector.UIString("Toggle device mode"));
        section.addKey(shortcut.makeDescriptor("f", shortcut.Modifiers.CtrlOrMeta), WebInspector.UIString("Search"));
        var advancedSearchShortcutModifier = WebInspector.isMac() ? WebInspector.KeyboardShortcut.Modifiers.Meta | WebInspector.KeyboardShortcut.Modifiers.Alt : WebInspector.KeyboardShortcut.Modifiers.Ctrl | WebInspector.KeyboardShortcut.Modifiers.Shift;
        var advancedSearchShortcut = shortcut.makeDescriptor("f", advancedSearchShortcutModifier);
        section.addKey(advancedSearchShortcut, WebInspector.UIString("Search across all sources"));
        var inspectElementModeShortcut = WebInspector.InspectElementModeController.createShortcut();
        section.addKey(inspectElementModeShortcut, WebInspector.UIString("Select node to inspect"));
        var openResourceShortcut = WebInspector.KeyboardShortcut.makeDescriptor("p", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta);
        section.addKey(openResourceShortcut, WebInspector.UIString("Go to source"));
        if (WebInspector.isMac()) {
            keys = [shortcut.makeDescriptor("g", shortcut.Modifiers.Meta), shortcut.makeDescriptor("g", shortcut.Modifiers.Meta | shortcut.Modifiers.Shift)];
            section.addRelatedKeys(keys, WebInspector.UIString("Find next/previous"));
        }
    }, _postDocumentKeyDown: function (event) {
        if (event.handled)
            return;
        if (!WebInspector.Dialog.currentInstance() && WebInspector.inspectorView.currentPanel()) {
            WebInspector.inspectorView.currentPanel().handleShortcut(event);
            if (event.handled) {
                event.consume(true);
                return;
            }
        }
        WebInspector.shortcutRegistry.handleShortcut(event);
    }, _documentCanCopy: function (event) {
        var panel = WebInspector.inspectorView.currentPanel();
        if (panel && panel["handleCopyEvent"])
            event.preventDefault();
    }, _documentCopy: function (event) {
        var panel = WebInspector.inspectorView.currentPanel();
        if (panel && panel["handleCopyEvent"])
            panel["handleCopyEvent"](event);
    }, _documentCut: function (event) {
        var panel = WebInspector.inspectorView.currentPanel();
        if (panel && panel["handleCutEvent"])
            panel["handleCutEvent"](event);
    }, _documentPaste: function (event) {
        var panel = WebInspector.inspectorView.currentPanel();
        if (panel && panel["handlePasteEvent"])
            panel["handlePasteEvent"](event);
    }, _contextMenuEventFired: function (event) {
        if (event.handled || event.target.classList.contains("popup-glasspane"))
            event.preventDefault();
    }, _addMainEventListeners: function (doc) {
        doc.addEventListener("keydown", this._postDocumentKeyDown.bind(this), false);
        doc.addEventListener("beforecopy", this._documentCanCopy.bind(this), true);
        doc.addEventListener("copy", this._documentCopy.bind(this), false);
        doc.addEventListener("cut", this._documentCut.bind(this), false);
        doc.addEventListener("paste", this._documentPaste.bind(this), false);
        doc.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), true);
        doc.addEventListener("click", this._documentClick.bind(this), false);
    }, inspect: function (payload, hints) {
        var object = WebInspector.runtimeModel.createRemoteObject(payload);
        if (object.isNode()) {
            var nodeObjectInspector = runtime.instance(WebInspector.NodeRemoteObjectInspector, object);
            if (nodeObjectInspector)
                nodeObjectInspector.inspectNodeObject(object);
            return;
        }
        if (object.type === "function") {
            object.functionDetails(didGetDetails);
            return;
        }
        function didGetDetails(response) {
            object.release();
            if (!response || !response.location)
                return;
            WebInspector.Revealer.reveal(WebInspector.debuggerWorkspaceBinding.rawLocationToUILocation(response.location));
        }

        if (hints.copyToClipboard)
            InspectorFrontendHost.copyText(object.value);
        object.release();
    }, detached: function (reason) {
        WebInspector._disconnectedScreenWithReasonWasShown = true;
        new WebInspector.RemoteDebuggingTerminatedScreen(reason).showModal();
    }, targetCrashed: function () {
        (new WebInspector.HelpScreenUntilReload(WebInspector.UIString("Inspected target crashed"), WebInspector.UIString("Inspected target has crashed. Once it reloads we will attach to it automatically."))).showModal();
    }, evaluateForTestInFrontend: function (callId, script) {
        WebInspector.evaluateForTestInFrontend(callId, script);
    }
}
WebInspector.reload = function () {
    InspectorAgent.reset();
    window.location.reload();
}
WebInspector.Main.ReloadActionDelegate = function () {
}
WebInspector.Main.ReloadActionDelegate.prototype = {
    handleAction: function () {
        WebInspector.debuggerModel.skipAllPauses(true, true);
        WebInspector.resourceTreeModel.reloadPage(false);
        return true;
    }
}
WebInspector.Main.HardReloadActionDelegate = function () {
}
WebInspector.Main.HardReloadActionDelegate.prototype = {
    handleAction: function () {
        WebInspector.debuggerModel.skipAllPauses(true, true);
        WebInspector.resourceTreeModel.reloadPage(true);
        return true;
    }
}
WebInspector.Main.DebugReloadActionDelegate = function () {
}
WebInspector.Main.DebugReloadActionDelegate.prototype = {
    handleAction: function () {
        WebInspector.reload();
        return true;
    }
}
WebInspector.Main.ZoomInActionDelegate = function () {
}
WebInspector.Main.ZoomInActionDelegate.prototype = {
    handleAction: function () {
        if (InspectorFrontendHost.isHostedMode())
            return false;
        InspectorFrontendHost.zoomIn();
        return true;
    }
}
WebInspector.Main.ZoomOutActionDelegate = function () {
}
WebInspector.Main.ZoomOutActionDelegate.prototype = {
    handleAction: function () {
        if (InspectorFrontendHost.isHostedMode())
            return false;
        InspectorFrontendHost.zoomOut();
        return true;
    }
}
WebInspector.Main.ZoomResetActionDelegate = function () {
}
WebInspector.Main.ZoomResetActionDelegate.prototype = {
    handleAction: function () {
        if (InspectorFrontendHost.isHostedMode())
            return false;
        InspectorFrontendHost.resetZoom();
        return true;
    }
}
WebInspector.Main.ShortcutPanelSwitchSettingDelegate = function () {
    WebInspector.UISettingDelegate.call(this);
}
WebInspector.Main.ShortcutPanelSwitchSettingDelegate.prototype = {
    settingElement: function () {
        var modifier = WebInspector.platform() === "mac" ? "Cmd" : "Ctrl";
        return WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Enable %s + 1-9 shortcut to switch panels", modifier), WebInspector.settings.shortcutPanelSwitch);
    }, __proto__: WebInspector.UISettingDelegate.prototype
}
WebInspector.Main._addWebSocketTarget = function (ws) {
    function callback(connection) {
        WebInspector.targetManager.createTarget(ws, connection);
    }

    new InspectorBackendClass.WebSocketConnection(ws, callback);
}
new WebInspector.Main();
WebInspector.__defineGetter__("inspectedPageURL", function () {
    return WebInspector.resourceTreeModel.inspectedPageURL();
});
WebInspector.panel = function (name) {
    return WebInspector.inspectorView.panel(name);
}
WebInspector.Main.WarningErrorCounter = function () {
    this._counter = new WebInspector.StatusBarCounter(["error-icon-small", "warning-icon-small"]);
    this._counter.addEventListener("click", showConsole);
    function showConsole() {
        WebInspector.console.show();
    }

    WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._updateErrorAndWarningCounts, this);
    WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, this._updateErrorAndWarningCounts, this);
}
WebInspector.Main.WarningErrorCounter.prototype = {
    _updateErrorAndWarningCounts: function () {
        var errors = 0;
        var warnings = 0;
        var targets = WebInspector.targetManager.targets();
        for (var i = 0; i < targets.length; ++i) {
            errors = errors + targets[i].consoleModel.errors;
            warnings = warnings + targets[i].consoleModel.warnings;
        }
        this._counter.setCounter("error-icon-small", errors, WebInspector.UIString(errors > 1 ? "%d errors" : "%d error", errors));
        this._counter.setCounter("warning-icon-small", warnings, WebInspector.UIString(warnings > 1 ? "%d warnings" : "%d warning", warnings));
        WebInspector.inspectorView.toolbarItemResized();
    }, item: function () {
        return this._counter;
    }
}
WebInspector.Main.PauseListener = function () {
    WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this);
}
WebInspector.Main.PauseListener.prototype = {
    _debuggerPaused: function (event) {
        WebInspector.targetManager.removeModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this);
        var debuggerModel = (event.target);
        WebInspector.context.setFlavor(WebInspector.Target, debuggerModel.target());
        WebInspector.inspectorView.showPanel("sources");
    }
}
WebInspector.Main.InspectedNodeRevealer = function () {
    WebInspector.targetManager.addModelListener(WebInspector.DOMModel, WebInspector.DOMModel.Events.NodeInspected, this._inspectNode, this);
}
WebInspector.Main.InspectedNodeRevealer.prototype = {
    _inspectNode: function (event) {
        WebInspector.Revealer.reveal((event.data));
    }
}
function InspectorBackendClass() {
    this._connection = null;
    this._agentPrototypes = {};
    this._dispatcherPrototypes = {};
    this._initialized = false;
    this._enums = {};
    this._initProtocolAgentsConstructor();
}
InspectorBackendClass._DevToolsErrorCode = -32000;
InspectorBackendClass.prototype = {
    _initProtocolAgentsConstructor: function () {
        window.Protocol = {};
        window.Protocol.Agents = function (agentsMap) {
            this._agentsMap = agentsMap;
        };
    }, _addAgentGetterMethodToProtocolAgentsPrototype: function (domain) {
        var upperCaseLength = 0;
        while (upperCaseLength < domain.length && domain[upperCaseLength].toLowerCase() !== domain[upperCaseLength])
            ++upperCaseLength;
        var methodName = domain.substr(0, upperCaseLength).toLowerCase() + domain.slice(upperCaseLength) + "Agent";

        function agentGetter() {
            return this._agentsMap[domain];
        }

        window.Protocol.Agents.prototype[methodName] = agentGetter;
        function registerDispatcher(dispatcher) {
            this.registerDispatcher(domain, dispatcher)
        }

        window.Protocol.Agents.prototype["register" + domain + "Dispatcher"] = registerDispatcher;
    }, connection: function () {
        if (!this._connection)
            throw"Main connection was not initialized";
        return this._connection;
    }, setConnection: function (connection) {
        this._connection = connection;
        this._connection.registerAgentsOn(window);
        for (var type in this._enums) {
            var domainAndMethod = type.split(".");
            window[domainAndMethod[0] + "Agent"][domainAndMethod[1]] = this._enums[type];
        }
    }, _agentPrototype: function (domain) {
        if (!this._agentPrototypes[domain]) {
            this._agentPrototypes[domain] = new InspectorBackendClass.AgentPrototype(domain);
            this._addAgentGetterMethodToProtocolAgentsPrototype(domain);
        }
        return this._agentPrototypes[domain];
    }, _dispatcherPrototype: function (domain) {
        if (!this._dispatcherPrototypes[domain])
            this._dispatcherPrototypes[domain] = new InspectorBackendClass.DispatcherPrototype();
        return this._dispatcherPrototypes[domain];
    }, registerCommand: function (method, signature, replyArgs, hasErrorData) {
        var domainAndMethod = method.split(".");
        this._agentPrototype(domainAndMethod[0]).registerCommand(domainAndMethod[1], signature, replyArgs, hasErrorData);
        this._initialized = true;
    }, registerEnum: function (type, values) {
        this._enums[type] = values;
        this._initialized = true;
    }, registerEvent: function (eventName, params) {
        var domain = eventName.split(".")[0];
        this._dispatcherPrototype(domain).registerEvent(eventName, params);
        this._initialized = true;
    }, registerDomainDispatcher: function (domain, dispatcher) {
        this._connection.registerDispatcher(domain, dispatcher);
    }, loadFromJSONIfNeeded: function (jsonUrl) {
        if (this._initialized)
            return;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", jsonUrl, false);
        xhr.send(null);
        var schema = JSON.parse(xhr.responseText);
        var code = InspectorBackendClass._generateCommands(schema);
        eval(code);
    }, wrapClientCallback: function (clientCallback, errorPrefix, constructor, defaultValue) {
        function callbackWrapper(error, value) {
            if (error) {
                console.error(errorPrefix + error);
                clientCallback(defaultValue);
                return;
            }
            if (constructor)
                clientCallback(new constructor(value)); else
                clientCallback(value);
        }

        return callbackWrapper;
    }
}
InspectorBackendClass._generateCommands = function (schema) {
    var jsTypes = {integer: "number", array: "object"};
    var rawTypes = {};
    var result = [];
    var domains = schema["domains"] || [];
    for (var i = 0; i < domains.length; ++i) {
        var domain = domains[i];
        for (var j = 0; domain.types && j < domain.types.length; ++j) {
            var type = domain.types[j];
            rawTypes[domain.domain + "." + type.id] = jsTypes[type.type] || type.type;
        }
    }
    function toUpperCase(groupIndex, group0, group1) {
        return [group0, group1][groupIndex].toUpperCase();
    }

    function generateEnum(enumName, items) {
        var members = []
        for (var m = 0; m < items.length; ++m) {
            var value = items[m];
            var name = value.replace(/-(\w)/g, toUpperCase.bind(null, 1)).toTitleCase();
            name = name.replace(/HTML|XML|WML|API/ig, toUpperCase.bind(null, 0));
            members.push(name + ": \"" + value + "\"");
        }
        return "InspectorBackend.registerEnum(\"" + enumName + "\", {" + members.join(", ") + "});";
    }

    for (var i = 0; i < domains.length; ++i) {
        var domain = domains[i];
        var types = domain["types"] || [];
        for (var j = 0; j < types.length; ++j) {
            var type = types[j];
            if ((type["type"] === "string") && type["enum"])
                result.push(generateEnum(domain.domain + "." + type.id, type["enum"])); else if (type["type"] === "object") {
                var properties = type["properties"] || [];
                for (var k = 0; k < properties.length; ++k) {
                    var property = properties[k];
                    if ((property["type"] === "string") && property["enum"])
                        result.push(generateEnum(domain.domain + "." + type.id + property["name"].toTitleCase(), property["enum"]));
                }
            }
        }
        var commands = domain["commands"] || [];
        for (var j = 0; j < commands.length; ++j) {
            var command = commands[j];
            var parameters = command["parameters"];
            var paramsText = [];
            for (var k = 0; parameters && k < parameters.length; ++k) {
                var parameter = parameters[k];
                var type;
                if (parameter.type)
                    type = jsTypes[parameter.type] || parameter.type; else {
                    var ref = parameter["$ref"];
                    if (ref.indexOf(".") !== -1)
                        type = rawTypes[ref]; else
                        type = rawTypes[domain.domain + "." + ref];
                }
                var text = "{\"name\": \"" + parameter.name + "\", \"type\": \"" + type + "\", \"optional\": " + (parameter.optional ? "true" : "false") + "}";
                paramsText.push(text);
            }
            var returnsText = [];
            var returns = command["returns"] || [];
            for (var k = 0; k < returns.length; ++k) {
                var parameter = returns[k];
                returnsText.push("\"" + parameter.name + "\"");
            }
            var hasErrorData = String(Boolean(command.error));
            result.push("InspectorBackend.registerCommand(\"" + domain.domain + "." + command.name + "\", [" + paramsText.join(", ") + "], [" + returnsText.join(", ") + "], " + hasErrorData + ");");
        }
        for (var j = 0; domain.events && j < domain.events.length; ++j) {
            var event = domain.events[j];
            var paramsText = [];
            for (var k = 0; event.parameters && k < event.parameters.length; ++k) {
                var parameter = event.parameters[k];
                paramsText.push("\"" + parameter.name + "\"");
            }
            result.push("InspectorBackend.registerEvent(\"" + domain.domain + "." + event.name + "\", [" + paramsText.join(", ") + "]);");
        }
        result.push("InspectorBackend.register" + domain.domain + "Dispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, \"" + domain.domain + "\");");
    }
    return result.join("\n");
}
InspectorBackendClass.Connection = function () {
    this._lastMessageId = 1;
    this._pendingResponsesCount = 0;
    this._agents = {};
    this._dispatchers = {};
    this._callbacks = {};
    this._initialize(InspectorBackend._agentPrototypes, InspectorBackend._dispatcherPrototypes);
    this._isConnected = true;
}
InspectorBackendClass.Connection.Events = {Disconnected: "Disconnected",}
InspectorBackendClass.Connection.prototype = {
    _initialize: function (agentPrototypes, dispatcherPrototypes) {
        for (var domain in agentPrototypes) {
            this._agents[domain] = Object.create(agentPrototypes[domain]);
            this._agents[domain].setConnection(this);
        }
        for (var domain in dispatcherPrototypes)
            this._dispatchers[domain] = Object.create(dispatcherPrototypes[domain])
    }, registerAgentsOn: function (object) {
        for (var domain in this._agents)
            object[domain + "Agent"] = this._agents[domain];
    }, nextMessageId: function () {
        return this._lastMessageId++;
    }, agent: function (domain) {
        return this._agents[domain];
    }, agentsMap: function () {
        return this._agents;
    }, _wrapCallbackAndSendMessageObject: function (domain, method, params, callback) {
        if (!this._isConnected && callback) {
            this._dispatchConnectionErrorResponse(domain, method, callback);
            return;
        }
        var messageObject = {};
        var messageId = this.nextMessageId();
        messageObject.id = messageId;
        messageObject.method = method;
        if (params)
            messageObject.params = params;
        var wrappedCallback = this._wrap(callback, domain, method);
        if (InspectorBackendClass.Options.dumpInspectorProtocolMessages)
            this._dumpProtocolMessage("frontend: " + JSON.stringify(messageObject));
        this.sendMessage(messageObject);
        ++this._pendingResponsesCount;
        this._callbacks[messageId] = wrappedCallback;
    }, _wrap: function (callback, domain, method) {
        if (!callback)
            callback = function () {
            };
        callback.methodName = method;
        callback.domain = domain;
        if (InspectorBackendClass.Options.dumpInspectorTimeStats)
            callback.sendRequestTime = Date.now();
        return callback;
    }, sendMessage: function (messageObject) {
        throw"Not implemented";
    }, reportProtocolError: function (messageObject) {
        console.error("Protocol Error: the message with wrong id. Message =  " + JSON.stringify(messageObject));
    }, dispatch: function (message) {
        if (InspectorBackendClass.Options.dumpInspectorProtocolMessages)
            this._dumpProtocolMessage("backend: " + ((typeof message === "string") ? message : JSON.stringify(message)));
        var messageObject = ((typeof message === "string") ? JSON.parse(message) : message);
        if ("id"in messageObject) {
            var callback = this._callbacks[messageObject.id];
            if (!callback) {
                this.reportProtocolError(messageObject);
                return;
            }
            var processingStartTime;
            if (InspectorBackendClass.Options.dumpInspectorTimeStats)
                processingStartTime = Date.now();
            this.agent(callback.domain).dispatchResponse(messageObject, callback.methodName, callback);
            --this._pendingResponsesCount;
            delete this._callbacks[messageObject.id];
            if (InspectorBackendClass.Options.dumpInspectorTimeStats)
                console.log("time-stats: " + callback.methodName + " = " + (processingStartTime - callback.sendRequestTime) + " + " + (Date.now() - processingStartTime));
            if (this._scripts && !this._pendingResponsesCount)
                this.runAfterPendingDispatches();
            return;
        } else {
            var method = messageObject.method.split(".");
            var domainName = method[0];
            if (!(domainName in this._dispatchers)) {
                console.error("Protocol Error: the message " + messageObject.method + " is for non-existing domain '" + domainName + "'");
                return;
            }
            this._dispatchers[domainName].dispatch(method[1], messageObject);
        }
    }, registerDispatcher: function (domain, dispatcher) {
        if (!this._dispatchers[domain])
            return;
        this._dispatchers[domain].setDomainDispatcher(dispatcher);
    }, runAfterPendingDispatches: function (script) {
        if (!this._scripts)
            this._scripts = [];
        if (script)
            this._scripts.push(script);
        if (!this._pendingResponsesCount) {
            var scripts = this._scripts;
            this._scripts = [];
            for (var id = 0; id < scripts.length; ++id)
                scripts[id].call(this);
        }
    }, _dumpProtocolMessage: function (message) {
        console.log(message);
    }, connectionClosed: function (reason) {
        this._isConnected = false;
        this._runPendingCallbacks();
        this.dispatchEventToListeners(InspectorBackendClass.Connection.Events.Disconnected, {reason: reason});
    }, _runPendingCallbacks: function () {
        var keys = Object.keys(this._callbacks).map(function (num) {
            return parseInt(num, 10)
        });
        for (var i = 0; i < keys.length; ++i) {
            var callback = this._callbacks[keys[i]];
            this._dispatchConnectionErrorResponse(callback.domain, callback.methodName, callback)
        }
        this._callbacks = {};
    }, _dispatchConnectionErrorResponse: function (domain, methodName, callback) {
        var error = {message: "Connection is closed", code: InspectorBackendClass._DevToolsErrorCode, data: null};
        var messageObject = {error: error};
        setTimeout(InspectorBackendClass.AgentPrototype.prototype.dispatchResponse.bind(this.agent(domain), messageObject, methodName, callback), 0);
    }, isClosed: function () {
        return !this._isConnected;
    }, suppressErrorsForDomains: function (domains) {
        domains.forEach(function (domain) {
            this._agents[domain].suppressErrorLogging();
        }, this);
    }, __proto__: WebInspector.Object.prototype
}
InspectorBackendClass.MainConnection = function () {
    InspectorBackendClass.Connection.call(this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DispatchMessage, this._dispatchMessage, this);
}
InspectorBackendClass.MainConnection.prototype = {
    sendMessage: function (messageObject) {
        var message = JSON.stringify(messageObject);
        InspectorFrontendHost.sendMessageToBackend(message);
    }, _dispatchMessage: function (event) {
        this.dispatch((event.data));
    }, __proto__: InspectorBackendClass.Connection.prototype
}
InspectorBackendClass.WebSocketConnection = function (url, onConnectionReady) {
    InspectorBackendClass.Connection.call(this);
    this._socket = new WebSocket(url);
    this._socket.setShit(this._onMessage.bind(this));
    this._socket.onerror = this._onError.bind(this);
    this._socket.onopen = onConnectionReady.bind(null, this);
    this._socket.onclose = this.connectionClosed.bind(this, "websocket_closed");
}
InspectorBackendClass.WebSocketConnection.Create = function (url, onConnectionReady) {
    new InspectorBackendClass.WebSocketConnection(url, onConnectionReady);
}
InspectorBackendClass.WebSocketConnection.prototype = {
    _onMessage: function (message) {
        var data = (message.data)
        this.dispatch(data);
    }, _onError: function (error) {
        console.error(error);
    }, sendMessage: function (messageObject) {
        var message = JSON.stringify(messageObject);
        this._socket.send(message);
    }, __proto__: InspectorBackendClass.Connection.prototype
}
InspectorBackendClass.StubConnection = function () {
    InspectorBackendClass.Connection.call(this);
}
InspectorBackendClass.StubConnection.prototype = {
    sendMessage: function (messageObject) {
        var message = JSON.stringify(messageObject);
        setTimeout(this._echoResponse.bind(this, messageObject), 0);
    }, _echoResponse: function (messageObject) {
        this.dispatch(messageObject)
    }, __proto__: InspectorBackendClass.Connection.prototype
}
InspectorBackendClass.AgentPrototype = function (domain) {
    this._replyArgs = {};
    this._hasErrorData = {};
    this._domain = domain;
    this._suppressErrorLogging = false;
}
InspectorBackendClass.AgentPrototype.prototype = {
    setConnection: function (connection) {
        this._connection = connection;
    }, registerCommand: function (methodName, signature, replyArgs, hasErrorData) {
        var domainAndMethod = this._domain + "." + methodName;

        function sendMessage(vararg) {
            var params = [domainAndMethod, signature].concat(Array.prototype.slice.call(arguments));
            InspectorBackendClass.AgentPrototype.prototype._sendMessageToBackend.apply(this, params);
        }

        this[methodName] = sendMessage;
        function invoke(vararg) {
            var params = [domainAndMethod].concat(Array.prototype.slice.call(arguments));
            InspectorBackendClass.AgentPrototype.prototype._invoke.apply(this, params);
        }

        this["invoke_" + methodName] = invoke;
        this._replyArgs[domainAndMethod] = replyArgs;
        if (hasErrorData)
            this._hasErrorData[domainAndMethod] = true;
    }, _sendMessageToBackend: function (method, signature, vararg) {
        var args = Array.prototype.slice.call(arguments, 2);
        var callback = (args.length && typeof args[args.length - 1] === "function") ? args.pop() : null;
        var params = {};
        var hasParams = false;
        for (var i = 0; i < signature.length; ++i) {
            var param = signature[i];
            var paramName = param["name"];
            var typeName = param["type"];
            var optionalFlag = param["optional"];
            if (!args.length && !optionalFlag) {
                console.error("Protocol Error: Invalid number of arguments for method '" + method + "' call. It must have the following arguments '" + JSON.stringify(signature) + "'.");
                return;
            }
            var value = args.shift();
            if (optionalFlag && typeof value === "undefined") {
                continue;
            }
            if (typeof value !== typeName) {
                console.error("Protocol Error: Invalid type of argument '" + paramName + "' for method '" + method + "' call. It must be '" + typeName + "' but it is '" + typeof value + "'.");
                return;
            }
            params[paramName] = value;
            hasParams = true;
        }
        if (args.length === 1 && !callback && (typeof args[0] !== "undefined")) {
            console.error("Protocol Error: Optional callback argument for method '" + method + "' call must be a function but its type is '" + typeof args[0] + "'.");
            return;
        }
        this._connection._wrapCallbackAndSendMessageObject(this._domain, method, hasParams ? params : null, callback);
    }, _invoke: function (method, args, callback) {
        this._connection._wrapCallbackAndSendMessageObject(this._domain, method, args, callback);
    }, dispatchResponse: function (messageObject, methodName, callback) {
        if (messageObject.error && messageObject.error.code !== InspectorBackendClass._DevToolsErrorCode && !InspectorBackendClass.Options.suppressRequestErrors && !this._suppressErrorLogging)
            console.error("Request with id = " + messageObject.id + " failed. " + JSON.stringify(messageObject.error));
        var argumentsArray = [];
        argumentsArray[0] = messageObject.error ? messageObject.error.message : null;
        if (this._hasErrorData[methodName])
            argumentsArray[1] = messageObject.error ? messageObject.error.data : null;
        if (messageObject.result) {
            var paramNames = this._replyArgs[methodName] || [];
            for (var i = 0; i < paramNames.length; ++i)
                argumentsArray.push(messageObject.result[paramNames[i]]);
        }
        callback.apply(null, argumentsArray);
    }, suppressErrorLogging: function () {
        this._suppressErrorLogging = true;
    }
}
InspectorBackendClass.DispatcherPrototype = function () {
    this._eventArgs = {};
    this._dispatcher = null;
}
InspectorBackendClass.DispatcherPrototype.prototype = {
    registerEvent: function (eventName, params) {
        this._eventArgs[eventName] = params
    }, setDomainDispatcher: function (dispatcher) {
        this._dispatcher = dispatcher;
    }, dispatch: function (functionName, messageObject) {
        if (!this._dispatcher)
            return;
        if (!(functionName in this._dispatcher)) {
            console.error("Protocol Error: Attempted to dispatch an unimplemented method '" + messageObject.method + "'");
            return;
        }
        if (!this._eventArgs[messageObject.method]) {
            console.error("Protocol Error: Attempted to dispatch an unspecified method '" + messageObject.method + "'");
            return;
        }
        var params = [];
        if (messageObject.params) {
            var paramNames = this._eventArgs[messageObject.method];
            for (var i = 0; i < paramNames.length; ++i)
                params.push(messageObject.params[paramNames[i]]);
        }
        var processingStartTime;
        if (InspectorBackendClass.Options.dumpInspectorTimeStats)
            processingStartTime = Date.now();
        this._dispatcher[functionName].apply(this._dispatcher, params);
        if (InspectorBackendClass.Options.dumpInspectorTimeStats)
            console.log("time-stats: " + messageObject.method + " = " + (Date.now() - processingStartTime));
    }
}
InspectorBackendClass.Options = {dumpInspectorTimeStats: false, dumpInspectorProtocolMessages: false, suppressRequestErrors: false}
InspectorBackend = new InspectorBackendClass();
InspectorBackend.registerInspectorDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Inspector");
InspectorBackend.registerEvent("Inspector.evaluateForTestInFrontend", ["testCallId", "script"]);
InspectorBackend.registerEvent("Inspector.inspect", ["object", "hints"]);
InspectorBackend.registerEvent("Inspector.detached", ["reason"]);
InspectorBackend.registerEvent("Inspector.targetCrashed", []);
InspectorBackend.registerCommand("Inspector.enable", [], [], false);
InspectorBackend.registerCommand("Inspector.disable", [], [], false);
InspectorBackend.registerCommand("Inspector.reset", [], [], false);
InspectorBackend.registerMemoryDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Memory");
InspectorBackend.registerCommand("Memory.getDOMCounters", [], ["documents", "nodes", "jsEventListeners"], false);
InspectorBackend.registerPageDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Page");
InspectorBackend.registerEnum("Page.ResourceType", {
    Document: "Document",
    Stylesheet: "Stylesheet",
    Image: "Image",
    Media: "Media",
    Font: "Font",
    Script: "Script",
    TextTrack: "TextTrack",
    XHR: "XHR",
    WebSocket: "WebSocket",
    Other: "Other"
});
InspectorBackend.registerEnum("Page.UsageItemId", {Filesystem: "filesystem", Database: "database", Appcache: "appcache", Indexeddatabase: "indexeddatabase"});
InspectorBackend.registerEvent("Page.domContentEventFired", ["timestamp"]);
InspectorBackend.registerEvent("Page.loadEventFired", ["timestamp"]);
InspectorBackend.registerEvent("Page.frameAttached", ["frameId", "parentFrameId"]);
InspectorBackend.registerEvent("Page.frameNavigated", ["frame"]);
InspectorBackend.registerEvent("Page.frameDetached", ["frameId"]);
InspectorBackend.registerEvent("Page.frameStartedLoading", ["frameId"]);
InspectorBackend.registerEvent("Page.frameStoppedLoading", ["frameId"]);
InspectorBackend.registerEvent("Page.frameScheduledNavigation", ["frameId", "delay"]);
InspectorBackend.registerEvent("Page.frameClearedScheduledNavigation", ["frameId"]);
InspectorBackend.registerEvent("Page.frameResized", []);
InspectorBackend.registerEvent("Page.javascriptDialogOpening", ["message"]);
InspectorBackend.registerEvent("Page.javascriptDialogClosed", []);
InspectorBackend.registerEvent("Page.scriptsEnabled", ["isEnabled"]);
InspectorBackend.registerEvent("Page.screencastFrame", ["data", "metadata"]);
InspectorBackend.registerEvent("Page.screencastVisibilityChanged", ["visible"]);
InspectorBackend.registerEvent("Page.viewportChanged", ["viewport"]);
InspectorBackend.registerCommand("Page.enable", [], [], false);
InspectorBackend.registerCommand("Page.disable", [], [], false);
InspectorBackend.registerCommand("Page.addScriptToEvaluateOnLoad", [{"name": "scriptSource", "type": "string", "optional": false}], ["identifier"], false);
InspectorBackend.registerCommand("Page.removeScriptToEvaluateOnLoad", [{"name": "identifier", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.reload", [{"name": "ignoreCache", "type": "boolean", "optional": true}, {"name": "scriptToEvaluateOnLoad", "type": "string", "optional": true}, {
    "name": "scriptPreprocessor",
    "type": "string",
    "optional": true
}], [], false);
InspectorBackend.registerCommand("Page.navigate", [{"name": "url", "type": "string", "optional": false}], ["frameId"], false);
InspectorBackend.registerCommand("Page.getNavigationHistory", [], ["currentIndex", "entries"], false);
InspectorBackend.registerCommand("Page.navigateToHistoryEntry", [{"name": "entryId", "type": "number", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.getCookies", [], ["cookies"], false);
InspectorBackend.registerCommand("Page.deleteCookie", [{"name": "cookieName", "type": "string", "optional": false}, {"name": "url", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.getResourceTree", [], ["frameTree"], false);
InspectorBackend.registerCommand("Page.getResourceContent", [{"name": "frameId", "type": "string", "optional": false}, {"name": "url", "type": "string", "optional": false}], ["content", "base64Encoded"], false);
InspectorBackend.registerCommand("Page.searchInResource", [{"name": "frameId", "type": "string", "optional": false}, {"name": "url", "type": "string", "optional": false}, {
    "name": "query",
    "type": "string",
    "optional": false
}, {"name": "caseSensitive", "type": "boolean", "optional": true}, {"name": "isRegex", "type": "boolean", "optional": true}], ["result"], false);
InspectorBackend.registerCommand("Page.setDocumentContent", [{"name": "frameId", "type": "string", "optional": false}, {"name": "html", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.setDeviceMetricsOverride", [{"name": "width", "type": "number", "optional": false}, {"name": "height", "type": "number", "optional": false}, {
    "name": "deviceScaleFactor",
    "type": "number",
    "optional": false
}, {"name": "mobile", "type": "boolean", "optional": false}, {"name": "fitWindow", "type": "boolean", "optional": false}, {"name": "scale", "type": "number", "optional": true}, {
    "name": "offsetX",
    "type": "number",
    "optional": true
}, {"name": "offsetY", "type": "number", "optional": true}], [], false);
InspectorBackend.registerCommand("Page.clearDeviceMetricsOverride", [], [], false);
InspectorBackend.registerCommand("Page.resetScrollAndPageScaleFactor", [], [], false);
InspectorBackend.registerCommand("Page.setShowPaintRects", [{"name": "result", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.setShowDebugBorders", [{"name": "show", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.setShowFPSCounter", [{"name": "show", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.setContinuousPaintingEnabled", [{"name": "enabled", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.setShowScrollBottleneckRects", [{"name": "show", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.getScriptExecutionStatus", [], ["result"], false);
InspectorBackend.registerCommand("Page.setScriptExecutionDisabled", [{"name": "value", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.setGeolocationOverride", [{"name": "latitude", "type": "number", "optional": true}, {"name": "longitude", "type": "number", "optional": true}, {
    "name": "accuracy",
    "type": "number",
    "optional": true
}], [], false);
InspectorBackend.registerCommand("Page.clearGeolocationOverride", [], [], false);
InspectorBackend.registerCommand("Page.setDeviceOrientationOverride", [{"name": "alpha", "type": "number", "optional": false}, {"name": "beta", "type": "number", "optional": false}, {
    "name": "gamma",
    "type": "number",
    "optional": false
}], [], false);
InspectorBackend.registerCommand("Page.clearDeviceOrientationOverride", [], [], false);
InspectorBackend.registerCommand("Page.setTouchEmulationEnabled", [{"name": "enabled", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.setEmulatedMedia", [{"name": "media", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Page.captureScreenshot", [], ["data"], false);
InspectorBackend.registerCommand("Page.canScreencast", [], ["result"], false);
InspectorBackend.registerCommand("Page.startScreencast", [{"name": "format", "type": "string", "optional": true}, {"name": "quality", "type": "number", "optional": true}, {
    "name": "maxWidth",
    "type": "number",
    "optional": true
}, {"name": "maxHeight", "type": "number", "optional": true}], [], false);
InspectorBackend.registerCommand("Page.stopScreencast", [], [], false);
InspectorBackend.registerCommand("Page.handleJavaScriptDialog", [{"name": "accept", "type": "boolean", "optional": false}, {"name": "promptText", "type": "string", "optional": true}], [], false);
InspectorBackend.registerCommand("Page.setShowViewportSizeOnResize", [{"name": "show", "type": "boolean", "optional": false}, {"name": "showGrid", "type": "boolean", "optional": true}], [], false);
InspectorBackend.registerCommand("Page.queryUsageAndQuota", [{"name": "securityOrigin", "type": "string", "optional": false}], ["quota", "usage"], false);
InspectorBackend.registerRuntimeDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Runtime");
InspectorBackend.registerEnum("Runtime.RemoteObjectType", {Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean", Symbol: "symbol"});
InspectorBackend.registerEnum("Runtime.RemoteObjectSubtype", {Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date"});
InspectorBackend.registerEnum("Runtime.PropertyPreviewType", {Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean", Symbol: "symbol", Accessor: "accessor"});
InspectorBackend.registerEnum("Runtime.PropertyPreviewSubtype", {Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date"});
InspectorBackend.registerEnum("Runtime.CallArgumentType", {Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean", Symbol: "symbol"});
InspectorBackend.registerEvent("Runtime.executionContextCreated", ["context"]);
InspectorBackend.registerEvent("Runtime.executionContextDestroyed", ["executionContextId"]);
InspectorBackend.registerEvent("Runtime.executionContextsCleared", []);
InspectorBackend.registerCommand("Runtime.evaluate", [{"name": "expression", "type": "string", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}, {
    "name": "includeCommandLineAPI",
    "type": "boolean",
    "optional": true
}, {"name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true}, {"name": "contextId", "type": "number", "optional": true}, {"name": "returnByValue", "type": "boolean", "optional": true}, {
    "name": "generatePreview",
    "type": "boolean",
    "optional": true
}], ["result", "wasThrown", "exceptionDetails"], false);
InspectorBackend.registerCommand("Runtime.callFunctionOn", [{"name": "objectId", "type": "string", "optional": false}, {"name": "functionDeclaration", "type": "string", "optional": false}, {
    "name": "arguments",
    "type": "object",
    "optional": true
}, {"name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true}, {"name": "returnByValue", "type": "boolean", "optional": true}, {
    "name": "generatePreview",
    "type": "boolean",
    "optional": true
}], ["result", "wasThrown"], false);
InspectorBackend.registerCommand("Runtime.getProperties", [{"name": "objectId", "type": "string", "optional": false}, {"name": "ownProperties", "type": "boolean", "optional": true}, {
    "name": "accessorPropertiesOnly",
    "type": "boolean",
    "optional": true
}], ["result", "internalProperties"], false);
InspectorBackend.registerCommand("Runtime.releaseObject", [{"name": "objectId", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Runtime.releaseObjectGroup", [{"name": "objectGroup", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Runtime.run", [], [], false);
InspectorBackend.registerCommand("Runtime.enable", [], [], false);
InspectorBackend.registerCommand("Runtime.disable", [], [], false);
InspectorBackend.registerCommand("Runtime.isRunRequired", [], ["result"], false);
InspectorBackend.registerConsoleDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Console");
InspectorBackend.registerEnum("Console.ConsoleMessageSource", {
    XML: "xml",
    Javascript: "javascript",
    Network: "network",
    ConsoleAPI: "console-api",
    Storage: "storage",
    Appcache: "appcache",
    Rendering: "rendering",
    Css: "css",
    Security: "security",
    Other: "other",
    Deprecation: "deprecation"
});
InspectorBackend.registerEnum("Console.ConsoleMessageLevel", {Log: "log", Warning: "warning", Error: "error", Debug: "debug", Info: "info"});
InspectorBackend.registerEnum("Console.ConsoleMessageType", {
    Log: "log",
    Dir: "dir",
    DirXML: "dirxml",
    Table: "table",
    Trace: "trace",
    Clear: "clear",
    StartGroup: "startGroup",
    StartGroupCollapsed: "startGroupCollapsed",
    EndGroup: "endGroup",
    Assert: "assert",
    Profile: "profile",
    ProfileEnd: "profileEnd"
});
InspectorBackend.registerEvent("Console.messageAdded", ["message"]);
InspectorBackend.registerEvent("Console.messageRepeatCountUpdated", ["count", "timestamp"]);
InspectorBackend.registerEvent("Console.messagesCleared", []);
InspectorBackend.registerCommand("Console.enable", [], [], false);
InspectorBackend.registerCommand("Console.disable", [], [], false);
InspectorBackend.registerCommand("Console.clearMessages", [], [], false);
InspectorBackend.registerCommand("Console.setMonitoringXHREnabled", [{"name": "enabled", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Console.addInspectedNode", [{"name": "nodeId", "type": "number", "optional": false}], [], false);
InspectorBackend.registerCommand("Console.addInspectedHeapObject", [{"name": "heapObjectId", "type": "number", "optional": false}], [], false);
InspectorBackend.registerCommand("Console.setTracingBasedTimeline", [{"name": "enabled", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerNetworkDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Network");
InspectorBackend.registerEnum("Network.InitiatorType", {Parser: "parser", Script: "script", Other: "other"});
InspectorBackend.registerEvent("Network.requestWillBeSent", ["requestId", "frameId", "loaderId", "documentURL", "request", "timestamp", "initiator", "redirectResponse"]);
InspectorBackend.registerEvent("Network.requestServedFromCache", ["requestId"]);
InspectorBackend.registerEvent("Network.responseReceived", ["requestId", "frameId", "loaderId", "timestamp", "type", "response"]);
InspectorBackend.registerEvent("Network.dataReceived", ["requestId", "timestamp", "dataLength", "encodedDataLength"]);
InspectorBackend.registerEvent("Network.loadingFinished", ["requestId", "timestamp", "encodedDataLength"]);
InspectorBackend.registerEvent("Network.loadingFailed", ["requestId", "timestamp", "type", "errorText", "canceled"]);
InspectorBackend.registerEvent("Network.webSocketWillSendHandshakeRequest", ["requestId", "timestamp", "request"]);
InspectorBackend.registerEvent("Network.webSocketHandshakeResponseReceived", ["requestId", "timestamp", "response"]);
InspectorBackend.registerEvent("Network.webSocketCreated", ["requestId", "url"]);
InspectorBackend.registerEvent("Network.webSocketClosed", ["requestId", "timestamp"]);
InspectorBackend.registerEvent("Network.webSocketFrameReceived", ["requestId", "timestamp", "response"]);
InspectorBackend.registerEvent("Network.webSocketFrameError", ["requestId", "timestamp", "errorMessage"]);
InspectorBackend.registerEvent("Network.webSocketFrameSent", ["requestId", "timestamp", "response"]);
InspectorBackend.registerCommand("Network.enable", [], [], false);
InspectorBackend.registerCommand("Network.disable", [], [], false);
InspectorBackend.registerCommand("Network.setUserAgentOverride", [{"name": "userAgent", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Network.setExtraHTTPHeaders", [{"name": "headers", "type": "object", "optional": false}], [], false);
InspectorBackend.registerCommand("Network.getResponseBody", [{"name": "requestId", "type": "string", "optional": false}], ["body", "base64Encoded"], false);
InspectorBackend.registerCommand("Network.replayXHR", [{"name": "requestId", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Network.canClearBrowserCache", [], ["result"], false);
InspectorBackend.registerCommand("Network.clearBrowserCache", [], [], false);
InspectorBackend.registerCommand("Network.canClearBrowserCookies", [], ["result"], false);
InspectorBackend.registerCommand("Network.clearBrowserCookies", [], [], false);
InspectorBackend.registerCommand("Network.canEmulateNetworkConditions", [], ["result"], false);
InspectorBackend.registerCommand("Network.emulateNetworkConditions", [{"name": "offline", "type": "boolean", "optional": false}, {"name": "latency", "type": "number", "optional": false}, {
    "name": "downloadThroughput",
    "type": "number",
    "optional": false
}, {"name": "uploadThroughput", "type": "number", "optional": false}], [], false);
InspectorBackend.registerCommand("Network.setCacheDisabled", [{"name": "cacheDisabled", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Network.loadResourceForFrontend", [{"name": "frameId", "type": "string", "optional": false}, {"name": "url", "type": "string", "optional": false}, {
    "name": "requestHeaders",
    "type": "object",
    "optional": true
}], ["statusCode", "responseHeaders", "content"], false);
InspectorBackend.registerDatabaseDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Database");
InspectorBackend.registerEvent("Database.addDatabase", ["database"]);
InspectorBackend.registerCommand("Database.enable", [], [], false);
InspectorBackend.registerCommand("Database.disable", [], [], false);
InspectorBackend.registerCommand("Database.getDatabaseTableNames", [{"name": "databaseId", "type": "string", "optional": false}], ["tableNames"], false);
InspectorBackend.registerCommand("Database.executeSQL", [{"name": "databaseId", "type": "string", "optional": false}, {"name": "query", "type": "string", "optional": false}], ["columnNames", "values", "sqlError"], false);
InspectorBackend.registerIndexedDBDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "IndexedDB");
InspectorBackend.registerEnum("IndexedDB.KeyType", {Number: "number", String: "string", Date: "date", Array: "array"});
InspectorBackend.registerEnum("IndexedDB.KeyPathType", {Null: "null", String: "string", Array: "array"});
InspectorBackend.registerCommand("IndexedDB.enable", [], [], false);
InspectorBackend.registerCommand("IndexedDB.disable", [], [], false);
InspectorBackend.registerCommand("IndexedDB.requestDatabaseNames", [{"name": "securityOrigin", "type": "string", "optional": false}], ["databaseNames"], false);
InspectorBackend.registerCommand("IndexedDB.requestDatabase", [{"name": "securityOrigin", "type": "string", "optional": false}, {"name": "databaseName", "type": "string", "optional": false}], ["databaseWithObjectStores"], false);
InspectorBackend.registerCommand("IndexedDB.requestData", [{"name": "securityOrigin", "type": "string", "optional": false}, {"name": "databaseName", "type": "string", "optional": false}, {
    "name": "objectStoreName",
    "type": "string",
    "optional": false
}, {"name": "indexName", "type": "string", "optional": false}, {"name": "skipCount", "type": "number", "optional": false}, {"name": "pageSize", "type": "number", "optional": false}, {
    "name": "keyRange",
    "type": "object",
    "optional": true
}], ["objectStoreDataEntries", "hasMore"], false);
InspectorBackend.registerCommand("IndexedDB.clearObjectStore", [{"name": "securityOrigin", "type": "string", "optional": false}, {"name": "databaseName", "type": "string", "optional": false}, {
    "name": "objectStoreName",
    "type": "string",
    "optional": false
}], [], false);
InspectorBackend.registerDOMStorageDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DOMStorage");
InspectorBackend.registerEvent("DOMStorage.domStorageItemsCleared", ["storageId"]);
InspectorBackend.registerEvent("DOMStorage.domStorageItemRemoved", ["storageId", "key"]);
InspectorBackend.registerEvent("DOMStorage.domStorageItemAdded", ["storageId", "key", "newValue"]);
InspectorBackend.registerEvent("DOMStorage.domStorageItemUpdated", ["storageId", "key", "oldValue", "newValue"]);
InspectorBackend.registerCommand("DOMStorage.enable", [], [], false);
InspectorBackend.registerCommand("DOMStorage.disable", [], [], false);
InspectorBackend.registerCommand("DOMStorage.getDOMStorageItems", [{"name": "storageId", "type": "object", "optional": false}], ["entries"], false);
InspectorBackend.registerCommand("DOMStorage.setDOMStorageItem", [{"name": "storageId", "type": "object", "optional": false}, {"name": "key", "type": "string", "optional": false}, {
    "name": "value",
    "type": "string",
    "optional": false
}], [], false);
InspectorBackend.registerCommand("DOMStorage.removeDOMStorageItem", [{"name": "storageId", "type": "object", "optional": false}, {"name": "key", "type": "string", "optional": false}], [], false);
InspectorBackend.registerApplicationCacheDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "ApplicationCache");
InspectorBackend.registerEvent("ApplicationCache.applicationCacheStatusUpdated", ["frameId", "manifestURL", "status"]);
InspectorBackend.registerEvent("ApplicationCache.networkStateUpdated", ["isNowOnline"]);
InspectorBackend.registerCommand("ApplicationCache.getFramesWithManifests", [], ["frameIds"], false);
InspectorBackend.registerCommand("ApplicationCache.enable", [], [], false);
InspectorBackend.registerCommand("ApplicationCache.getManifestForFrame", [{"name": "frameId", "type": "string", "optional": false}], ["manifestURL"], false);
InspectorBackend.registerCommand("ApplicationCache.getApplicationCacheForFrame", [{"name": "frameId", "type": "string", "optional": false}], ["applicationCache"], false);
InspectorBackend.registerFileSystemDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "FileSystem");
InspectorBackend.registerCommand("FileSystem.enable", [], [], false);
InspectorBackend.registerCommand("FileSystem.disable", [], [], false);
InspectorBackend.registerCommand("FileSystem.requestFileSystemRoot", [{"name": "origin", "type": "string", "optional": false}, {"name": "type", "type": "string", "optional": false}], ["errorCode", "root"], false);
InspectorBackend.registerCommand("FileSystem.requestDirectoryContent", [{"name": "url", "type": "string", "optional": false}], ["errorCode", "entries"], false);
InspectorBackend.registerCommand("FileSystem.requestMetadata", [{"name": "url", "type": "string", "optional": false}], ["errorCode", "metadata"], false);
InspectorBackend.registerCommand("FileSystem.requestFileContent", [{"name": "url", "type": "string", "optional": false}, {"name": "readAsText", "type": "boolean", "optional": false}, {
    "name": "start",
    "type": "number",
    "optional": true
}, {"name": "end", "type": "number", "optional": true}, {"name": "charset", "type": "string", "optional": true}], ["errorCode", "content", "charset"], false);
InspectorBackend.registerCommand("FileSystem.deleteEntry", [{"name": "url", "type": "string", "optional": false}], ["errorCode"], false);
InspectorBackend.registerDOMDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DOM");
InspectorBackend.registerEnum("DOM.PseudoType", {Before: "before", After: "after"});
InspectorBackend.registerEnum("DOM.ShadowRootType", {UserAgent: "user-agent", Author: "author"});
InspectorBackend.registerEvent("DOM.documentUpdated", []);
InspectorBackend.registerEvent("DOM.inspectNodeRequested", ["nodeId"]);
InspectorBackend.registerEvent("DOM.setChildNodes", ["parentId", "nodes"]);
InspectorBackend.registerEvent("DOM.attributeModified", ["nodeId", "name", "value"]);
InspectorBackend.registerEvent("DOM.attributeRemoved", ["nodeId", "name"]);
InspectorBackend.registerEvent("DOM.inlineStyleInvalidated", ["nodeIds"]);
InspectorBackend.registerEvent("DOM.characterDataModified", ["nodeId", "characterData"]);
InspectorBackend.registerEvent("DOM.childNodeCountUpdated", ["nodeId", "childNodeCount"]);
InspectorBackend.registerEvent("DOM.childNodeInserted", ["parentNodeId", "previousNodeId", "node"]);
InspectorBackend.registerEvent("DOM.childNodeRemoved", ["parentNodeId", "nodeId"]);
InspectorBackend.registerEvent("DOM.shadowRootPushed", ["hostId", "root"]);
InspectorBackend.registerEvent("DOM.shadowRootPopped", ["hostId", "rootId"]);
InspectorBackend.registerEvent("DOM.pseudoElementAdded", ["parentId", "pseudoElement"]);
InspectorBackend.registerEvent("DOM.pseudoElementRemoved", ["parentId", "pseudoElementId"]);
InspectorBackend.registerCommand("DOM.enable", [], [], false);
InspectorBackend.registerCommand("DOM.disable", [], [], false);
InspectorBackend.registerCommand("DOM.getDocument", [], ["root"], false);
InspectorBackend.registerCommand("DOM.requestChildNodes", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "depth", "type": "number", "optional": true}], [], false);
InspectorBackend.registerCommand("DOM.querySelector", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["nodeId"], false);
InspectorBackend.registerCommand("DOM.querySelectorAll", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "selector", "type": "string", "optional": false}], ["nodeIds"], false);
InspectorBackend.registerCommand("DOM.setNodeName", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "name", "type": "string", "optional": false}], ["nodeId"], false);
InspectorBackend.registerCommand("DOM.setNodeValue", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "value", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOM.removeNode", [{"name": "nodeId", "type": "number", "optional": false}], [], false);
InspectorBackend.registerCommand("DOM.setAttributeValue", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "name", "type": "string", "optional": false}, {"name": "value", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOM.setAttributesAsText", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "text", "type": "string", "optional": false}, {"name": "name", "type": "string", "optional": true}], [], false);
InspectorBackend.registerCommand("DOM.removeAttribute", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "name", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOM.getEventListenersForNode", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}], ["listeners"], false);
InspectorBackend.registerCommand("DOM.getOuterHTML", [{"name": "nodeId", "type": "number", "optional": false}], ["outerHTML"], false);
InspectorBackend.registerCommand("DOM.setOuterHTML", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "outerHTML", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOM.performSearch", [{"name": "query", "type": "string", "optional": false}, {"name": "includeUserAgentShadowDOM", "type": "boolean", "optional": true}], ["searchId", "resultCount"], false);
InspectorBackend.registerCommand("DOM.getSearchResults", [{"name": "searchId", "type": "string", "optional": false}, {"name": "fromIndex", "type": "number", "optional": false}, {
    "name": "toIndex",
    "type": "number",
    "optional": false
}], ["nodeIds"], false);
InspectorBackend.registerCommand("DOM.discardSearchResults", [{"name": "searchId", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOM.requestNode", [{"name": "objectId", "type": "string", "optional": false}], ["nodeId"], false);
InspectorBackend.registerCommand("DOM.setInspectModeEnabled", [{"name": "enabled", "type": "boolean", "optional": false}, {"name": "inspectUAShadowDOM", "type": "boolean", "optional": true}, {
    "name": "highlightConfig",
    "type": "object",
    "optional": true
}], [], false);
InspectorBackend.registerCommand("DOM.highlightRect", [{"name": "x", "type": "number", "optional": false}, {"name": "y", "type": "number", "optional": false}, {"name": "width", "type": "number", "optional": false}, {
    "name": "height",
    "type": "number",
    "optional": false
}, {"name": "color", "type": "object", "optional": true}, {"name": "outlineColor", "type": "object", "optional": true}], [], false);
InspectorBackend.registerCommand("DOM.highlightQuad", [{"name": "quad", "type": "object", "optional": false}, {"name": "color", "type": "object", "optional": true}, {"name": "outlineColor", "type": "object", "optional": true}], [], false);
InspectorBackend.registerCommand("DOM.highlightNode", [{"name": "highlightConfig", "type": "object", "optional": false}, {"name": "nodeId", "type": "number", "optional": true}, {
    "name": "objectId",
    "type": "string",
    "optional": true
}], [], false);
InspectorBackend.registerCommand("DOM.hideHighlight", [], [], false);
InspectorBackend.registerCommand("DOM.highlightFrame", [{"name": "frameId", "type": "string", "optional": false}, {"name": "contentColor", "type": "object", "optional": true}, {
    "name": "contentOutlineColor",
    "type": "object",
    "optional": true
}], [], false);
InspectorBackend.registerCommand("DOM.pushNodeByPathToFrontend", [{"name": "path", "type": "string", "optional": false}], ["nodeId"], false);
InspectorBackend.registerCommand("DOM.pushNodesByBackendIdsToFrontend", [{"name": "backendNodeIds", "type": "object", "optional": false}], ["nodeIds"], false);
InspectorBackend.registerCommand("DOM.resolveNode", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}], ["object"], false);
InspectorBackend.registerCommand("DOM.getAttributes", [{"name": "nodeId", "type": "number", "optional": false}], ["attributes"], false);
InspectorBackend.registerCommand("DOM.copyTo", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "targetNodeId", "type": "number", "optional": false}, {
    "name": "insertBeforeNodeId",
    "type": "number",
    "optional": true
}], ["nodeId"], false);
InspectorBackend.registerCommand("DOM.moveTo", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "targetNodeId", "type": "number", "optional": false}, {
    "name": "insertBeforeNodeId",
    "type": "number",
    "optional": true
}], ["nodeId"], false);
InspectorBackend.registerCommand("DOM.undo", [], [], false);
InspectorBackend.registerCommand("DOM.redo", [], [], false);
InspectorBackend.registerCommand("DOM.markUndoableState", [], [], false);
InspectorBackend.registerCommand("DOM.focus", [{"name": "nodeId", "type": "number", "optional": false}], [], false);
InspectorBackend.registerCommand("DOM.setFileInputFiles", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "files", "type": "object", "optional": false}], [], false);
InspectorBackend.registerCommand("DOM.getBoxModel", [{"name": "nodeId", "type": "number", "optional": false}], ["model"], false);
InspectorBackend.registerCommand("DOM.getNodeForLocation", [{"name": "x", "type": "number", "optional": false}, {"name": "y", "type": "number", "optional": false}], ["nodeId"], false);
InspectorBackend.registerCommand("DOM.getRelayoutBoundary", [{"name": "nodeId", "type": "number", "optional": false}], ["nodeId"], false);
InspectorBackend.registerCSSDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "CSS");
InspectorBackend.registerEnum("CSS.StyleSheetOrigin", {User: "user", UserAgent: "user-agent", Inspector: "inspector", Regular: "regular"});
InspectorBackend.registerEnum("CSS.CSSMediaSource", {MediaRule: "mediaRule", ImportRule: "importRule", LinkedSheet: "linkedSheet", InlineSheet: "inlineSheet"});
InspectorBackend.registerEvent("CSS.mediaQueryResultChanged", []);
InspectorBackend.registerEvent("CSS.styleSheetChanged", ["styleSheetId"]);
InspectorBackend.registerEvent("CSS.styleSheetAdded", ["header"]);
InspectorBackend.registerEvent("CSS.styleSheetRemoved", ["styleSheetId"]);
InspectorBackend.registerCommand("CSS.enable", [], [], false);
InspectorBackend.registerCommand("CSS.disable", [], [], false);
InspectorBackend.registerCommand("CSS.getMatchedStylesForNode", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "excludePseudo", "type": "boolean", "optional": true}, {
    "name": "excludeInherited",
    "type": "boolean",
    "optional": true
}], ["matchedCSSRules", "pseudoElements", "inherited"], false);
InspectorBackend.registerCommand("CSS.getInlineStylesForNode", [{"name": "nodeId", "type": "number", "optional": false}], ["inlineStyle", "attributesStyle"], false);
InspectorBackend.registerCommand("CSS.getComputedStyleForNode", [{"name": "nodeId", "type": "number", "optional": false}], ["computedStyle"], false);
InspectorBackend.registerCommand("CSS.getPlatformFontsForNode", [{"name": "nodeId", "type": "number", "optional": false}], ["cssFamilyName", "fonts"], false);
InspectorBackend.registerCommand("CSS.getStyleSheetText", [{"name": "styleSheetId", "type": "string", "optional": false}], ["text"], false);
InspectorBackend.registerCommand("CSS.setStyleSheetText", [{"name": "styleSheetId", "type": "string", "optional": false}, {"name": "text", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("CSS.setPropertyText", [{"name": "styleSheetId", "type": "string", "optional": false}, {"name": "range", "type": "object", "optional": false}, {
    "name": "text",
    "type": "string",
    "optional": false
}], ["style"], false);
InspectorBackend.registerCommand("CSS.setRuleSelector", [{"name": "styleSheetId", "type": "string", "optional": false}, {"name": "range", "type": "object", "optional": false}, {
    "name": "selector",
    "type": "string",
    "optional": false
}], ["rule"], false);
InspectorBackend.registerCommand("CSS.createStyleSheet", [{"name": "frameId", "type": "string", "optional": false}], ["styleSheetId"], false);
InspectorBackend.registerCommand("CSS.addRule", [{"name": "styleSheetId", "type": "string", "optional": false}, {"name": "ruleText", "type": "string", "optional": false}, {
    "name": "location",
    "type": "object",
    "optional": false
}], ["rule"], false);
InspectorBackend.registerCommand("CSS.forcePseudoState", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "forcedPseudoClasses", "type": "object", "optional": false}], [], false);
InspectorBackend.registerCommand("CSS.getMediaQueries", [], ["medias"], false);
InspectorBackend.registerTimelineDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Timeline");
InspectorBackend.registerEvent("Timeline.eventRecorded", ["record"]);
InspectorBackend.registerEvent("Timeline.progress", ["count"]);
InspectorBackend.registerEvent("Timeline.started", ["consoleTimeline"]);
InspectorBackend.registerEvent("Timeline.stopped", ["consoleTimeline", "events"]);
InspectorBackend.registerCommand("Timeline.enable", [], [], false);
InspectorBackend.registerCommand("Timeline.disable", [], [], false);
InspectorBackend.registerCommand("Timeline.start", [{"name": "maxCallStackDepth", "type": "number", "optional": true}, {"name": "bufferEvents", "type": "boolean", "optional": true}, {
    "name": "liveEvents",
    "type": "string",
    "optional": true
}, {"name": "includeCounters", "type": "boolean", "optional": true}, {"name": "includeGPUEvents", "type": "boolean", "optional": true}], [], false);
InspectorBackend.registerCommand("Timeline.stop", [], [], false);
InspectorBackend.registerDebuggerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Debugger");
InspectorBackend.registerEnum("Debugger.ScopeType", {Global: "global", Local: "local", With: "with", Closure: "closure", Catch: "catch"});
InspectorBackend.registerEvent("Debugger.globalObjectCleared", []);
InspectorBackend.registerEvent("Debugger.scriptParsed", ["scriptId", "url", "startLine", "startColumn", "endLine", "endColumn", "isContentScript", "sourceMapURL", "hasSourceURL", "context_data"]);
InspectorBackend.registerEvent("Debugger.scriptFailedToParse", ["scriptId", "url", "startLine", "startColumn", "endLine", "endColumn", "isContentScript", "sourceMapURL", "hasSourceURL"]);
InspectorBackend.registerEvent("Debugger.breakpointResolved", ["breakpointId", "location"]);
InspectorBackend.registerEvent("Debugger.paused", ["callFrames", "reason", "data", "hitBreakpoints", "asyncStackTrace"]);
InspectorBackend.registerEvent("Debugger.resumed", []);
InspectorBackend.registerCommand("Debugger.enable", [], [], false);
InspectorBackend.registerCommand("Debugger.disable", [], [], false);
InspectorBackend.registerCommand("Debugger.setBreakpointsActive", [{"name": "active", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCommand("Debugger.setSkipAllPauses", [{"name": "skipped", "type": "boolean", "optional": false}, {"name": "untilReload", "type": "boolean", "optional": true}], [], false);
InspectorBackend.registerCommand("Debugger.setBreakpointByUrl", [{"name": "lineNumber", "type": "number", "optional": false}, {"name": "url", "type": "string", "optional": true}, {
    "name": "urlRegex",
    "type": "string",
    "optional": true
}, {"name": "columnNumber", "type": "number", "optional": true}, {"name": "condition", "type": "string", "optional": true}, {"name": "isAntibreakpoint", "type": "boolean", "optional": true}], ["breakpointId", "locations"], false);
InspectorBackend.registerCommand("Debugger.setBreakpoint", [{"name": "location", "type": "object", "optional": false}, {"name": "condition", "type": "string", "optional": true}], ["breakpointId", "actualLocation"], false);
InspectorBackend.registerCommand("Debugger.removeBreakpoint", [{"name": "breakpointId", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Debugger.continueToLocation", [{"name": "location", "type": "object", "optional": false}, {"name": "interstatementLocation", "type": "boolean", "optional": true}], [], false);
InspectorBackend.registerCommand("Debugger.stepOver", [], [], false);
InspectorBackend.registerCommand("Debugger.stepInto", [], [], false);
InspectorBackend.registerCommand("Debugger.stepOut", [], [], false);
InspectorBackend.registerCommand("Debugger.pause", [], [], false);
InspectorBackend.registerCommand("Debugger.resume", [], [], false);
InspectorBackend.registerCommand("Debugger.searchInContent", [{"name": "scriptId", "type": "string", "optional": false}, {"name": "query", "type": "string", "optional": false}, {
    "name": "caseSensitive",
    "type": "boolean",
    "optional": true
}, {"name": "isRegex", "type": "boolean", "optional": true}], ["result"], false);
InspectorBackend.registerCommand("Debugger.canSetScriptSource", [], ["result"], false);
InspectorBackend.registerCommand("Debugger.setScriptSource", [{"name": "scriptId", "type": "string", "optional": false}, {"name": "scriptSource", "type": "string", "optional": false}, {
    "name": "preview",
    "type": "boolean",
    "optional": true
}], ["callFrames", "result", "asyncStackTrace"], true);
InspectorBackend.registerCommand("Debugger.restartFrame", [{"name": "callFrameId", "type": "string", "optional": false}], ["callFrames", "result", "asyncStackTrace"], false);
InspectorBackend.registerCommand("Debugger.getScriptSource", [{"name": "scriptId", "type": "string", "optional": false}], ["scriptSource"], false);
InspectorBackend.registerCommand("Debugger.getFunctionDetails", [{"name": "functionId", "type": "string", "optional": false}], ["details"], false);
InspectorBackend.registerCommand("Debugger.setPauseOnExceptions", [{"name": "state", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Debugger.evaluateOnCallFrame", [{"name": "callFrameId", "type": "string", "optional": false}, {"name": "expression", "type": "string", "optional": false}, {
    "name": "objectGroup",
    "type": "string",
    "optional": true
}, {"name": "includeCommandLineAPI", "type": "boolean", "optional": true}, {"name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true}, {
    "name": "returnByValue",
    "type": "boolean",
    "optional": true
}, {"name": "generatePreview", "type": "boolean", "optional": true}], ["result", "wasThrown", "exceptionDetails"], false);
InspectorBackend.registerCommand("Debugger.compileScript", [{"name": "expression", "type": "string", "optional": false}, {"name": "sourceURL", "type": "string", "optional": false}, {
    "name": "executionContextId",
    "type": "number",
    "optional": true
}], ["scriptId", "exceptionDetails"], false);
InspectorBackend.registerCommand("Debugger.runScript", [{"name": "scriptId", "type": "string", "optional": false}, {"name": "executionContextId", "type": "number", "optional": true}, {
    "name": "objectGroup",
    "type": "string",
    "optional": true
}, {"name": "doNotPauseOnExceptionsAndMuteConsole", "type": "boolean", "optional": true}], ["result", "exceptionDetails"], false);
InspectorBackend.registerCommand("Debugger.setOverlayMessage", [{"name": "message", "type": "string", "optional": true}], [], false);
InspectorBackend.registerCommand("Debugger.setVariableValue", [{"name": "scopeNumber", "type": "number", "optional": false}, {"name": "variableName", "type": "string", "optional": false}, {
    "name": "newValue",
    "type": "object",
    "optional": false
}, {"name": "callFrameId", "type": "string", "optional": true}, {"name": "functionObjectId", "type": "string", "optional": true}], [], false);
InspectorBackend.registerCommand("Debugger.getStepInPositions", [{"name": "callFrameId", "type": "string", "optional": false}], ["stepInPositions"], false);
InspectorBackend.registerCommand("Debugger.getBacktrace", [], ["callFrames", "asyncStackTrace"], false);
InspectorBackend.registerCommand("Debugger.skipStackFrames", [{"name": "script", "type": "string", "optional": true}], [], false);
InspectorBackend.registerCommand("Debugger.setAsyncCallStackDepth", [{"name": "maxDepth", "type": "number", "optional": false}], [], false);
InspectorBackend.registerDOMDebuggerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DOMDebugger");
InspectorBackend.registerEnum("DOMDebugger.DOMBreakpointType", {SubtreeModified: "subtree-modified", AttributeModified: "attribute-modified", NodeRemoved: "node-removed"});
InspectorBackend.registerCommand("DOMDebugger.setDOMBreakpoint", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "type", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOMDebugger.removeDOMBreakpoint", [{"name": "nodeId", "type": "number", "optional": false}, {"name": "type", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOMDebugger.setEventListenerBreakpoint", [{"name": "eventName", "type": "string", "optional": false}, {"name": "targetName", "type": "string", "optional": true}], [], false);
InspectorBackend.registerCommand("DOMDebugger.removeEventListenerBreakpoint", [{"name": "eventName", "type": "string", "optional": false}, {"name": "targetName", "type": "string", "optional": true}], [], false);
InspectorBackend.registerCommand("DOMDebugger.setInstrumentationBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOMDebugger.removeInstrumentationBreakpoint", [{"name": "eventName", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOMDebugger.setXHRBreakpoint", [{"name": "url", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("DOMDebugger.removeXHRBreakpoint", [{"name": "url", "type": "string", "optional": false}], [], false);
InspectorBackend.registerProfilerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Profiler");
InspectorBackend.registerEvent("Profiler.consoleProfileStarted", ["id", "location", "title"]);
InspectorBackend.registerEvent("Profiler.consoleProfileFinished", ["id", "location", "profile", "title"]);
InspectorBackend.registerCommand("Profiler.enable", [], [], false);
InspectorBackend.registerCommand("Profiler.disable", [], [], false);
InspectorBackend.registerCommand("Profiler.setSamplingInterval", [{"name": "interval", "type": "number", "optional": false}], [], false);
InspectorBackend.registerCommand("Profiler.start", [], [], false);
InspectorBackend.registerCommand("Profiler.stop", [], ["profile"], false);
InspectorBackend.registerHeapProfilerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "HeapProfiler");
InspectorBackend.registerEvent("HeapProfiler.addHeapSnapshotChunk", ["chunk"]);
InspectorBackend.registerEvent("HeapProfiler.resetProfiles", []);
InspectorBackend.registerEvent("HeapProfiler.reportHeapSnapshotProgress", ["done", "total", "finished"]);
InspectorBackend.registerEvent("HeapProfiler.lastSeenObjectId", ["lastSeenObjectId", "timestamp"]);
InspectorBackend.registerEvent("HeapProfiler.heapStatsUpdate", ["statsUpdate"]);
InspectorBackend.registerCommand("HeapProfiler.enable", [], [], false);
InspectorBackend.registerCommand("HeapProfiler.disable", [], [], false);
InspectorBackend.registerCommand("HeapProfiler.startTrackingHeapObjects", [{"name": "trackAllocations", "type": "boolean", "optional": true}], [], false);
InspectorBackend.registerCommand("HeapProfiler.stopTrackingHeapObjects", [{"name": "reportProgress", "type": "boolean", "optional": true}], [], false);
InspectorBackend.registerCommand("HeapProfiler.takeHeapSnapshot", [{"name": "reportProgress", "type": "boolean", "optional": true}], [], false);
InspectorBackend.registerCommand("HeapProfiler.collectGarbage", [], [], false);
InspectorBackend.registerCommand("HeapProfiler.getObjectByHeapObjectId", [{"name": "objectId", "type": "string", "optional": false}, {"name": "objectGroup", "type": "string", "optional": true}], ["result"], false);
InspectorBackend.registerCommand("HeapProfiler.getHeapObjectId", [{"name": "objectId", "type": "string", "optional": false}], ["heapSnapshotObjectId"], false);
InspectorBackend.registerWorkerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Worker");
InspectorBackend.registerEvent("Worker.workerCreated", ["workerId", "url", "inspectorConnected"]);
InspectorBackend.registerEvent("Worker.workerTerminated", ["workerId"]);
InspectorBackend.registerEvent("Worker.dispatchMessageFromWorker", ["workerId", "message"]);
InspectorBackend.registerEvent("Worker.disconnectedFromWorker", []);
InspectorBackend.registerCommand("Worker.enable", [], [], false);
InspectorBackend.registerCommand("Worker.disable", [], [], false);
InspectorBackend.registerCommand("Worker.sendMessageToWorker", [{"name": "workerId", "type": "number", "optional": false}, {"name": "message", "type": "object", "optional": false}], [], false);
InspectorBackend.registerCommand("Worker.canInspectWorkers", [], ["result"], false);
InspectorBackend.registerCommand("Worker.connectToWorker", [{"name": "workerId", "type": "number", "optional": false}], [], false);
InspectorBackend.registerCommand("Worker.disconnectFromWorker", [{"name": "workerId", "type": "number", "optional": false}], [], false);
InspectorBackend.registerCommand("Worker.setAutoconnectToWorkers", [{"name": "value", "type": "boolean", "optional": false}], [], false);
InspectorBackend.registerCanvasDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Canvas");
InspectorBackend.registerEnum("Canvas.CallArgumentType", {Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean"});
InspectorBackend.registerEnum("Canvas.CallArgumentSubtype", {Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date"});
InspectorBackend.registerEvent("Canvas.contextCreated", ["frameId"]);
InspectorBackend.registerEvent("Canvas.traceLogsRemoved", ["frameId", "traceLogId"]);
InspectorBackend.registerCommand("Canvas.enable", [], [], false);
InspectorBackend.registerCommand("Canvas.disable", [], [], false);
InspectorBackend.registerCommand("Canvas.dropTraceLog", [{"name": "traceLogId", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Canvas.hasUninstrumentedCanvases", [], ["result"], false);
InspectorBackend.registerCommand("Canvas.captureFrame", [{"name": "frameId", "type": "string", "optional": true}], ["traceLogId"], false);
InspectorBackend.registerCommand("Canvas.startCapturing", [{"name": "frameId", "type": "string", "optional": true}], ["traceLogId"], false);
InspectorBackend.registerCommand("Canvas.stopCapturing", [{"name": "traceLogId", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("Canvas.getTraceLog", [{"name": "traceLogId", "type": "string", "optional": false}, {"name": "startOffset", "type": "number", "optional": true}, {
    "name": "maxLength",
    "type": "number",
    "optional": true
}], ["traceLog"], false);
InspectorBackend.registerCommand("Canvas.replayTraceLog", [{"name": "traceLogId", "type": "string", "optional": false}, {"name": "stepNo", "type": "number", "optional": false}], ["resourceState", "replayTime"], false);
InspectorBackend.registerCommand("Canvas.getResourceState", [{"name": "traceLogId", "type": "string", "optional": false}, {"name": "resourceId", "type": "string", "optional": false}], ["resourceState"], false);
InspectorBackend.registerCommand("Canvas.evaluateTraceLogCallArgument", [{"name": "traceLogId", "type": "string", "optional": false}, {"name": "callIndex", "type": "number", "optional": false}, {
    "name": "argumentIndex",
    "type": "number",
    "optional": false
}, {"name": "objectGroup", "type": "string", "optional": true}], ["result", "resourceState"], false);
InspectorBackend.registerInputDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Input");
InspectorBackend.registerEnum("Input.TouchPointState", {TouchPressed: "touchPressed", TouchReleased: "touchReleased", TouchMoved: "touchMoved", TouchStationary: "touchStationary", TouchCancelled: "touchCancelled"});
InspectorBackend.registerCommand("Input.dispatchKeyEvent", [{"name": "type", "type": "string", "optional": false}, {"name": "modifiers", "type": "number", "optional": true}, {
    "name": "timestamp",
    "type": "number",
    "optional": true
}, {"name": "text", "type": "string", "optional": true}, {"name": "unmodifiedText", "type": "string", "optional": true}, {"name": "keyIdentifier", "type": "string", "optional": true}, {
    "name": "windowsVirtualKeyCode",
    "type": "number",
    "optional": true
}, {"name": "nativeVirtualKeyCode", "type": "number", "optional": true}, {"name": "autoRepeat", "type": "boolean", "optional": true}, {"name": "isKeypad", "type": "boolean", "optional": true}, {
    "name": "isSystemKey",
    "type": "boolean",
    "optional": true
}], [], false);
InspectorBackend.registerCommand("Input.dispatchMouseEvent", [{"name": "type", "type": "string", "optional": false}, {"name": "x", "type": "number", "optional": false}, {
    "name": "y",
    "type": "number",
    "optional": false
}, {"name": "modifiers", "type": "number", "optional": true}, {"name": "timestamp", "type": "number", "optional": true}, {"name": "button", "type": "string", "optional": true}, {
    "name": "clickCount",
    "type": "number",
    "optional": true
}], [], false);
InspectorBackend.registerCommand("Input.dispatchTouchEvent", [{"name": "type", "type": "string", "optional": false}, {"name": "touchPoints", "type": "object", "optional": false}, {
    "name": "modifiers",
    "type": "number",
    "optional": true
}, {"name": "timestamp", "type": "number", "optional": true}], [], false);
InspectorBackend.registerCommand("Input.emulateTouchFromMouseEvent", [{"name": "type", "type": "string", "optional": false}, {"name": "x", "type": "number", "optional": false}, {
    "name": "y",
    "type": "number",
    "optional": false
}, {"name": "deltaX", "type": "number", "optional": true}, {"name": "deltaY", "type": "number", "optional": true}, {"name": "modifiers", "type": "number", "optional": true}, {
    "name": "timestamp",
    "type": "number",
    "optional": true
}, {"name": "button", "type": "string", "optional": true}, {"name": "clickCount", "type": "number", "optional": true}], [], false);
InspectorBackend.registerLayerTreeDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "LayerTree");
InspectorBackend.registerEnum("LayerTree.ScrollRectType", {RepaintsOnScroll: "RepaintsOnScroll", TouchEventHandler: "TouchEventHandler", WheelEventHandler: "WheelEventHandler"});
InspectorBackend.registerEvent("LayerTree.layerTreeDidChange", ["layers"]);
InspectorBackend.registerEvent("LayerTree.layerPainted", ["layerId", "clip"]);
InspectorBackend.registerCommand("LayerTree.enable", [], [], false);
InspectorBackend.registerCommand("LayerTree.disable", [], [], false);
InspectorBackend.registerCommand("LayerTree.compositingReasons", [{"name": "layerId", "type": "string", "optional": false}], ["compositingReasons"], false);
InspectorBackend.registerCommand("LayerTree.makeSnapshot", [{"name": "layerId", "type": "string", "optional": false}], ["snapshotId"], false);
InspectorBackend.registerCommand("LayerTree.loadSnapshot", [{"name": "data", "type": "string", "optional": false}], ["snapshotId"], false);
InspectorBackend.registerCommand("LayerTree.releaseSnapshot", [{"name": "snapshotId", "type": "string", "optional": false}], [], false);
InspectorBackend.registerCommand("LayerTree.profileSnapshot", [{"name": "snapshotId", "type": "string", "optional": false}, {"name": "minRepeatCount", "type": "number", "optional": true}, {
    "name": "minDuration",
    "type": "number",
    "optional": true
}], ["timings"], false);
InspectorBackend.registerCommand("LayerTree.replaySnapshot", [{"name": "snapshotId", "type": "string", "optional": false}, {"name": "fromStep", "type": "number", "optional": true}, {
    "name": "toStep",
    "type": "number",
    "optional": true
}, {"name": "scale", "type": "number", "optional": true}], ["dataURL"], false);
InspectorBackend.registerCommand("LayerTree.snapshotCommandLog", [{"name": "snapshotId", "type": "string", "optional": false}], ["commandLog"], false);
InspectorBackend.registerGeolocationDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Geolocation");
InspectorBackend.registerCommand("Geolocation.setGeolocationOverride", [{"name": "latitude", "type": "number", "optional": true}, {"name": "longitude", "type": "number", "optional": true}, {
    "name": "accuracy",
    "type": "number",
    "optional": true
}], [], false);
InspectorBackend.registerCommand("Geolocation.clearGeolocationOverride", [], [], false);
InspectorBackend.registerDeviceOrientationDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "DeviceOrientation");
InspectorBackend.registerCommand("DeviceOrientation.setDeviceOrientationOverride", [{"name": "alpha", "type": "number", "optional": false}, {"name": "beta", "type": "number", "optional": false}, {
    "name": "gamma",
    "type": "number",
    "optional": false
}], [], false);
InspectorBackend.registerCommand("DeviceOrientation.clearDeviceOrientationOverride", [], [], false);
InspectorBackend.registerTracingDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Tracing");
InspectorBackend.registerEvent("Tracing.started", ["consoleTimeline", "sessionId"]);
InspectorBackend.registerEvent("Tracing.stopped", []);
InspectorBackend.registerEvent("Tracing.dataCollected", ["value"]);
InspectorBackend.registerEvent("Tracing.tracingComplete", []);
InspectorBackend.registerEvent("Tracing.bufferUsage", ["value"]);
InspectorBackend.registerCommand("Tracing.start", [{"name": "categories", "type": "string", "optional": false}, {"name": "options", "type": "string", "optional": false}, {
    "name": "bufferUsageReportingInterval",
    "type": "number",
    "optional": true
}], [], false);
InspectorBackend.registerCommand("Tracing.end", [], [], false);
InspectorBackend.registerCommand("Tracing.getCategories", [], ["categories"], false);
InspectorBackend.registerPowerDispatcher = InspectorBackend.registerDomainDispatcher.bind(InspectorBackend, "Power");
InspectorBackend.registerEvent("Power.dataAvailable", ["value"]);
InspectorBackend.registerCommand("Power.start", [], [], false);
InspectorBackend.registerCommand("Power.end", [], [], false);
InspectorBackend.registerCommand("Power.canProfilePower", [], ["result"], false);
InspectorBackend.registerCommand("Power.getAccuracyLevel", [], ["result"], false);
function InspectorFrontendHostAPI() {
}
InspectorFrontendHostAPI.ContextMenuDescriptor;
InspectorFrontendHostAPI.Events = {
    AppendedToURL: "appendedToURL",
    CanceledSaveURL: "canceledSaveURL",
    ContextMenuCleared: "contextMenuCleared",
    ContextMenuItemSelected: "contextMenuItemSelected",
    DeviceCountUpdated: "deviceCountUpdated",
    DevicesUpdated: "devicesUpdated",
    DispatchMessage: "dispatchMessage",
    EnterInspectElementMode: "enterInspectElementMode",
    FileSystemsLoaded: "fileSystemsLoaded",
    FileSystemRemoved: "fileSystemRemoved",
    FileSystemAdded: "fileSystemAdded",
    IndexingTotalWorkCalculated: "indexingTotalWorkCalculated",
    IndexingWorked: "indexingWorked",
    IndexingDone: "indexingDone",
    KeyEventUnhandled: "keyEventUnhandled",
    RevealSourceLine: "revealSourceLine",
    SavedURL: "savedURL",
    SearchCompleted: "searchCompleted",
    SetToolbarColors: "setToolbarColors",
    SetUseSoftMenu: "setUseSoftMenu",
    ShowConsole: "showConsole"
}
InspectorFrontendHostAPI.EventDescriptors = [[InspectorFrontendHostAPI.Events.AppendedToURL, ["url"]], [InspectorFrontendHostAPI.Events.CanceledSaveURL, ["url"]], [InspectorFrontendHostAPI.Events.ContextMenuCleared, []], [InspectorFrontendHostAPI.Events.ContextMenuItemSelected, ["id"]], [InspectorFrontendHostAPI.Events.DeviceCountUpdated, ["count"]], [InspectorFrontendHostAPI.Events.DevicesUpdated, ["devices"]], [InspectorFrontendHostAPI.Events.DispatchMessage, ["messageObject"]], [InspectorFrontendHostAPI.Events.EnterInspectElementMode, [], true], [InspectorFrontendHostAPI.Events.FileSystemsLoaded, ["fileSystems"]], [InspectorFrontendHostAPI.Events.FileSystemRemoved, ["fileSystemPath"]], [InspectorFrontendHostAPI.Events.FileSystemAdded, ["errorMessage", "fileSystem"]], [InspectorFrontendHostAPI.Events.IndexingTotalWorkCalculated, ["requestId", "fileSystemPath", "totalWork"]], [InspectorFrontendHostAPI.Events.IndexingWorked, ["requestId", "fileSystemPath", "worked"]], [InspectorFrontendHostAPI.Events.IndexingDone, ["requestId", "fileSystemPath"]], [InspectorFrontendHostAPI.Events.KeyEventUnhandled, ["event"], true], [InspectorFrontendHostAPI.Events.RevealSourceLine, ["url", "lineNumber", "columnNumber"], true], [InspectorFrontendHostAPI.Events.SavedURL, ["url"]], [InspectorFrontendHostAPI.Events.SearchCompleted, ["requestId", "fileSystemPath", "files"]], [InspectorFrontendHostAPI.Events.SetToolbarColors, ["backgroundColor", "color"]], [InspectorFrontendHostAPI.Events.SetUseSoftMenu, ["useSoftMenu"]], [InspectorFrontendHostAPI.Events.ShowConsole, [], true]];
InspectorFrontendHostAPI.prototype = {
    addFileSystem: function () {
    }, append: function (url, content) {
    }, indexPath: function (requestId, fileSystemPath) {
    }, getSelectionBackgroundColor: function () {
    }, getSelectionForegroundColor: function () {
    }, setInspectedPageBounds: function (bounds) {
    }, setContentsResizingStrategy: function (insets, minSize) {
    }, setWhitelistedShortcuts: function (shortcuts) {
    }, inspectElementCompleted: function () {
    }, moveWindowBy: function (x, y) {
    }, openInNewTab: function (url) {
    }, removeFileSystem: function (fileSystemPath) {
    }, requestFileSystems: function () {
    }, save: function (url, content, forceSaveAs) {
    }, searchInPath: function (requestId, fileSystemPath, query) {
    }, stopIndexing: function (requestId) {
    }, bringToFront: function () {
    }, openUrlOnRemoteDeviceAndInspect: function (browserId, url) {
    }, closeWindow: function () {
    }, copyText: function (text) {
    }, inspectedURLChanged: function (url) {
    }, isolatedFileSystem: function (fileSystemId, registeredName) {
    }, upgradeDraggedFileSystemPermissions: function (fileSystem) {
    }, platform: function () {
    }, port: function () {
    }, recordActionTaken: function (actionCode) {
    }, recordPanelShown: function (panelCode) {
    }, sendMessageToBackend: function (message) {
    }, sendMessageToEmbedder: function (message) {
    }, setDeviceCountUpdatesEnabled: function (enabled) {
    }, setDevicesUpdatesEnabled: function (enabled) {
    }, setInjectedScriptForOrigin: function (origin, script) {
    }, setIsDocked: function (isDocked, callback) {
    }, setZoomFactor: function (zoom) {
    }, zoomFactor: function () {
    }, zoomIn: function () {
    }, zoomOut: function () {
    }, resetZoom: function () {
    }, showContextMenuAtPoint: function (x, y, items) {
    }, isUnderTest: function () {
    }, isHostedMode: function () {
    }
}
WebInspector.InspectorFrontendHostStub = function () {
}
WebInspector.InspectorFrontendHostStub.prototype = {
    getSelectionBackgroundColor: function () {
        return "#6e86ff";
    }, getSelectionForegroundColor: function () {
        return "#ffffff";
    }, platform: function () {
        var match = navigator.userAgent.match(/Windows NT/);
        if (match)
            return "windows";
        match = navigator.userAgent.match(/Mac OS X/);
        if (match)
            return "mac";
        return "linux";
    }, port: function () {
        return "unknown";
    }, bringToFront: function () {
        this._windowVisible = true;
    }, closeWindow: function () {
        this._windowVisible = false;
    }, setIsDocked: function (isDocked, callback) {
    }, setInspectedPageBounds: function (bounds) {
    }, setContentsResizingStrategy: function (insets, minSize) {
    }, inspectElementCompleted: function () {
    }, moveWindowBy: function (x, y) {
    }, setInjectedScriptForOrigin: function (origin, script) {
    }, inspectedURLChanged: function (url) {
        document.title = WebInspector.UIString("Developer Tools - %s", url);
    }, copyText: function (text) {
        WebInspector.console.error("Clipboard is not enabled in hosted mode. Please inspect using chrome://inspect");
    }, openInNewTab: function (url) {
        window.open(url, "_blank");
    }, save: function (url, content, forceSaveAs) {
        WebInspector.console.error("Saving files is not enabled in hosted mode. Please inspect using chrome://inspect");
        this.events.dispatchEventToListeners(InspectorFrontendHostAPI.Events.CanceledSaveURL, url);
    }, append: function (url, content) {
        WebInspector.console.error("Saving files is not enabled in hosted mode. Please inspect using chrome://inspect");
    }, sendMessageToBackend: function (message) {
    }, sendMessageToEmbedder: function (message) {
    }, recordActionTaken: function (actionCode) {
    }, recordPanelShown: function (panelCode) {
    }, requestFileSystems: function () {
    }, addFileSystem: function () {
    }, removeFileSystem: function (fileSystemPath) {
    }, isolatedFileSystem: function (fileSystemId, registeredName) {
        return null;
    }, upgradeDraggedFileSystemPermissions: function (fileSystem) {
    }, indexPath: function (requestId, fileSystemPath) {
    }, stopIndexing: function (requestId) {
    }, searchInPath: function (requestId, fileSystemPath, query) {
    }, setZoomFactor: function (zoom) {
    }, zoomFactor: function () {
        return 1;
    }, zoomIn: function () {
    }, zoomOut: function () {
    }, resetZoom: function () {
    }, setWhitelistedShortcuts: function (shortcuts) {
    }, isUnderTest: function () {
        return false;
    }, openUrlOnRemoteDeviceAndInspect: function (browserId, url) {
    }, setDeviceCountUpdatesEnabled: function (enabled) {
    }, setDevicesUpdatesEnabled: function (enabled) {
    }, showContextMenuAtPoint: function (x, y, items) {
        throw"Soft context menu should be used";
    }, isHostedMode: function () {
        return true;
    }
};
var InspectorFrontendHost = window.InspectorFrontendHost || null;
(function () {
    if (!InspectorFrontendHost) {
        InspectorFrontendHost = new WebInspector.InspectorFrontendHostStub();
    } else {
        var proto = WebInspector.InspectorFrontendHostStub.prototype;
        for (var name in proto) {
            var value = proto[name];
            if (typeof value !== "function" || InspectorFrontendHost[name])
                continue;
            InspectorFrontendHost[name] = stub.bind(null, name);
        }
    }
    function stub(name) {
        console.error("Incompatible embedder: method InspectorFrontendHost." + name + " is missing. Using stub instead.");
        var args = Array.prototype.slice.call(arguments, 1);
        return proto[name].apply(InspectorFrontendHost, args);
    }

    InspectorFrontendHost.events = new WebInspector.Object();
})();
function InspectorFrontendAPIImpl() {
    this._isLoaded = false;
    this._pendingCommands = [];
    this._debugFrontend = !!WebInspector.queryParam("debugFrontend");
    var descriptors = InspectorFrontendHostAPI.EventDescriptors;
    for (var i = 0; i < descriptors.length; ++i)
        this[descriptors[i][0]] = this._dispatch.bind(this, descriptors[i][0], descriptors[i][1], descriptors[i][2]);
}
InspectorFrontendAPIImpl.prototype = {
    loadCompleted: function () {
        this._isLoaded = true;
        for (var i = 0; i < this._pendingCommands.length; ++i)
            this._pendingCommands[i]();
        this._pendingCommands = [];
        if (window.opener)
            window.opener.postMessage(["loadCompleted"], "*");
    }, _dispatch: function (name, signature, runOnceLoaded) {
        var params = Array.prototype.slice.call(arguments, 3);
        if (this._debugFrontend)
            setImmediate(innerDispatch.bind(this)); else
            innerDispatch.call(this);
        function innerDispatch() {
            if (runOnceLoaded)
                this._runOnceLoaded(dispatchAfterLoad); else
                dispatchAfterLoad();
            function dispatchAfterLoad() {
                if (signature.length < 2) {
                    InspectorFrontendHost.events.dispatchEventToListeners(name, params[0]);
                    return;
                }
                var data = {};
                for (var i = 0; i < signature.length; ++i)
                    data[signature[i]] = params[i];
                InspectorFrontendHost.events.dispatchEventToListeners(name, data);
            }
        }
    }, _runOnceLoaded: function (command) {
        if (this._isLoaded) {
            command();
            return;
        }
        this._pendingCommands.push(command);
    }, embedderMessageAck: function (id, error) {
        InspectorFrontendHost["embedderMessageAck"](id, error);
    }
}
var InspectorFrontendAPI = new InspectorFrontendAPIImpl();
WebInspector.platform = function () {
    if (!WebInspector._platform)
        WebInspector._platform = InspectorFrontendHost.platform();
    return WebInspector._platform;
}
WebInspector.isMac = function () {
    if (typeof WebInspector._isMac === "undefined")
        WebInspector._isMac = WebInspector.platform() === "mac";
    return WebInspector._isMac;
}
WebInspector.isWin = function () {
    if (typeof WebInspector._isWin === "undefined")
        WebInspector._isWin = WebInspector.platform() === "windows";
    return WebInspector._isWin;
}
WebInspector.PlatformFlavor = {WindowsVista: "windows-vista", MacTiger: "mac-tiger", MacLeopard: "mac-leopard", MacSnowLeopard: "mac-snowleopard", MacLion: "mac-lion"}
WebInspector.platformFlavor = function () {
    function detectFlavor() {
        const userAgent = navigator.userAgent;
        if (WebInspector.platform() === "windows") {
            var match = userAgent.match(/Windows NT (\d+)\.(?:\d+)/);
            if (match && match[1] >= 6)
                return WebInspector.PlatformFlavor.WindowsVista;
            return null;
        } else if (WebInspector.platform() === "mac") {
            var match = userAgent.match(/Mac OS X\s*(?:(\d+)_(\d+))?/);
            if (!match || match[1] != 10)
                return WebInspector.PlatformFlavor.MacSnowLeopard;
            switch (Number(match[2])) {
                case 4:
                    return WebInspector.PlatformFlavor.MacTiger;
                case 5:
                    return WebInspector.PlatformFlavor.MacLeopard;
                case 6:
                    return WebInspector.PlatformFlavor.MacSnowLeopard;
                case 7:
                    return WebInspector.PlatformFlavor.MacLion;
                case 8:
                case 9:
                default:
                    return "";
            }
        }
    }

    if (!WebInspector._platformFlavor)
        WebInspector._platformFlavor = detectFlavor();
    return WebInspector._platformFlavor;
}
WebInspector.port = function () {
    if (!WebInspector._port)
        WebInspector._port = InspectorFrontendHost.port();
    return WebInspector._port;
}
WebInspector.fontFamily = function () {
    if (WebInspector._fontFamily)
        return WebInspector._fontFamily;
    switch (WebInspector.platform()) {
        case"linux":
            WebInspector._fontFamily = "Ubuntu, Arial, sans-serif";
            break;
        case"mac":
            WebInspector._fontFamily = "'Lucida Grande', sans-serif";
            break;
        case"windows":
            WebInspector._fontFamily = "'Segoe UI', Tahoma, sans-serif";
            break;
    }
    return WebInspector._fontFamily;
}
WebInspector.monospaceFontFamily = function () {
    if (WebInspector._monospaceFontFamily)
        return WebInspector._monospaceFontFamily;
    switch (WebInspector.platform()) {
        case"linux":
            WebInspector._monospaceFontFamily = "dejavu sans mono, monospace";
            break;
        case"mac":
            WebInspector._monospaceFontFamily = "Menlo, monospace";
            break;
        case"windows":
            WebInspector._monospaceFontFamily = "Consolas, monospace";
            break;
    }
    return WebInspector._monospaceFontFamily;
}
WebInspector.isWorkerFrontend = function () {
    return !!WebInspector.queryParam("dedicatedWorkerId") || !!WebInspector.queryParam("isSharedWorker");
}
WebInspector.UserMetrics = function () {
    for (var actionName in WebInspector.UserMetrics._ActionCodes) {
        var actionCode = WebInspector.UserMetrics._ActionCodes[actionName];
        this[actionName] = new WebInspector.UserMetrics._Recorder(actionCode);
    }
}
WebInspector.UserMetrics._ActionCodes = {
    WindowDocked: 1,
    WindowUndocked: 2,
    ScriptsBreakpointSet: 3,
    TimelineStarted: 4,
    ProfilesCPUProfileTaken: 5,
    ProfilesHeapProfileTaken: 6,
    AuditsStarted: 7,
    ConsoleEvaluated: 8,
    FileSavedInWorkspace: 9,
    DeviceModeEnabled: 10
}
WebInspector.UserMetrics._PanelCodes = {elements: 1, resources: 2, network: 3, sources: 4, timeline: 5, profiles: 6, audits: 7, console: 8}
WebInspector.UserMetrics.UserAction = "UserAction";
WebInspector.UserMetrics.UserActionNames = {
    ForcedElementState: "forcedElementState",
    FileSaved: "fileSaved",
    RevertRevision: "revertRevision",
    ApplyOriginalContent: "applyOriginalContent",
    TogglePrettyPrint: "togglePrettyPrint",
    SetBreakpoint: "setBreakpoint",
    OpenSourceLink: "openSourceLink",
    NetworkSort: "networkSort",
    NetworkRequestSelected: "networkRequestSelected",
    NetworkRequestTabSelected: "networkRequestTabSelected",
    HeapSnapshotFilterChanged: "heapSnapshotFilterChanged"
};
WebInspector.UserMetrics.prototype = {
    panelShown: function (panelName) {
        InspectorFrontendHost.recordPanelShown(WebInspector.UserMetrics._PanelCodes[panelName] || 0);
    }
}
WebInspector.UserMetrics._Recorder = function (actionCode) {
    this._actionCode = actionCode;
}
WebInspector.UserMetrics._Recorder.prototype = {
    record: function () {
        InspectorFrontendHost.recordActionTaken(this._actionCode);
    }
}
WebInspector.userMetrics = new WebInspector.UserMetrics();
WebInspector.profilingLock = function () {
    if (!WebInspector._profilingLock)
        WebInspector._profilingLock = new WebInspector.Lock();
    return WebInspector._profilingLock;
}
WebInspector.Target = function (name, connection, callback) {
    Protocol.Agents.call(this, connection.agentsMap());
    this._weakReference = new WeakReference(this);
    this._name = name;
    this._connection = connection;
    connection.addEventListener(InspectorBackendClass.Connection.Events.Disconnected, this._onDisconnect, this);
    this._id = WebInspector.Target._nextId++;
    this._modelByConstructor = new Map();
    this._capabilities = {};
    this.pageAgent().canScreencast(this._initializeCapability.bind(this, WebInspector.Target.Capabilities.CanScreencast, null));
    if (WebInspector.experimentsSettings.timelinePowerProfiler.isEnabled())
        this.powerAgent().canProfilePower(this._initializeCapability.bind(this, WebInspector.Target.Capabilities.CanProfilePower, null));
    this.workerAgent().canInspectWorkers(this._initializeCapability.bind(this, WebInspector.Target.Capabilities.CanInspectWorkers, this._loadedWithCapabilities.bind(this, callback)));
    if (WebInspector.experimentsSettings.timelineOnTraceEvents.isEnabled())
        this.consoleAgent().setTracingBasedTimeline(true);
}
WebInspector.Target.Capabilities = {CanScreencast: "CanScreencast", HasTouchInputs: "HasTouchInputs", CanProfilePower: "CanProfilePower", CanInspectWorkers: "CanInspectWorkers"}
WebInspector.Target._nextId = 1;
WebInspector.Target.prototype = {
    id: function () {
        return this._id;
    }, name: function () {
        return this._name;
    }, weakReference: function () {
        return this._weakReference;
    }, _initializeCapability: function (name, callback, error, result) {
        this._capabilities[name] = result;
        if (callback)
            callback();
    }, hasCapability: function (capability) {
        return !!this._capabilities[capability];
    }, _loadedWithCapabilities: function (callback) {
        this.consoleModel = new WebInspector.ConsoleModel(this);
        this.networkManager = new WebInspector.NetworkManager(this);
        this.resourceTreeModel = new WebInspector.ResourceTreeModel(this);
        if (!WebInspector.resourceTreeModel)
            WebInspector.resourceTreeModel = this.resourceTreeModel;
        this.networkLog = new WebInspector.NetworkLog(this);
        if (!WebInspector.networkLog)
            WebInspector.networkLog = this.networkLog;
        this.debuggerModel = new WebInspector.DebuggerModel(this);
        if (!WebInspector.debuggerModel)
            WebInspector.debuggerModel = this.debuggerModel;
        this.runtimeModel = new WebInspector.RuntimeModel(this);
        if (!WebInspector.runtimeModel)
            WebInspector.runtimeModel = this.runtimeModel;
        this.domModel = new WebInspector.DOMModel(this);
        this.cssModel = new WebInspector.CSSStyleModel(this);
        if (!WebInspector.cssModel)
            WebInspector.cssModel = this.cssModel;
        this.workerManager = new WebInspector.WorkerManager(this, this.hasCapability(WebInspector.Target.Capabilities.CanInspectWorkers));
        if (!WebInspector.workerManager)
            WebInspector.workerManager = this.workerManager;
        if (this.hasCapability(WebInspector.Target.Capabilities.CanProfilePower))
            WebInspector.powerProfiler = new WebInspector.PowerProfiler();
        this.timelineManager = new WebInspector.TimelineManager(this);
        this.databaseModel = new WebInspector.DatabaseModel(this);
        if (!WebInspector.databaseModel)
            WebInspector.databaseModel = this.databaseModel;
        this.domStorageModel = new WebInspector.DOMStorageModel(this);
        if (!WebInspector.domStorageModel)
            WebInspector.domStorageModel = this.domStorageModel;
        this.cpuProfilerModel = new WebInspector.CPUProfilerModel(this);
        if (!WebInspector.cpuProfilerModel)
            WebInspector.cpuProfilerModel = this.cpuProfilerModel;
        this.heapProfilerModel = new WebInspector.HeapProfilerModel(this);
        if (callback)
            callback(this);
    }, registerDispatcher: function (domain, dispatcher) {
        this._connection.registerDispatcher(domain, dispatcher);
    }, isWorkerTarget: function () {
        return !this.hasCapability(WebInspector.Target.Capabilities.CanInspectWorkers);
    }, isMobile: function () {
        return this.hasCapability(WebInspector.Target.Capabilities.CanScreencast);
    }, _onDisconnect: function () {
        WebInspector.targetManager.removeTarget(this);
        this._dispose();
    }, _dispose: function () {
        this._weakReference.clear();
        this.debuggerModel.dispose();
        this.networkManager.dispose();
        this.cpuProfilerModel.dispose();
    }, isDetached: function () {
        return this._connection.isClosed();
    }, __proto__: Protocol.Agents.prototype
}
WebInspector.SDKObject = function (target) {
    WebInspector.Object.call(this);
    this._target = target;
}
WebInspector.SDKObject.prototype = {
    target: function () {
        return this._target;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.SDKModel = function (modelClass, target) {
    WebInspector.SDKObject.call(this, target);
    target._modelByConstructor.put(modelClass, this);
}
WebInspector.SDKModel.prototype = {__proto__: WebInspector.SDKObject.prototype}
WebInspector.TargetManager = function () {
    this._targets = [];
    this._observers = [];
    this._listeners = {};
}
WebInspector.TargetManager.prototype = {
    addModelListener: function (modelClass, eventType, listener, thisObject) {
        for (var i = 0; i < this._targets.length; ++i) {
            var model = this._targets[i]._modelByConstructor.get(modelClass);
            model.addEventListener(eventType, listener, thisObject);
        }
        if (!this._listeners[eventType])
            this._listeners[eventType] = [];
        this._listeners[eventType].push({modelClass: modelClass, thisObject: thisObject, listener: listener});
    }, removeModelListener: function (modelClass, eventType, listener, thisObject) {
        if (!this._listeners[eventType])
            return;
        for (var i = 0; i < this._targets.length; ++i) {
            var model = this._targets[i]._modelByConstructor.get(modelClass);
            model.removeEventListener(eventType, listener, thisObject);
        }
        var listeners = this._listeners[eventType];
        for (var i = 0; i < listeners.length; ++i) {
            if (listeners[i].modelClass === modelClass && listeners[i].listener === listener && listeners[i].thisObject === thisObject)
                listeners.splice(i--, 1);
        }
        if (!listeners.length)
            delete this._listeners[eventType];
    }, observeTargets: function (targetObserver) {
        this.targets().forEach(targetObserver.targetAdded.bind(targetObserver));
        this._observers.push(targetObserver);
    }, unobserveTargets: function (targetObserver) {
        this._observers.remove(targetObserver);
    }, createTarget: function (name, connection, callback) {
        var target = new WebInspector.Target(name, connection, callbackWrapper.bind(this));

        function callbackWrapper(newTarget) {
            this.addTarget(newTarget);
            if (callback)
                callback(newTarget);
        }
    }, addTarget: function (target) {
        this._targets.push(target);
        var copy = this._observers.slice();
        for (var i = 0; i < copy.length; ++i)
            copy[i].targetAdded(target);
        for (var eventType in this._listeners) {
            var listeners = this._listeners[eventType];
            for (var i = 0; i < listeners.length; ++i) {
                var model = target._modelByConstructor.get(listeners[i].modelClass);
                model.addEventListener(eventType, listeners[i].listener, listeners[i].thisObject);
            }
        }
    }, removeTarget: function (target) {
        this._targets.remove(target);
        var copy = this._observers.slice();
        for (var i = 0; i < copy.length; ++i)
            copy[i].targetRemoved(target);
        for (var eventType in this._listeners) {
            var listeners = this._listeners[eventType];
            for (var i = 0; i < listeners.length; ++i) {
                var model = target._modelByConstructor.get(listeners[i].modelClass);
                model.removeEventListener(eventType, listeners[i].listener, listeners[i].thisObject);
            }
        }
    }, targets: function () {
        return this._targets.slice();
    }, mainTarget: function () {
        return this._targets[0];
    }
}
WebInspector.TargetManager.Observer = function () {
}
WebInspector.TargetManager.Observer.prototype = {
    targetAdded: function (target) {
    }, targetRemoved: function (target) {
    },
}
WebInspector.targetManager = new WebInspector.TargetManager();
WebInspector.BlackboxSupport = function () {
}
WebInspector.BlackboxSupport._urlToRegExpString = function (url) {
    var name = new WebInspector.ParsedURL(url).lastPathComponent;
    return "/" + name.escapeForRegExp() + (url.endsWith(name) ? "$" : "\\b");
}
WebInspector.BlackboxSupport.blackboxURL = function (url) {
    var regexPatterns = WebInspector.settings.skipStackFramesPattern.getAsArray();
    var regexValue = WebInspector.BlackboxSupport._urlToRegExpString(url);
    var found = false;
    for (var i = 0; i < regexPatterns.length; ++i) {
        var item = regexPatterns[i];
        if (item.pattern === regexValue) {
            item.disabled = false;
            found = true;
            break;
        }
    }
    if (!found)
        regexPatterns.push({pattern: regexValue});
    WebInspector.settings.skipStackFramesPattern.setAsArray(regexPatterns);
}
WebInspector.BlackboxSupport.unblackboxURL = function (url) {
    var regexPatterns = WebInspector.settings.skipStackFramesPattern.getAsArray();
    var regexValue = WebInspector.BlackboxSupport._urlToRegExpString(url);
    regexPatterns = regexPatterns.filter(function (item) {
        return item.pattern !== regexValue;
    });
    for (var i = 0; i < regexPatterns.length; ++i) {
        var item = regexPatterns[i];
        if (item.disabled)
            continue;
        try {
            var regex = new RegExp(item.pattern);
            if (regex.test(url))
                item.disabled = true;
        } catch (e) {
        }
    }
    WebInspector.settings.skipStackFramesPattern.setAsArray(regexPatterns);
}
WebInspector.BlackboxSupport.isBlackboxedURL = function (url) {
    var regex = WebInspector.settings.skipStackFramesPattern.asRegExp();
    return (url && regex) ? regex.test(url) : false;
}
WebInspector.Context = function () {
    this._flavors = new Map();
    this._eventDispatchers = new Map();
}
WebInspector.Context.Events = {FlavorChanged: "FlavorChanged"}
WebInspector.Context.prototype = {
    setFlavor: function (flavorType, flavorValue) {
        var value = this._flavors.get(flavorType) || null;
        if (value === flavorValue)
            return;
        if (flavorValue)
            this._flavors.put(flavorType, flavorValue); else
            this._flavors.remove(flavorType);
        this._dispatchFlavorChange(flavorType, flavorValue);
    }, _dispatchFlavorChange: function (flavorType, flavorValue) {
        var dispatcher = this._eventDispatchers.get(flavorType);
        if (!dispatcher)
            return;
        dispatcher.dispatchEventToListeners(WebInspector.Context.Events.FlavorChanged, flavorValue);
    }, addFlavorChangeListener: function (flavorType, listener, thisObject) {
        var dispatcher = this._eventDispatchers.get(flavorType);
        if (!dispatcher) {
            dispatcher = new WebInspector.Object();
            this._eventDispatchers.put(flavorType, dispatcher);
        }
        dispatcher.addEventListener(WebInspector.Context.Events.FlavorChanged, listener, thisObject);
    }, removeFlavorChangeListener: function (flavorType, listener, thisObject) {
        var dispatcher = this._eventDispatchers.get(flavorType);
        if (!dispatcher)
            return;
        dispatcher.removeEventListener(WebInspector.Context.Events.FlavorChanged, listener, thisObject);
        if (!dispatcher.hasEventListeners(WebInspector.Context.Events.FlavorChanged))
            this._eventDispatchers.remove(flavorType);
    }, flavor: function (flavorType) {
        return this._flavors.get(flavorType) || null;
    }, flavors: function () {
        return this._flavors.keys();
    }, applicableExtensions: function (extensions) {
        var targetExtensionSet = new Set();
        var availableFlavors = this.flavors();
        extensions.forEach(function (extension) {
            if (self.runtime.isExtensionApplicableToContextTypes(extension, availableFlavors))
                targetExtensionSet.add(extension);
        });
        return targetExtensionSet;
    }
}
WebInspector.context = new WebInspector.Context();
WebInspector.ExecutionContextSelector = function () {
    WebInspector.targetManager.observeTargets(this);
    WebInspector.context.addFlavorChangeListener(WebInspector.ExecutionContext, this._executionContextChanged, this);
    WebInspector.context.addFlavorChangeListener(WebInspector.Target, this._targetChanged, this);
    WebInspector.targetManager.addModelListener(WebInspector.RuntimeModel, WebInspector.RuntimeModel.Events.ExecutionContextCreated, this._onExecutionContextCreated, this);
    WebInspector.targetManager.addModelListener(WebInspector.RuntimeModel, WebInspector.RuntimeModel.Events.ExecutionContextDestroyed, this._onExecutionContextDestroyed, this);
}
WebInspector.ExecutionContextSelector.prototype = {
    targetAdded: function (target) {
        if (!WebInspector.context.flavor(WebInspector.Target))
            WebInspector.context.setFlavor(WebInspector.Target, target);
    }, targetRemoved: function (target) {
        var currentExecutionContext = WebInspector.context.flavor(WebInspector.ExecutionContext);
        if (currentExecutionContext && currentExecutionContext.target() === target)
            this._currentExecutionContextGone();
        var targets = WebInspector.targetManager.targets();
        if (WebInspector.context.flavor(WebInspector.Target) === target && targets.length)
            WebInspector.context.setFlavor(WebInspector.Target, targets[0]);
    }, _executionContextChanged: function (event) {
        var newContext = (event.data);
        if (newContext)
            WebInspector.context.setFlavor(WebInspector.Target, newContext.target());
    }, _targetChanged: function (event) {
        var newTarget = (event.data);
        var currentContext = WebInspector.context.flavor(WebInspector.ExecutionContext);
        if (!newTarget || (currentContext && currentContext.target() === newTarget))
            return;
        var executionContexts = newTarget.runtimeModel.executionContexts();
        if (!executionContexts.length)
            return;
        var newContext = executionContexts[0];
        for (var i = 1; i < executionContexts.length; ++i) {
            if (executionContexts[i].isMainWorldContext)
                newContext = executionContexts[i];
        }
        WebInspector.context.setFlavor(WebInspector.ExecutionContext, newContext);
    }, _onExecutionContextCreated: function (event) {
        var executionContext = (event.data);
        if (!WebInspector.context.flavor(WebInspector.ExecutionContext))
            WebInspector.context.setFlavor(WebInspector.ExecutionContext, executionContext);
    }, _onExecutionContextDestroyed: function (event) {
        var executionContext = (event.data);
        if (WebInspector.context.flavor(WebInspector.ExecutionContext) === executionContext)
            this._currentExecutionContextGone();
    }, _currentExecutionContextGone: function () {
        var targets = WebInspector.targetManager.targets();
        var newContext = null;
        for (var i = 0; i < targets.length; ++i) {
            var executionContexts = targets[i].runtimeModel.executionContexts();
            if (executionContexts.length) {
                newContext = executionContexts[0];
                break;
            }
        }
        WebInspector.context.setFlavor(WebInspector.ExecutionContext, newContext);
    }
}
WebInspector.ExecutionContextSelector.completionsForTextPromptInCurrentContext = function (proxyElement, wordRange, force, completionsReadyCallback) {
    var executionContext = WebInspector.context.flavor(WebInspector.ExecutionContext);
    if (!executionContext) {
        completionsReadyCallback([]);
        return;
    }
    var expressionRange = wordRange.startContainer.rangeOfWord(wordRange.startOffset, " =:[({;,!+-*/&|^<>", proxyElement, "backward");
    var expressionString = expressionRange.toString();
    var prefix = wordRange.toString();
    executionContext.completionsForExpression(expressionString, prefix, force, completionsReadyCallback);
}
WebInspector.View = function () {
    this.element = document.createElementWithClass("div", "view");
    this.element.__view = this;
    this._visible = true;
    this._isRoot = false;
    this._isShowing = false;
    this._children = [];
    this._hideOnDetach = false;
    this._cssFiles = [];
    this._notificationDepth = 0;
}
WebInspector.View._cssFileToVisibleViewCount = {};
WebInspector.View._cssFileToStyleElement = {};
WebInspector.View._cssUnloadTimeout = 2000;
WebInspector.View._buildSourceURL = function (cssFile) {
    return "\n/*# sourceURL=" + WebInspector.ParsedURL.completeURL(window.location.href, cssFile) + " */";
}
WebInspector.View.createStyleElement = function (cssFile) {
    var styleElement = document.createElement("style");
    styleElement.type = "text/css";
    styleElement.textContent = loadResource(cssFile) + WebInspector.View._buildSourceURL(cssFile);
    document.head.insertBefore(styleElement, document.head.firstChild);
    return styleElement;
}
WebInspector.View.prototype = {
    markAsRoot: function () {
        WebInspector.View.__assert(!this.element.parentElement, "Attempt to mark as root attached node");
        this._isRoot = true;
    }, parentView: function () {
        return this._parentView;
    }, children: function () {
        return this._children;
    }, isShowing: function () {
        return this._isShowing;
    }, setHideOnDetach: function () {
        this._hideOnDetach = true;
    }, _inNotification: function () {
        return !!this._notificationDepth || (this._parentView && this._parentView._inNotification());
    }, _parentIsShowing: function () {
        if (this._isRoot)
            return true;
        return this._parentView && this._parentView.isShowing();
    }, _callOnVisibleChildren: function (method) {
        var copy = this._children.slice();
        for (var i = 0; i < copy.length; ++i) {
            if (copy[i]._parentView === this && copy[i]._visible)
                method.call(copy[i]);
        }
    }, _processWillShow: function () {
        this._loadCSSIfNeeded();
        this._callOnVisibleChildren(this._processWillShow);
        this._isShowing = true;
    }, _processWasShown: function () {
        if (this._inNotification())
            return;
        this.restoreScrollPositions();
        this._notify(this.wasShown);
        this._callOnVisibleChildren(this._processWasShown);
    }, _processWillHide: function () {
        if (this._inNotification())
            return;
        this.storeScrollPositions();
        this._callOnVisibleChildren(this._processWillHide);
        this._notify(this.willHide);
        this._isShowing = false;
    }, _processWasHidden: function () {
        this._disableCSSIfNeeded();
        this._callOnVisibleChildren(this._processWasHidden);
    }, _processOnResize: function () {
        if (this._inNotification())
            return;
        if (!this.isShowing())
            return;
        this._notify(this.onResize);
        this._callOnVisibleChildren(this._processOnResize);
    }, _notify: function (notification) {
        ++this._notificationDepth;
        try {
            notification.call(this);
        } finally {
            --this._notificationDepth;
        }
    }, wasShown: function () {
    }, willHide: function () {
    }, onResize: function () {
    }, onLayout: function () {
    }, show: function (parentElement, insertBefore) {
        WebInspector.View.__assert(parentElement, "Attempt to attach view with no parent element");
        if (this.element.parentElement !== parentElement) {
            if (this.element.parentElement)
                this.detach();
            var currentParent = parentElement;
            while (currentParent && !currentParent.__view)
                currentParent = currentParent.parentElement;
            if (currentParent) {
                this._parentView = currentParent.__view;
                this._parentView._children.push(this);
                this._isRoot = false;
            } else
                WebInspector.View.__assert(this._isRoot, "Attempt to attach view to orphan node");
        } else if (this._visible) {
            return;
        }
        this._visible = true;
        if (this._parentIsShowing())
            this._processWillShow();
        this.element.classList.add("visible");
        if (this.element.parentElement !== parentElement) {
            WebInspector.View._incrementViewCounter(parentElement, this.element);
            if (insertBefore)
                WebInspector.View._originalInsertBefore.call(parentElement, this.element, insertBefore); else
                WebInspector.View._originalAppendChild.call(parentElement, this.element);
        }
        if (this._parentIsShowing())
            this._processWasShown();
        if (this._parentView && this._hasNonZeroConstraints())
            this._parentView.invalidateConstraints(); else
            this._processOnResize();
    }, detach: function (overrideHideOnDetach) {
        var parentElement = this.element.parentElement;
        if (!parentElement)
            return;
        if (this._parentIsShowing())
            this._processWillHide();
        if (this._hideOnDetach && !overrideHideOnDetach) {
            this.element.classList.remove("visible");
            this._visible = false;
            if (this._parentIsShowing())
                this._processWasHidden();
            if (this._parentView && this._hasNonZeroConstraints())
                this._parentView.invalidateConstraints();
            return;
        }
        WebInspector.View._decrementViewCounter(parentElement, this.element);
        WebInspector.View._originalRemoveChild.call(parentElement, this.element);
        this._visible = false;
        if (this._parentIsShowing())
            this._processWasHidden();
        if (this._parentView) {
            var childIndex = this._parentView._children.indexOf(this);
            WebInspector.View.__assert(childIndex >= 0, "Attempt to remove non-child view");
            this._parentView._children.splice(childIndex, 1);
            var parent = this._parentView;
            this._parentView = null;
            if (this._hasNonZeroConstraints())
                parent.invalidateConstraints();
        } else
            WebInspector.View.__assert(this._isRoot, "Removing non-root view from DOM");
    }, detachChildViews: function () {
        var children = this._children.slice();
        for (var i = 0; i < children.length; ++i)
            children[i].detach();
    }, elementsToRestoreScrollPositionsFor: function () {
        return [this.element];
    }, storeScrollPositions: function () {
        var elements = this.elementsToRestoreScrollPositionsFor();
        for (var i = 0; i < elements.length; ++i) {
            var container = elements[i];
            container._scrollTop = container.scrollTop;
            container._scrollLeft = container.scrollLeft;
        }
    }, restoreScrollPositions: function () {
        var elements = this.elementsToRestoreScrollPositionsFor();
        for (var i = 0; i < elements.length; ++i) {
            var container = elements[i];
            if (container._scrollTop)
                container.scrollTop = container._scrollTop;
            if (container._scrollLeft)
                container.scrollLeft = container._scrollLeft;
        }
    }, doResize: function () {
        if (!this.isShowing())
            return;
        if (!this._inNotification())
            this._callOnVisibleChildren(this._processOnResize);
    }, doLayout: function () {
        if (!this.isShowing())
            return;
        this._notify(this.onLayout);
        this.doResize();
    }, registerRequiredCSS: function (cssFile) {
        this._cssFiles.push(cssFile);
    }, _loadCSSIfNeeded: function () {
        for (var i = 0; i < this._cssFiles.length; ++i) {
            var cssFile = this._cssFiles[i];
            var viewsWithCSSFile = WebInspector.View._cssFileToVisibleViewCount[cssFile];
            WebInspector.View._cssFileToVisibleViewCount[cssFile] = (viewsWithCSSFile || 0) + 1;
            if (!viewsWithCSSFile)
                this._doLoadCSS(cssFile);
        }
    }, _doLoadCSS: function (cssFile) {
        var styleElement = WebInspector.View._cssFileToStyleElement[cssFile];
        if (styleElement) {
            styleElement.disabled = false;
            return;
        }
        styleElement = WebInspector.View.createStyleElement(cssFile);
        WebInspector.View._cssFileToStyleElement[cssFile] = styleElement;
    }, _disableCSSIfNeeded: function () {
        var scheduleUnload = !!WebInspector.View._cssUnloadTimer;
        for (var i = 0; i < this._cssFiles.length; ++i) {
            var cssFile = this._cssFiles[i];
            if (!--WebInspector.View._cssFileToVisibleViewCount[cssFile])
                scheduleUnload = true;
        }
        function doUnloadCSS() {
            delete WebInspector.View._cssUnloadTimer;
            for (cssFile in WebInspector.View._cssFileToVisibleViewCount) {
                if (WebInspector.View._cssFileToVisibleViewCount.hasOwnProperty(cssFile) && !WebInspector.View._cssFileToVisibleViewCount[cssFile])
                    WebInspector.View._cssFileToStyleElement[cssFile].disabled = true;
            }
        }

        if (scheduleUnload && !WebInspector.View._cssUnloadTimer)
            WebInspector.View._cssUnloadTimer = setTimeout(doUnloadCSS, WebInspector.View._cssUnloadTimeout);
    }, printViewHierarchy: function () {
        var lines = [];
        this._collectViewHierarchy("", lines);
        console.log(lines.join("\n"));
    }, _collectViewHierarchy: function (prefix, lines) {
        lines.push(prefix + "[" + this.element.className + "]" + (this._children.length ? " {" : ""));
        for (var i = 0; i < this._children.length; ++i)
            this._children[i]._collectViewHierarchy(prefix + "    ", lines);
        if (this._children.length)
            lines.push(prefix + "}");
    }, defaultFocusedElement: function () {
        return this._defaultFocusedElement || this.element;
    }, setDefaultFocusedElement: function (element) {
        this._defaultFocusedElement = element;
    }, focus: function () {
        var element = this.defaultFocusedElement();
        if (!element || element.isAncestor(document.activeElement))
            return;
        WebInspector.setCurrentFocusElement(element);
    }, hasFocus: function () {
        var activeElement = document.activeElement;
        return activeElement && activeElement.isSelfOrDescendant(this.element);
    }, measurePreferredSize: function () {
        this._loadCSSIfNeeded();
        WebInspector.View._originalAppendChild.call(document.body, this.element);
        this.element.positionAt(0, 0);
        var result = new Size(this.element.offsetWidth, this.element.offsetHeight);
        this.element.positionAt(undefined, undefined);
        WebInspector.View._originalRemoveChild.call(document.body, this.element);
        this._disableCSSIfNeeded();
        return result;
    }, calculateConstraints: function () {
        return new Constraints(new Size(0, 0));
    }, constraints: function () {
        if (typeof this._constraints !== "undefined")
            return this._constraints;
        if (typeof this._cachedConstraints === "undefined")
            this._cachedConstraints = this.calculateConstraints();
        return this._cachedConstraints;
    }, setMinimumAndPreferredSizes: function (width, height, preferredWidth, preferredHeight) {
        this._constraints = new Constraints(new Size(width, height), new Size(preferredWidth, preferredHeight));
        this.invalidateConstraints();
    }, setMinimumSize: function (width, height) {
        this._constraints = new Constraints(new Size(width, height));
        this.invalidateConstraints();
    }, _hasNonZeroConstraints: function () {
        var constraints = this.constraints();
        return !!(constraints.minimum.width || constraints.minimum.height || constraints.preferred.width || constraints.preferred.height);
    }, invalidateConstraints: function () {
        var cached = this._cachedConstraints;
        delete this._cachedConstraints;
        var actual = this.constraints();
        if (!actual.isEqual(cached) && this._parentView)
            this._parentView.invalidateConstraints(); else
            this.doLayout();
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.View._originalAppendChild = Element.prototype.appendChild;
WebInspector.View._originalInsertBefore = Element.prototype.insertBefore;
WebInspector.View._originalRemoveChild = Element.prototype.removeChild;
WebInspector.View._originalRemoveChildren = Element.prototype.removeChildren;
WebInspector.View._incrementViewCounter = function (parentElement, childElement) {
    var count = (childElement.__viewCounter || 0) + (childElement.__view ? 1 : 0);
    if (!count)
        return;
    while (parentElement) {
        parentElement.__viewCounter = (parentElement.__viewCounter || 0) + count;
        parentElement = parentElement.parentElement;
    }
}
WebInspector.View._decrementViewCounter = function (parentElement, childElement) {
    var count = (childElement.__viewCounter || 0) + (childElement.__view ? 1 : 0);
    if (!count)
        return;
    while (parentElement) {
        parentElement.__viewCounter -= count;
        parentElement = parentElement.parentElement;
    }
}
WebInspector.View.__assert = function (condition, message) {
    if (!condition) {
        console.trace();
        throw new Error(message);
    }
}
WebInspector.VBox = function () {
    WebInspector.View.call(this);
    this.element.classList.add("vbox");
};
WebInspector.VBox.prototype = {
    calculateConstraints: function () {
        var constraints = new Constraints(new Size(0, 0));

        function updateForChild() {
            var child = this.constraints();
            constraints = constraints.widthToMax(child);
            constraints = constraints.addHeight(child);
        }

        this._callOnVisibleChildren(updateForChild);
        return constraints;
    }, __proto__: WebInspector.View.prototype
};
WebInspector.HBox = function () {
    WebInspector.View.call(this);
    this.element.classList.add("hbox");
};
WebInspector.HBox.prototype = {
    calculateConstraints: function () {
        var constraints = new Constraints(new Size(0, 0));

        function updateForChild() {
            var child = this.constraints();
            constraints = constraints.addWidth(child);
            constraints = constraints.heightToMax(child);
        }

        this._callOnVisibleChildren(updateForChild);
        return constraints;
    }, __proto__: WebInspector.View.prototype
};
WebInspector.VBoxWithResizeCallback = function (resizeCallback) {
    WebInspector.VBox.call(this);
    this._resizeCallback = resizeCallback;
}
WebInspector.VBoxWithResizeCallback.prototype = {
    onResize: function () {
        this._resizeCallback();
    }, __proto__: WebInspector.VBox.prototype
}
Element.prototype.appendChild = function (child) {
    WebInspector.View.__assert(!child.__view || child.parentElement === this, "Attempt to add view via regular DOM operation.");
    return WebInspector.View._originalAppendChild.call(this, child);
}
Element.prototype.insertBefore = function (child, anchor) {
    WebInspector.View.__assert(!child.__view || child.parentElement === this, "Attempt to add view via regular DOM operation.");
    return WebInspector.View._originalInsertBefore.call(this, child, anchor);
}
Element.prototype.removeChild = function (child) {
    WebInspector.View.__assert(!child.__viewCounter && !child.__view, "Attempt to remove element containing view via regular DOM operation");
    return WebInspector.View._originalRemoveChild.call(this, child);
}
Element.prototype.removeChildren = function () {
    WebInspector.View.__assert(!this.__viewCounter, "Attempt to remove element containing view via regular DOM operation");
    WebInspector.View._originalRemoveChildren.call(this);
}
WebInspector.RootView = function () {
    WebInspector.VBox.call(this);
    this.markAsRoot();
    this.element.classList.add("root-view");
    this.element.setAttribute("spellcheck", false);
    window.addEventListener("resize", this.doResize.bind(this), false);
}
WebInspector.RootView.prototype = {
    attachToBody: function () {
        this.doResize();
        this.show(document.body);
    }, doResize: function () {
        var size = this.constraints().minimum;
        var zoom = WebInspector.zoomManager.zoomFactor();
        var right = Math.min(0, window.innerWidth - size.width / zoom);
        this.element.style.marginRight = right + "px";
        var bottom = Math.min(0, window.innerHeight - size.height / zoom);
        this.element.style.marginBottom = bottom + "px";
        WebInspector.VBox.prototype.doResize.call(this);
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.installDragHandle = function (element, elementDragStart, elementDrag, elementDragEnd, cursor, hoverCursor) {
    element.addEventListener("mousedown", WebInspector.elementDragStart.bind(WebInspector, elementDragStart, elementDrag, elementDragEnd, cursor), false);
    if (hoverCursor !== null)
        element.style.cursor = hoverCursor || cursor;
}
WebInspector.elementDragStart = function (elementDragStart, elementDrag, elementDragEnd, cursor, event) {
    if (event.button || (WebInspector.isMac() && event.ctrlKey))
        return;
    if (WebInspector._elementDraggingEventListener)
        return;
    if (elementDragStart && !elementDragStart((event)))
        return;
    if (WebInspector._elementDraggingGlassPane) {
        WebInspector._elementDraggingGlassPane.dispose();
        delete WebInspector._elementDraggingGlassPane;
    }
    var targetDocument = event.target.ownerDocument;
    WebInspector._elementDraggingEventListener = elementDrag;
    WebInspector._elementEndDraggingEventListener = elementDragEnd;
    WebInspector._mouseOutWhileDraggingTargetDocument = targetDocument;
    targetDocument.addEventListener("mousemove", WebInspector._elementDragMove, true);
    targetDocument.addEventListener("mouseup", WebInspector._elementDragEnd, true);
    targetDocument.addEventListener("mouseout", WebInspector._mouseOutWhileDragging, true);
    targetDocument.body.style.cursor = cursor;
    event.preventDefault();
}
WebInspector._mouseOutWhileDragging = function () {
    WebInspector._unregisterMouseOutWhileDragging();
    WebInspector._elementDraggingGlassPane = new WebInspector.GlassPane();
}
WebInspector._unregisterMouseOutWhileDragging = function () {
    if (!WebInspector._mouseOutWhileDraggingTargetDocument)
        return;
    WebInspector._mouseOutWhileDraggingTargetDocument.removeEventListener("mouseout", WebInspector._mouseOutWhileDragging, true);
    delete WebInspector._mouseOutWhileDraggingTargetDocument;
}
WebInspector._elementDragMove = function (event) {
    if (WebInspector._elementDraggingEventListener((event)))
        WebInspector._cancelDragEvents(event);
}
WebInspector._cancelDragEvents = function (event) {
    var targetDocument = event.target.ownerDocument;
    targetDocument.removeEventListener("mousemove", WebInspector._elementDragMove, true);
    targetDocument.removeEventListener("mouseup", WebInspector._elementDragEnd, true);
    WebInspector._unregisterMouseOutWhileDragging();
    targetDocument.body.style.removeProperty("cursor");
    if (WebInspector._elementDraggingGlassPane)
        WebInspector._elementDraggingGlassPane.dispose();
    delete WebInspector._elementDraggingGlassPane;
    delete WebInspector._elementDraggingEventListener;
    delete WebInspector._elementEndDraggingEventListener;
}
WebInspector._elementDragEnd = function (event) {
    var elementDragEnd = WebInspector._elementEndDraggingEventListener;
    WebInspector._cancelDragEvents((event));
    event.preventDefault();
    if (elementDragEnd)
        elementDragEnd((event));
}
WebInspector.GlassPane = function () {
    this.element = document.createElement("div");
    this.element.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;background-color:transparent;z-index:1000;";
    this.element.id = "glass-pane";
    document.body.appendChild(this.element);
    WebInspector._glassPane = this;
}
WebInspector.GlassPane.prototype = {
    dispose: function () {
        delete WebInspector._glassPane;
        if (WebInspector.GlassPane.DefaultFocusedViewStack.length)
            WebInspector.GlassPane.DefaultFocusedViewStack.peekLast().focus();
        this.element.remove();
    }
}
WebInspector.GlassPane.DefaultFocusedViewStack = [];
WebInspector.isBeingEdited = function (node) {
    if (!node || node.nodeType !== Node.ELEMENT_NODE)
        return false;
    var element = (node);
    if (element.classList.contains("text-prompt") || element.nodeName === "INPUT" || element.nodeName === "TEXTAREA")
        return true;
    if (!WebInspector.__editingCount)
        return false;
    while (element) {
        if (element.__editing)
            return true;
        element = element.parentElement;
    }
    return false;
}
WebInspector.markBeingEdited = function (element, value) {
    if (value) {
        if (element.__editing)
            return false;
        element.classList.add("being-edited");
        element.__editing = true;
        WebInspector.__editingCount = (WebInspector.__editingCount || 0) + 1;
    } else {
        if (!element.__editing)
            return false;
        element.classList.remove("being-edited");
        delete element.__editing;
        --WebInspector.__editingCount;
    }
    return true;
}
WebInspector.CSSNumberRegex = /^(-?(?:\d+(?:\.\d+)?|\.\d+))$/;
WebInspector.StyleValueDelimiters = " \xA0\t\n\"':;,/()";
WebInspector._valueModificationDirection = function (event) {
    var direction = null;
    if (event.type === "mousewheel") {
        if (event.wheelDeltaY > 0)
            direction = "Up"; else if (event.wheelDeltaY < 0)
            direction = "Down";
    } else {
        if (event.keyIdentifier === "Up" || event.keyIdentifier === "PageUp")
            direction = "Up"; else if (event.keyIdentifier === "Down" || event.keyIdentifier === "PageDown")
            direction = "Down";
    }
    return direction;
}
WebInspector._modifiedHexValue = function (hexString, event) {
    var direction = WebInspector._valueModificationDirection(event);
    if (!direction)
        return hexString;
    var number = parseInt(hexString, 16);
    if (isNaN(number) || !isFinite(number))
        return hexString;
    var maxValue = Math.pow(16, hexString.length) - 1;
    var arrowKeyOrMouseWheelEvent = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down" || event.type === "mousewheel");
    var delta;
    if (arrowKeyOrMouseWheelEvent)
        delta = (direction === "Up") ? 1 : -1; else
        delta = (event.keyIdentifier === "PageUp") ? 16 : -16;
    if (event.shiftKey)
        delta *= 16;
    var result = number + delta;
    if (result < 0)
        result = 0; else if (result > maxValue)
        return hexString;
    var resultString = result.toString(16).toUpperCase();
    for (var i = 0, lengthDelta = hexString.length - resultString.length; i < lengthDelta; ++i)
        resultString = "0" + resultString;
    return resultString;
}
WebInspector._modifiedFloatNumber = function (number, event) {
    var direction = WebInspector._valueModificationDirection(event);
    if (!direction)
        return number;
    var arrowKeyOrMouseWheelEvent = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down" || event.type === "mousewheel");
    var changeAmount = 1;
    if (event.shiftKey && !arrowKeyOrMouseWheelEvent)
        changeAmount = 100; else if (event.shiftKey || !arrowKeyOrMouseWheelEvent)
        changeAmount = 10; else if (event.altKey)
        changeAmount = 0.1;
    if (direction === "Down")
        changeAmount *= -1;
    var result = Number((number + changeAmount).toFixed(6));
    if (!String(result).match(WebInspector.CSSNumberRegex))
        return null;
    return result;
}
WebInspector.handleElementValueModifications = function (event, element, finishHandler, suggestionHandler, customNumberHandler) {
    var arrowKeyOrMouseWheelEvent = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down" || event.type === "mousewheel");
    var pageKeyPressed = (event.keyIdentifier === "PageUp" || event.keyIdentifier === "PageDown");
    if (!arrowKeyOrMouseWheelEvent && !pageKeyPressed)
        return false;
    var selection = window.getSelection();
    if (!selection.rangeCount)
        return false;
    var selectionRange = selection.getRangeAt(0);
    if (!selectionRange.commonAncestorContainer.isSelfOrDescendant(element))
        return false;
    var originalValue = element.textContent;
    var wordRange = selectionRange.startContainer.rangeOfWord(selectionRange.startOffset, WebInspector.StyleValueDelimiters, element);
    var wordString = wordRange.toString();
    if (suggestionHandler && suggestionHandler(wordString))
        return false;
    var replacementString;
    var prefix, suffix, number;
    var matches;
    matches = /(.*#)([\da-fA-F]+)(.*)/.exec(wordString);
    if (matches && matches.length) {
        prefix = matches[1];
        suffix = matches[3];
        number = WebInspector._modifiedHexValue(matches[2], event);
        replacementString = customNumberHandler ? customNumberHandler(prefix, number, suffix) : prefix + number + suffix;
    } else {
        matches = /(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/.exec(wordString);
        if (matches && matches.length) {
            prefix = matches[1];
            suffix = matches[3];
            number = WebInspector._modifiedFloatNumber(parseFloat(matches[2]), event);
            if (number === null)
                return false;
            replacementString = customNumberHandler ? customNumberHandler(prefix, number, suffix) : prefix + number + suffix;
        }
    }
    if (replacementString) {
        var replacementTextNode = document.createTextNode(replacementString);
        wordRange.deleteContents();
        wordRange.insertNode(replacementTextNode);
        var finalSelectionRange = document.createRange();
        finalSelectionRange.setStart(replacementTextNode, 0);
        finalSelectionRange.setEnd(replacementTextNode, replacementString.length);
        selection.removeAllRanges();
        selection.addRange(finalSelectionRange);
        event.handled = true;
        event.preventDefault();
        if (finishHandler)
            finishHandler(originalValue, replacementString);
        return true;
    }
    return false;
}
Number.preciseMillisToString = function (ms, precision) {
    precision = precision || 0;
    var format = "%." + precision + "f\u2009ms";
    return WebInspector.UIString(format, ms);
}
Number.millisToString = function (ms, higherResolution) {
    if (!isFinite(ms))
        return "-";
    if (ms === 0)
        return "0";
    if (higherResolution && ms < 1000)
        return WebInspector.UIString("%.3f\u2009ms", ms); else if (ms < 1000)
        return WebInspector.UIString("%.0f\u2009ms", ms);
    var seconds = ms / 1000;
    if (seconds < 60)
        return WebInspector.UIString("%.2f\u2009s", seconds);
    var minutes = seconds / 60;
    if (minutes < 60)
        return WebInspector.UIString("%.1f\u2009min", minutes);
    var hours = minutes / 60;
    if (hours < 24)
        return WebInspector.UIString("%.1f\u2009hrs", hours);
    var days = hours / 24;
    return WebInspector.UIString("%.1f\u2009days", days);
}
Number.secondsToString = function (seconds, higherResolution) {
    if (!isFinite(seconds))
        return "-";
    return Number.millisToString(seconds * 1000, higherResolution);
}
Number.bytesToString = function (bytes) {
    if (bytes < 1024)
        return WebInspector.UIString("%.0f\u2009B", bytes);
    var kilobytes = bytes / 1024;
    if (kilobytes < 100)
        return WebInspector.UIString("%.1f\u2009KB", kilobytes);
    if (kilobytes < 1024)
        return WebInspector.UIString("%.0f\u2009KB", kilobytes);
    var megabytes = kilobytes / 1024;
    if (megabytes < 100)
        return WebInspector.UIString("%.1f\u2009MB", megabytes); else
        return WebInspector.UIString("%.0f\u2009MB", megabytes);
}
Number.withThousandsSeparator = function (num) {
    var str = num + "";
    var re = /(\d+)(\d{3})/;
    while (str.match(re))
        str = str.replace(re, "$1\u2009$2");
    return str;
}
WebInspector.useLowerCaseMenuTitles = function () {
    return WebInspector.platform() === "windows";
}
WebInspector.formatLocalized = function (format, substitutions, formatters, initialValue, append) {
    return String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append);
}
WebInspector.openLinkExternallyLabel = function () {
    return WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Open link in new tab" : "Open Link in New Tab");
}
WebInspector.copyLinkAddressLabel = function () {
    return WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy link address" : "Copy Link Address");
}
WebInspector.anotherProfilerActiveLabel = function () {
    return WebInspector.UIString("Another profiler is already active");
}
WebInspector.asyncStackTraceLabel = function (description) {
    if (description)
        return description + " " + WebInspector.UIString("(async)");
    return WebInspector.UIString("Async Call");
}
WebInspector.manageBlackboxingButtonLabel = function () {
    return WebInspector.UIString("Manage framework blackboxing...");
}
WebInspector.installPortStyles = function () {
    var platform = WebInspector.platform();
    document.body.classList.add("platform-" + platform);
    var flavor = WebInspector.platformFlavor();
    if (flavor)
        document.body.classList.add("platform-" + flavor);
    var port = WebInspector.port();
    document.body.classList.add("port-" + port);
}
WebInspector._windowFocused = function (event) {
    if (event.target.document.nodeType === Node.DOCUMENT_NODE)
        document.body.classList.remove("inactive");
}
WebInspector._windowBlurred = function (event) {
    if (event.target.document.nodeType === Node.DOCUMENT_NODE)
        document.body.classList.add("inactive");
}
WebInspector.previousFocusElement = function () {
    return WebInspector._previousFocusElement;
}
WebInspector.currentFocusElement = function () {
    return WebInspector._currentFocusElement;
}
WebInspector._focusChanged = function (event) {
    WebInspector.setCurrentFocusElement(event.target);
}
WebInspector._documentBlurred = function (event) {
    if (!event.relatedTarget && document.activeElement === document.body)
        WebInspector.setCurrentFocusElement(null);
}
WebInspector._textInputTypes = ["text", "search", "tel", "url", "email", "password"].keySet();
WebInspector._isTextEditingElement = function (element) {
    if (element instanceof HTMLInputElement)
        return element.type in WebInspector._textInputTypes;
    if (element instanceof HTMLTextAreaElement)
        return true;
    return false;
}
WebInspector.setCurrentFocusElement = function (x) {
    if (WebInspector._glassPane && x && !WebInspector._glassPane.element.isAncestor(x))
        return;
    if (WebInspector._currentFocusElement !== x)
        WebInspector._previousFocusElement = WebInspector._currentFocusElement;
    WebInspector._currentFocusElement = x;
    if (WebInspector._currentFocusElement) {
        WebInspector._currentFocusElement.focus();
        var selection = window.getSelection();
        if (!WebInspector._isTextEditingElement(WebInspector._currentFocusElement) && selection.isCollapsed && !WebInspector._currentFocusElement.isInsertionCaretInside()) {
            var selectionRange = WebInspector._currentFocusElement.ownerDocument.createRange();
            selectionRange.setStart(WebInspector._currentFocusElement, 0);
            selectionRange.setEnd(WebInspector._currentFocusElement, 0);
            selection.removeAllRanges();
            selection.addRange(selectionRange);
        }
    } else if (WebInspector._previousFocusElement)
        WebInspector._previousFocusElement.blur();
}
WebInspector.restoreFocusFromElement = function (element) {
    if (element && element.isSelfOrAncestor(WebInspector.currentFocusElement()))
        WebInspector.setCurrentFocusElement(WebInspector.previousFocusElement());
}
WebInspector.setToolbarColors = function (backgroundColor, color) {
    if (!WebInspector._themeStyleElement) {
        WebInspector._themeStyleElement = document.createElement("style");
        document.head.appendChild(WebInspector._themeStyleElement);
    }
    var parsedColor = WebInspector.Color.parse(color);
    var shadowColor = parsedColor ? parsedColor.invert().setAlpha(0.33).toString(WebInspector.Color.Format.RGBA) : "white";
    var prefix = WebInspector.isMac() ? "body:not(.undocked)" : "";
    WebInspector._themeStyleElement.textContent = String.sprintf("%s .toolbar-colors {\
                 background-image: none !important;\
                 background-color: %s !important;\
                 color: %s !important;\
             }", prefix, backgroundColor, color) +
    String.sprintf("%s .toolbar-colors button.status-bar-item .glyph, %s .toolbar-colors button.status-bar-item .long-click-glyph {\
                 background-color: %s;\
             }", prefix, prefix, color) +
    String.sprintf("%s .toolbar-colors button.status-bar-item .glyph.shadow, %s .toolbar-colors button.status-bar-item .long-click-glyph.shadow {\
                 background-color: %s;\
             }", prefix, prefix, shadowColor);
}
WebInspector.resetToolbarColors = function () {
    if (WebInspector._themeStyleElement)
        WebInspector._themeStyleElement.textContent = "";
}
WebInspector.highlightSearchResult = function (element, offset, length, domChanges) {
    var result = WebInspector.highlightSearchResults(element, [new WebInspector.SourceRange(offset, length)], domChanges);
    return result.length ? result[0] : null;
}
WebInspector.highlightSearchResults = function (element, resultRanges, changes) {
    return WebInspector.highlightRangesWithStyleClass(element, resultRanges, "highlighted-search-result", changes);
}
WebInspector.runCSSAnimationOnce = function (element, className) {
    function animationEndCallback() {
        element.classList.remove(className);
        element.removeEventListener("animationend", animationEndCallback, false);
    }

    if (element.classList.contains(className))
        element.classList.remove(className);
    element.addEventListener("animationend", animationEndCallback, false);
    element.classList.add(className);
}
WebInspector.highlightRangesWithStyleClass = function (element, resultRanges, styleClass, changes) {
    changes = changes || [];
    var highlightNodes = [];
    var lineText = element.textContent;
    var ownerDocument = element.ownerDocument;
    var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var snapshotLength = textNodeSnapshot.snapshotLength;
    if (snapshotLength === 0)
        return highlightNodes;
    var nodeRanges = [];
    var rangeEndOffset = 0;
    for (var i = 0; i < snapshotLength; ++i) {
        var range = {};
        range.offset = rangeEndOffset;
        range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
        rangeEndOffset = range.offset + range.length;
        nodeRanges.push(range);
    }
    var startIndex = 0;
    for (var i = 0; i < resultRanges.length; ++i) {
        var startOffset = resultRanges[i].offset;
        var endOffset = startOffset + resultRanges[i].length;
        while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
            startIndex++;
        var endIndex = startIndex;
        while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
            endIndex++;
        if (endIndex === snapshotLength)
            break;
        var highlightNode = ownerDocument.createElement("span");
        highlightNode.className = styleClass;
        highlightNode.textContent = lineText.substring(startOffset, endOffset);
        var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
        var lastText = lastTextNode.textContent;
        lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
        changes.push({node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent});
        if (startIndex === endIndex) {
            lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
            changes.push({node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement});
            highlightNodes.push(highlightNode);
            var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
            lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
            changes.push({node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement});
        } else {
            var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
            var firstText = firstTextNode.textContent;
            var anchorElement = firstTextNode.nextSibling;
            firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
            changes.push({node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement});
            highlightNodes.push(highlightNode);
            firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
            changes.push({node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent});
            for (var j = startIndex + 1; j < endIndex; j++) {
                var textNode = textNodeSnapshot.snapshotItem(j);
                var text = textNode.textContent;
                textNode.textContent = "";
                changes.push({node: textNode, type: "changed", oldText: text, newText: textNode.textContent});
            }
        }
        startIndex = endIndex;
        nodeRanges[startIndex].offset = endOffset;
        nodeRanges[startIndex].length = lastTextNode.textContent.length;
    }
    return highlightNodes;
}
WebInspector.applyDomChanges = function (domChanges) {
    for (var i = 0, size = domChanges.length; i < size; ++i) {
        var entry = domChanges[i];
        switch (entry.type) {
            case"added":
                entry.parent.insertBefore(entry.node, entry.nextSibling);
                break;
            case"changed":
                entry.node.textContent = entry.newText;
                break;
        }
    }
}
WebInspector.revertDomChanges = function (domChanges) {
    for (var i = domChanges.length - 1; i >= 0; --i) {
        var entry = domChanges[i];
        switch (entry.type) {
            case"added":
                entry.node.remove();
                break;
            case"changed":
                entry.node.textContent = entry.oldText;
                break;
        }
    }
}
WebInspector.InvokeOnceHandlers = function (autoInvoke) {
    this._handlers = null;
    this._autoInvoke = autoInvoke;
}
WebInspector.InvokeOnceHandlers.prototype = {
    add: function (object, method) {
        if (!this._handlers) {
            this._handlers = new Map();
            if (this._autoInvoke)
                this.scheduleInvoke();
        }
        var methods = this._handlers.get(object);
        if (!methods) {
            methods = new Set();
            this._handlers.put(object, methods);
        }
        methods.add(method);
    }, scheduleInvoke: function () {
        if (this._handlers)
            requestAnimationFrame(this._invoke.bind(this));
    }, _invoke: function () {
        var handlers = this._handlers;
        this._handlers = null;
        var keys = handlers.keys();
        for (var i = 0; i < keys.length; ++i) {
            var object = keys[i];
            var methods = handlers.get(object).values();
            for (var j = 0; j < methods.length; ++j)
                methods[j].call(object);
        }
    }
}
WebInspector._coalescingLevel = 0;
WebInspector._postUpdateHandlers = null;
WebInspector.startBatchUpdate = function () {
    if (!WebInspector._coalescingLevel++)
        WebInspector._postUpdateHandlers = new WebInspector.InvokeOnceHandlers(false);
}
WebInspector.endBatchUpdate = function () {
    if (--WebInspector._coalescingLevel)
        return;
    WebInspector._postUpdateHandlers.scheduleInvoke();
    WebInspector._postUpdateHandlers = null;
}
WebInspector.invokeOnceAfterBatchUpdate = function (object, method) {
    if (!WebInspector._postUpdateHandlers)
        WebInspector._postUpdateHandlers = new WebInspector.InvokeOnceHandlers(true);
    WebInspector._postUpdateHandlers.add(object, method);
}
WebInspector.animateFunction = function (func, params, frames, animationComplete) {
    var values = new Array(params.length);
    var deltas = new Array(params.length);
    for (var i = 0; i < params.length; ++i) {
        values[i] = params[i].from;
        deltas[i] = (params[i].to - params[i].from) / frames;
    }
    var raf = requestAnimationFrame(animationStep);
    var framesLeft = frames;

    function animationStep() {
        if (--framesLeft < 0) {
            if (animationComplete)
                animationComplete();
            return;
        }
        for (var i = 0; i < params.length; ++i) {
            if (params[i].to > params[i].from)
                values[i] = Number.constrain(values[i] + deltas[i], params[i].from, params[i].to); else
                values[i] = Number.constrain(values[i] + deltas[i], params[i].to, params[i].from);
        }
        func.apply(null, values);
        raf = window.requestAnimationFrame(animationStep);
    }

    function cancelAnimation() {
        window.cancelAnimationFrame(raf);
    }

    return cancelAnimation;
};
(function () {
    function windowLoaded() {
        window.addEventListener("focus", WebInspector._windowFocused, false);
        window.addEventListener("blur", WebInspector._windowBlurred, false);
        document.addEventListener("focus", WebInspector._focusChanged, true);
        document.addEventListener("blur", WebInspector._documentBlurred, true);
        window.removeEventListener("DOMContentLoaded", windowLoaded, false);
    }

    window.addEventListener("DOMContentLoaded", windowLoaded, false);
})();
WebInspector.HelpScreen = function (title) {
    WebInspector.VBox.call(this);
    this.markAsRoot();
    this.registerRequiredCSS("helpScreen.css");
    this.element.classList.add("help-window-outer");
    this.element.addEventListener("keydown", this._onKeyDown.bind(this), false);
    this.element.tabIndex = 0;
    if (title) {
        var mainWindow = this.element.createChild("div", "help-window-main");
        var captionWindow = mainWindow.createChild("div", "help-window-caption");
        captionWindow.appendChild(this._createCloseButton());
        this.contentElement = mainWindow.createChild("div", "help-content");
        captionWindow.createChild("h1", "help-window-title").textContent = title;
    }
}
WebInspector.HelpScreen._visibleScreen = null;
WebInspector.HelpScreen.prototype = {
    _createCloseButton: function () {
        var closeButton = document.createElement("div");
        closeButton.className = "help-close-button close-button-gray";
        closeButton.addEventListener("click", this.hide.bind(this), false);
        return closeButton;
    }, showModal: function () {
        var visibleHelpScreen = WebInspector.HelpScreen._visibleScreen;
        if (visibleHelpScreen === this)
            return;
        if (visibleHelpScreen)
            visibleHelpScreen.hide();
        WebInspector.HelpScreen._visibleScreen = this;
        WebInspector.GlassPane.DefaultFocusedViewStack.push(this);
        this.show(WebInspector.inspectorView.element);
        this.focus();
    }, hide: function () {
        if (!this.isShowing())
            return;
        WebInspector.HelpScreen._visibleScreen = null;
        WebInspector.GlassPane.DefaultFocusedViewStack.pop();
        WebInspector.restoreFocusFromElement(this.element);
        this.detach();
    }, isClosingKey: function (keyCode) {
        return [WebInspector.KeyboardShortcut.Keys.Enter.code, WebInspector.KeyboardShortcut.Keys.Esc.code, WebInspector.KeyboardShortcut.Keys.Space.code,].indexOf(keyCode) >= 0;
    }, _onKeyDown: function (event) {
        if (this.isShowing() && this.isClosingKey(event.keyCode)) {
            this.hide();
            event.consume();
        }
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.RemoteDebuggingTerminatedScreen = function (reason) {
    WebInspector.HelpScreen.call(this, WebInspector.UIString("Detached from the target"));
    var p = this.contentElement.createChild("p");
    p.classList.add("help-section");
    p.createChild("span").textContent = WebInspector.UIString("Remote debugging has been terminated with reason: ");
    p.createChild("span", "error-message").textContent = reason;
    p.createChild("br");
    p.createChild("span").textContent = WebInspector.UIString("Please re-attach to the new target.");
}
WebInspector.RemoteDebuggingTerminatedScreen.prototype = {__proto__: WebInspector.HelpScreen.prototype}
WebInspector.WorkerTerminatedScreen = function () {
    WebInspector.HelpScreen.call(this, WebInspector.UIString("Inspected worker terminated"));
    var p = this.contentElement.createChild("p");
    p.classList.add("help-section");
    p.textContent = WebInspector.UIString("Inspected worker has terminated. Once it restarts we will attach to it automatically.");
}
WebInspector.WorkerTerminatedScreen.prototype = {__proto__: WebInspector.HelpScreen.prototype}
WebInspector.FileManager = function () {
    this._saveCallbacks = {};
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SavedURL, this._savedURL, this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.CanceledSaveURL, this._canceledSaveURL, this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.AppendedToURL, this._appendedToURL, this);
}
WebInspector.FileManager.EventTypes = {SavedURL: "SavedURL", AppendedToURL: "AppendedToURL"}
WebInspector.FileManager.prototype = {
    canSave: function () {
        return true;
    }, save: function (url, content, forceSaveAs, callback) {
        var savedURLs = WebInspector.settings.savedURLs.get();
        delete savedURLs[url];
        WebInspector.settings.savedURLs.set(savedURLs);
        this._saveCallbacks[url] = callback || null;
        InspectorFrontendHost.save(url, content, forceSaveAs);
    }, _savedURL: function (event) {
        var url = (event.data);
        var savedURLs = WebInspector.settings.savedURLs.get();
        savedURLs[url] = true;
        WebInspector.settings.savedURLs.set(savedURLs);
        this.dispatchEventToListeners(WebInspector.FileManager.EventTypes.SavedURL, url);
        this._invokeSaveCallback(url, true);
    }, _invokeSaveCallback: function (url, accepted) {
        var callback = this._saveCallbacks[url];
        delete this._saveCallbacks[url];
        if (callback)
            callback(accepted);
    }, _canceledSaveURL: function (event) {
        var url = (event.data);
        this._invokeSaveCallback(url, false);
    }, isURLSaved: function (url) {
        var savedURLs = WebInspector.settings.savedURLs.get();
        return savedURLs[url];
    }, append: function (url, content) {
        InspectorFrontendHost.append(url, content);
    }, close: function (url) {
    }, _appendedToURL: function (event) {
        var url = (event.data);
        this.dispatchEventToListeners(WebInspector.FileManager.EventTypes.AppendedToURL, url);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.fileManager = new WebInspector.FileManager();
WebInspector.Checkbox = function (label, className, tooltip) {
    this.element = document.createElementWithClass("label", className);
    this._inputElement = this.element.createChild("input");
    this._inputElement.type = "checkbox";
    this.element.createTextChild(label);
    if (tooltip)
        this.element.title = tooltip;
}
WebInspector.Checkbox.prototype = {
    set checked(checked) {
        this._inputElement.checked = checked;
    }, get checked() {
        return this._inputElement.checked;
    }, addEventListener: function (listener) {
        function listenerWrapper(event) {
            if (listener)
                listener(event);
            event.consume();
            return true;
        }

        this._inputElement.addEventListener("click", listenerWrapper, false);
        this.element.addEventListener("click", listenerWrapper, false);
    }
}
WebInspector.ContextMenuItem = function (topLevelMenu, type, label, disabled, checked) {
    this._type = type;
    this._label = label;
    this._disabled = disabled;
    this._checked = checked;
    this._contextMenu = topLevelMenu;
    if (type === "item" || type === "checkbox")
        this._id = topLevelMenu.nextId();
}
WebInspector.ContextMenuItem.prototype = {
    id: function () {
        return this._id;
    }, type: function () {
        return this._type;
    }, isEnabled: function () {
        return !this._disabled;
    }, setEnabled: function (enabled) {
        this._disabled = !enabled;
    }, _buildDescriptor: function () {
        switch (this._type) {
            case"item":
                return {type: "item", id: this._id, label: this._label, enabled: !this._disabled};
            case"separator":
                return {type: "separator"};
            case"checkbox":
                return {type: "checkbox", id: this._id, label: this._label, checked: !!this._checked, enabled: !this._disabled};
        }
        throw new Error("Invalid item type:" + this._type);
    }
}
WebInspector.ContextSubMenuItem = function (topLevelMenu, label, disabled) {
    WebInspector.ContextMenuItem.call(this, topLevelMenu, "subMenu", label, disabled);
    this._items = [];
}
WebInspector.ContextSubMenuItem.prototype = {
    appendItem: function (label, handler, disabled) {
        var item = new WebInspector.ContextMenuItem(this._contextMenu, "item", label, disabled);
        this._pushItem(item);
        this._contextMenu._setHandler(item.id(), handler);
        return item;
    }, appendSubMenuItem: function (label, disabled) {
        var item = new WebInspector.ContextSubMenuItem(this._contextMenu, label, disabled);
        this._pushItem(item);
        return item;
    }, appendCheckboxItem: function (label, handler, checked, disabled) {
        var item = new WebInspector.ContextMenuItem(this._contextMenu, "checkbox", label, disabled, checked);
        this._pushItem(item);
        this._contextMenu._setHandler(item.id(), handler);
        return item;
    }, appendSeparator: function () {
        if (this._items.length)
            this._pendingSeparator = true;
    }, _pushItem: function (item) {
        if (this._pendingSeparator) {
            this._items.push(new WebInspector.ContextMenuItem(this._contextMenu, "separator"));
            delete this._pendingSeparator;
        }
        this._items.push(item);
    }, isEmpty: function () {
        return !this._items.length;
    }, _buildDescriptor: function () {
        var result = {type: "subMenu", label: this._label, enabled: !this._disabled, subItems: []};
        for (var i = 0; i < this._items.length; ++i)
            result.subItems.push(this._items[i]._buildDescriptor());
        return result;
    }, __proto__: WebInspector.ContextMenuItem.prototype
}
WebInspector.ContextMenu = function (event) {
    WebInspector.ContextSubMenuItem.call(this, this, "");
    this._event = event;
    this._handlers = {};
    this._id = 0;
}
WebInspector.ContextMenu.initialize = function () {
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetUseSoftMenu, setUseSoftMenu);
    function setUseSoftMenu(event) {
        WebInspector.ContextMenu._useSoftMenu = (event.data);
    }
}
WebInspector.ContextMenu.prototype = {
    nextId: function () {
        return this._id++;
    }, show: function () {
        var menuObject = this._buildDescriptor();
        if (menuObject.length) {
            WebInspector._contextMenu = this;
            if (WebInspector.ContextMenu._useSoftMenu || InspectorFrontendHost.isHostedMode()) {
                var softMenu = new WebInspector.SoftContextMenu(menuObject, this._itemSelected.bind(this));
                softMenu.show(this._event.x, this._event.y);
            } else {
                InspectorFrontendHost.showContextMenuAtPoint(this._event.x, this._event.y, menuObject);
                InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuCleared, this._menuCleared, this);
                InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuItemSelected, this._onItemSelected, this);
            }
            this._event.consume(true);
        }
    }, _setHandler: function (id, handler) {
        if (handler)
            this._handlers[id] = handler;
    }, _buildDescriptor: function () {
        var result = [];
        for (var i = 0; i < this._items.length; ++i)
            result.push(this._items[i]._buildDescriptor());
        return result;
    }, _onItemSelected: function (event) {
        this._itemSelected((event.data));
    }, _itemSelected: function (id) {
        if (this._handlers[id])
            this._handlers[id].call(this);
        this._menuCleared();
    }, _menuCleared: function () {
        InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.ContextMenuCleared, this._menuCleared, this);
        InspectorFrontendHost.events.removeEventListener(InspectorFrontendHostAPI.Events.ContextMenuItemSelected, this._onItemSelected, this);
    }, appendApplicableItems: function (target) {
        self.runtime.extensions(WebInspector.ContextMenu.Provider, target).forEach(processProviders.bind(this));
        function processProviders(extension) {
            var provider = (extension.instance());
            this.appendSeparator();
            provider.appendApplicableItems(this._event, this, target);
            this.appendSeparator();
        }
    }, __proto__: WebInspector.ContextSubMenuItem.prototype
}
WebInspector.ContextMenu.Provider = function () {
}
WebInspector.ContextMenu.Provider.prototype = {
    appendApplicableItems: function (event, contextMenu, target) {
    }
}
WebInspector.SoftContextMenu = function (items, itemSelectedCallback, parentMenu) {
    this._items = items;
    this._itemSelectedCallback = itemSelectedCallback;
    this._parentMenu = parentMenu;
}
WebInspector.SoftContextMenu.prototype = {
    show: function (x, y) {
        this._x = x;
        this._y = y;
        this._time = new Date().getTime();
        this._contextMenuElement = document.createElementWithClass("div", "soft-context-menu");
        this._contextMenuElement.tabIndex = 0;
        this._contextMenuElement.style.top = y + "px";
        this._contextMenuElement.style.left = x + "px";
        this._contextMenuElement.addEventListener("mouseup", consumeEvent, false);
        this._contextMenuElement.addEventListener("keydown", this._menuKeyDown.bind(this), false);
        for (var i = 0; i < this._items.length; ++i)
            this._contextMenuElement.appendChild(this._createMenuItem(this._items[i]));
        if (!this._parentMenu) {
            this._glassPaneElement = document.createElementWithClass("div", "soft-context-menu-glass-pane");
            this._glassPaneElement.tabIndex = 0;
            this._glassPaneElement.addEventListener("mouseup", this._glassPaneMouseUp.bind(this), false);
            this._glassPaneElement.appendChild(this._contextMenuElement);
            document.body.appendChild(this._glassPaneElement);
            this._focus();
        } else {
            this._parentMenu._parentGlassPaneElement().appendChild(this._contextMenuElement);
        }
        if (document.body.offsetWidth < this._contextMenuElement.offsetLeft + this._contextMenuElement.offsetWidth)
            this._contextMenuElement.style.left = Math.max(0, x - this._contextMenuElement.offsetWidth) + "px";
        if (document.body.offsetHeight < this._contextMenuElement.offsetTop + this._contextMenuElement.offsetHeight)
            this._contextMenuElement.style.top = Math.max(0, document.body.offsetHeight - this._contextMenuElement.offsetHeight) + "px";
    }, _parentGlassPaneElement: function () {
        if (this._glassPaneElement)
            return this._glassPaneElement;
        if (this._parentMenu)
            return this._parentMenu._parentGlassPaneElement();
        return null;
    }, _createMenuItem: function (item) {
        if (item.type === "separator")
            return this._createSeparator();
        if (item.type === "subMenu")
            return this._createSubMenu(item);
        var menuItemElement = document.createElementWithClass("div", "soft-context-menu-item");
        var checkMarkElement = menuItemElement.createChild("span", "soft-context-menu-item-checkmark");
        checkMarkElement.textContent = "\u2713 ";
        if (!item.checked)
            checkMarkElement.style.opacity = "0";
        menuItemElement.createTextChild(item.label);
        menuItemElement.addEventListener("mousedown", this._menuItemMouseDown.bind(this), false);
        menuItemElement.addEventListener("mouseup", this._menuItemMouseUp.bind(this), false);
        menuItemElement.addEventListener("mouseover", this._menuItemMouseOver.bind(this), false);
        menuItemElement.addEventListener("mouseout", this._menuItemMouseOut.bind(this), false);
        menuItemElement._actionId = item.id;
        return menuItemElement;
    }, _createSubMenu: function (item) {
        var menuItemElement = document.createElementWithClass("div", "soft-context-menu-item");
        menuItemElement._subItems = item.subItems;
        var checkMarkElement = menuItemElement.createChild("span", "soft-context-menu-item-checkmark");
        checkMarkElement.textContent = "\u2713 ";
        checkMarkElement.style.opacity = "0";
        menuItemElement.createTextChild(item.label);
        var subMenuArrowElement = menuItemElement.createChild("span", "soft-context-menu-item-submenu-arrow");
        subMenuArrowElement.textContent = "\u25B6";
        menuItemElement.addEventListener("mousedown", this._menuItemMouseDown.bind(this), false);
        menuItemElement.addEventListener("mouseup", this._menuItemMouseUp.bind(this), false);
        menuItemElement.addEventListener("mouseover", this._menuItemMouseOver.bind(this), false);
        menuItemElement.addEventListener("mouseout", this._menuItemMouseOut.bind(this), false);
        return menuItemElement;
    }, _createSeparator: function () {
        var separatorElement = document.createElementWithClass("div", "soft-context-menu-separator");
        separatorElement._isSeparator = true;
        separatorElement.addEventListener("mouseover", this._hideSubMenu.bind(this), false);
        separatorElement.createChild("div", "separator-line");
        return separatorElement;
    }, _menuItemMouseDown: function (event) {
        event.consume(true);
    }, _menuItemMouseUp: function (event) {
        this._triggerAction(event.target, event);
        event.consume();
    }, _focus: function () {
        this._contextMenuElement.focus();
    }, _triggerAction: function (menuItemElement, event) {
        if (!menuItemElement._subItems) {
            this._discardMenu(true, event);
            if (typeof menuItemElement._actionId !== "undefined") {
                this._itemSelectedCallback(menuItemElement._actionId);
                delete menuItemElement._actionId;
            }
            return;
        }
        this._showSubMenu(menuItemElement);
        event.consume();
    }, _showSubMenu: function (menuItemElement) {
        if (menuItemElement._subMenuTimer) {
            clearTimeout(menuItemElement._subMenuTimer);
            delete menuItemElement._subMenuTimer;
        }
        if (this._subMenu)
            return;
        this._subMenu = new WebInspector.SoftContextMenu(menuItemElement._subItems, this._itemSelectedCallback, this);
        this._subMenu.show(this._x + menuItemElement.offsetWidth - 3, this._y + menuItemElement.offsetTop - 1);
    }, _hideSubMenu: function () {
        if (!this._subMenu)
            return;
        this._subMenu._discardSubMenus();
        this._focus();
    }, _menuItemMouseOver: function (event) {
        this._highlightMenuItem(event.target);
    }, _menuItemMouseOut: function (event) {
        if (!this._subMenu || !event.relatedTarget) {
            this._highlightMenuItem(null);
            return;
        }
        var relatedTarget = event.relatedTarget;
        if (this._contextMenuElement.isSelfOrAncestor(relatedTarget) || relatedTarget.classList.contains("soft-context-menu-glass-pane"))
            this._highlightMenuItem(null);
    }, _highlightMenuItem: function (menuItemElement) {
        if (this._highlightedMenuItemElement === menuItemElement)
            return;
        this._hideSubMenu();
        if (this._highlightedMenuItemElement) {
            this._highlightedMenuItemElement.classList.remove("soft-context-menu-item-mouse-over");
            if (this._highlightedMenuItemElement._subItems && this._highlightedMenuItemElement._subMenuTimer) {
                clearTimeout(this._highlightedMenuItemElement._subMenuTimer);
                delete this._highlightedMenuItemElement._subMenuTimer;
            }
        }
        this._highlightedMenuItemElement = menuItemElement;
        if (this._highlightedMenuItemElement) {
            this._highlightedMenuItemElement.classList.add("soft-context-menu-item-mouse-over");
            this._contextMenuElement.focus();
            if (this._highlightedMenuItemElement._subItems && !this._highlightedMenuItemElement._subMenuTimer)
                this._highlightedMenuItemElement._subMenuTimer = setTimeout(this._showSubMenu.bind(this, this._highlightedMenuItemElement), 150);
        }
    }, _highlightPrevious: function () {
        var menuItemElement = this._highlightedMenuItemElement ? this._highlightedMenuItemElement.previousSibling : this._contextMenuElement.lastChild;
        while (menuItemElement && menuItemElement._isSeparator)
            menuItemElement = menuItemElement.previousSibling;
        if (menuItemElement)
            this._highlightMenuItem(menuItemElement);
    }, _highlightNext: function () {
        var menuItemElement = this._highlightedMenuItemElement ? this._highlightedMenuItemElement.nextSibling : this._contextMenuElement.firstChild;
        while (menuItemElement && menuItemElement._isSeparator)
            menuItemElement = menuItemElement.nextSibling;
        if (menuItemElement)
            this._highlightMenuItem(menuItemElement);
    }, _menuKeyDown: function (event) {
        switch (event.keyIdentifier) {
            case"Up":
                this._highlightPrevious();
                break;
            case"Down":
                this._highlightNext();
                break;
            case"Left":
                if (this._parentMenu) {
                    this._highlightMenuItem(null);
                    this._parentMenu._focus();
                }
                break;
            case"Right":
                if (!this._highlightedMenuItemElement)
                    break;
                if (this._highlightedMenuItemElement._subItems) {
                    this._showSubMenu(this._highlightedMenuItemElement);
                    this._subMenu._focus();
                    this._subMenu._highlightNext();
                }
                break;
            case"U+001B":
                this._discardMenu(true, event);
                break;
            case"Enter":
                if (!isEnterKey(event))
                    break;
            case"U+0020":
                if (this._highlightedMenuItemElement)
                    this._triggerAction(this._highlightedMenuItemElement, event);
                break;
        }
        event.consume(true);
    }, _glassPaneMouseUp: function (event) {
        if (event.x === this._x && event.y === this._y && new Date().getTime() - this._time < 300)
            return;
        this._discardMenu(true, event);
        event.consume();
    }, _discardMenu: function (closeParentMenus, event) {
        if (this._subMenu && !closeParentMenus)
            return;
        if (this._glassPaneElement) {
            var glassPane = this._glassPaneElement;
            delete this._glassPaneElement;
            document.body.removeChild(glassPane);
            if (this._parentMenu) {
                delete this._parentMenu._subMenu;
                if (closeParentMenus)
                    this._parentMenu._discardMenu(closeParentMenus, event);
            }
            if (event)
                event.consume(true);
        } else if (this._parentMenu && this._contextMenuElement.parentElement) {
            this._discardSubMenus();
            if (closeParentMenus)
                this._parentMenu._discardMenu(closeParentMenus, event);
            if (event)
                event.consume(true);
        }
    }, _discardSubMenus: function () {
        if (this._subMenu)
            this._subMenu._discardSubMenus();
        this._contextMenuElement.remove();
        if (this._parentMenu)
            delete this._parentMenu._subMenu;
    }
}
WebInspector.ActionRegistry = function () {
    this._actionsById = new StringMap();
    this._registerActions();
}
WebInspector.ActionRegistry.prototype = {
    _registerActions: function () {
        self.runtime.extensions(WebInspector.ActionDelegate).forEach(registerExtension, this);
        function registerExtension(extension) {
            var actionId = extension.descriptor()["actionId"];
            console.assert(actionId);
            console.assert(!this._actionsById.get(actionId));
            this._actionsById.put(actionId, extension);
        }
    }, applicableActions: function (actionIds, context) {
        var extensions = [];
        actionIds.forEach(function (actionId) {
            var extension = this._actionsById.get(actionId);
            if (extension)
                extensions.push(extension);
        }, this);
        return context.applicableExtensions(extensions).values().map(function (extension) {
            return extension.descriptor()["actionId"];
        });
    }, execute: function (actionId) {
        var extension = this._actionsById.get(actionId);
        console.assert(extension, "No action found for actionId '" + actionId + "'");
        return extension.instance().handleAction(WebInspector.context);
    }
}
WebInspector.ActionDelegate = function () {
}
WebInspector.ActionDelegate.prototype = {
    handleAction: function (context) {
    }
}
WebInspector.actionRegistry;
WebInspector.KeyboardShortcut = function () {
}
WebInspector.KeyboardShortcut.Modifiers = {
    None: 0, Shift: 1, Ctrl: 2, Alt: 4, Meta: 8, get CtrlOrMeta() {
        return WebInspector.isMac() ? this.Meta : this.Ctrl;
    }, get ShiftOrOption() {
        return WebInspector.isMac() ? this.Shift : this.Alt;
    }
};
WebInspector.KeyboardShortcut.Key;
WebInspector.KeyboardShortcut.Keys = {
    Backspace: {code: 8, name: "\u21a4"},
    Tab: {code: 9, name: {mac: "\u21e5", other: "Tab"}},
    Enter: {code: 13, name: {mac: "\u21a9", other: "Enter"}},
    Ctrl: {code: 17, name: "Ctrl"},
    Esc: {code: 27, name: {mac: "\u238b", other: "Esc"}},
    Space: {code: 32, name: "Space"},
    PageUp: {code: 33, name: {mac: "\u21de", other: "PageUp"}},
    PageDown: {code: 34, name: {mac: "\u21df", other: "PageDown"}},
    End: {code: 35, name: {mac: "\u2197", other: "End"}},
    Home: {code: 36, name: {mac: "\u2196", other: "Home"}},
    Left: {code: 37, name: "\u2190"},
    Up: {code: 38, name: "\u2191"},
    Right: {code: 39, name: "\u2192"},
    Down: {code: 40, name: "\u2193"},
    Delete: {code: 46, name: "Del"},
    Zero: {code: 48, name: "0"},
    H: {code: 72, name: "H"},
    Meta: {code: 91, name: "Meta"},
    F1: {code: 112, name: "F1"},
    F2: {code: 113, name: "F2"},
    F3: {code: 114, name: "F3"},
    F4: {code: 115, name: "F4"},
    F5: {code: 116, name: "F5"},
    F6: {code: 117, name: "F6"},
    F7: {code: 118, name: "F7"},
    F8: {code: 119, name: "F8"},
    F9: {code: 120, name: "F9"},
    F10: {code: 121, name: "F10"},
    F11: {code: 122, name: "F11"},
    F12: {code: 123, name: "F12"},
    Semicolon: {code: 186, name: ";"},
    NumpadPlus: {code: 107, name: "Numpad +"},
    NumpadMinus: {code: 109, name: "Numpad -"},
    Numpad0: {code: 96, name: "Numpad 0"},
    Plus: {code: 187, name: "+"},
    Comma: {code: 188, name: ","},
    Minus: {code: 189, name: "-"},
    Period: {code: 190, name: "."},
    Slash: {code: 191, name: "/"},
    QuestionMark: {code: 191, name: "?"},
    Apostrophe: {code: 192, name: "`"},
    Tilde: {code: 192, name: "Tilde"},
    Backslash: {code: 220, name: "\\"},
    SingleQuote: {code: 222, name: "\'"},
    get CtrlOrMeta() {
        return WebInspector.isMac() ? this.Meta : this.Ctrl;
    },
};
WebInspector.KeyboardShortcut.KeyBindings = {};
(function () {
    for (var key in WebInspector.KeyboardShortcut.Keys) {
        var descriptor = WebInspector.KeyboardShortcut.Keys[key];
        if (typeof descriptor === "object" && descriptor["code"]) {
            var name = typeof descriptor["name"] === "string" ? descriptor["name"] : key;
            WebInspector.KeyboardShortcut.KeyBindings[name] = descriptor;
        }
    }
})();
WebInspector.KeyboardShortcut.makeKey = function (keyCode, modifiers) {
    if (typeof keyCode === "string")
        keyCode = keyCode.charCodeAt(0) - (/^[a-z]/.test(keyCode) ? 32 : 0);
    modifiers = modifiers || WebInspector.KeyboardShortcut.Modifiers.None;
    return WebInspector.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode, modifiers);
}
WebInspector.KeyboardShortcut.makeKeyFromEvent = function (keyboardEvent) {
    var modifiers = WebInspector.KeyboardShortcut.Modifiers.None;
    if (keyboardEvent.shiftKey)
        modifiers |= WebInspector.KeyboardShortcut.Modifiers.Shift;
    if (keyboardEvent.ctrlKey)
        modifiers |= WebInspector.KeyboardShortcut.Modifiers.Ctrl;
    if (keyboardEvent.altKey)
        modifiers |= WebInspector.KeyboardShortcut.Modifiers.Alt;
    if (keyboardEvent.metaKey)
        modifiers |= WebInspector.KeyboardShortcut.Modifiers.Meta;
    function keyCodeForEvent(keyboardEvent) {
        return keyboardEvent.keyCode || keyboardEvent["__keyCode"];
    }

    return WebInspector.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCodeForEvent(keyboardEvent), modifiers);
}
WebInspector.KeyboardShortcut.eventHasCtrlOrMeta = function (event) {
    return WebInspector.isMac() ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
}
WebInspector.KeyboardShortcut.hasNoModifiers = function (event) {
    return !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey;
}
WebInspector.KeyboardShortcut.Descriptor;
WebInspector.KeyboardShortcut.makeDescriptor = function (key, modifiers) {
    return {key: WebInspector.KeyboardShortcut.makeKey(typeof key === "string" ? key : key.code, modifiers), name: WebInspector.KeyboardShortcut.shortcutToString(key, modifiers)};
}
WebInspector.KeyboardShortcut.makeDescriptorFromBindingShortcut = function (shortcut) {
    var parts = shortcut.split(/\+(?!$)/);
    var modifiers = 0;
    var keyString;
    for (var i = 0; i < parts.length; ++i) {
        if (typeof WebInspector.KeyboardShortcut.Modifiers[parts[i]] !== "undefined") {
            modifiers |= WebInspector.KeyboardShortcut.Modifiers[parts[i]];
            continue;
        }
        console.assert(i === parts.length - 1, "Only one key other than modifier is allowed in shortcut <" + shortcut + ">");
        keyString = parts[i];
        break;
    }
    console.assert(keyString, "Modifiers-only shortcuts are not allowed (encountered <" + shortcut + ">)");
    if (!keyString)
        return null;
    var key = WebInspector.KeyboardShortcut.Keys[keyString] || WebInspector.KeyboardShortcut.KeyBindings[keyString];
    if (key && key.shiftKey)
        modifiers |= WebInspector.KeyboardShortcut.Modifiers.Shift;
    return WebInspector.KeyboardShortcut.makeDescriptor(key ? key : keyString, modifiers);
}
WebInspector.KeyboardShortcut.shortcutToString = function (key, modifiers) {
    return WebInspector.KeyboardShortcut._modifiersToString(modifiers) + WebInspector.KeyboardShortcut._keyName(key);
}
WebInspector.KeyboardShortcut._keyName = function (key) {
    if (typeof key === "string")
        return key.toUpperCase();
    if (typeof key.name === "string")
        return key.name;
    return key.name[WebInspector.platform()] || key.name.other || '';
}
WebInspector.KeyboardShortcut._makeKeyFromCodeAndModifiers = function (keyCode, modifiers) {
    return (keyCode & 255) | (modifiers << 8);
};
WebInspector.KeyboardShortcut.keyCodeAndModifiersFromKey = function (key) {
    return {keyCode: key & 255, modifiers: key >> 8};
}
WebInspector.KeyboardShortcut._modifiersToString = function (modifiers) {
    const cmdKey = "\u2318";
    const optKey = "\u2325";
    const shiftKey = "\u21e7";
    const ctrlKey = "\u2303";
    var isMac = WebInspector.isMac();
    var res = "";
    if (modifiers & WebInspector.KeyboardShortcut.Modifiers.Ctrl)
        res += isMac ? ctrlKey : "Ctrl + ";
    if (modifiers & WebInspector.KeyboardShortcut.Modifiers.Alt)
        res += isMac ? optKey : "Alt + ";
    if (modifiers & WebInspector.KeyboardShortcut.Modifiers.Shift)
        res += isMac ? shiftKey : "Shift + ";
    if (modifiers & WebInspector.KeyboardShortcut.Modifiers.Meta)
        res += isMac ? cmdKey : "Win + ";
    return res;
};
WebInspector.KeyboardShortcut.SelectAll = WebInspector.KeyboardShortcut.makeKey("a", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta);
WebInspector.ShortcutRegistry = function (actionRegistry) {
    this._actionRegistry = actionRegistry;
    this._defaultKeyToActions = new StringMultimap();
    this._defaultActionToShortcut = new StringMultimap();
    this._registerBindings();
}
WebInspector.ShortcutRegistry.prototype = {
    applicableActions: function (key) {
        return this._actionRegistry.applicableActions(this._actionIdsForKey(key), WebInspector.context);
    }, _actionIdsForKey: function (key) {
        var result = new StringSet();
        var defaults = this._defaultActionsForKey(key);
        defaults.values().forEach(function (actionId) {
            result.add(actionId);
        }, this);
        return result.values();
    }, _defaultActionsForKey: function (key) {
        return this._defaultKeyToActions.get(String(key));
    }, shortcutDescriptorsForAction: function (actionId) {
        return this._defaultActionToShortcut.get(actionId).values();
    }, keysForActions: function (actionIds) {
        var result = [];
        for (var i = 0; i < actionIds.length; ++i) {
            var descriptors = this.shortcutDescriptorsForAction(actionIds[i]);
            for (var j = 0; j < descriptors.length; ++j)
                result.push(descriptors[j].key);
        }
        return result;
    }, handleShortcut: function (event) {
        this.handleKey(WebInspector.KeyboardShortcut.makeKeyFromEvent(event), event.keyIdentifier, event);
    }, handleKey: function (key, keyIdentifier, event) {
        var keyModifiers = key >> 8;
        var actionIds = this.applicableActions(key);
        if (WebInspector.GlassPane.DefaultFocusedViewStack.length > 1) {
            if (actionIds.length && !isPossiblyInputKey())
                event.consume(true);
            return;
        }
        for (var i = 0; i < actionIds.length; ++i) {
            if (!isPossiblyInputKey()) {
                if (handler.call(this, actionIds[i]))
                    break;
            } else {
                this._pendingActionTimer = setTimeout(handler.bind(this, actionIds[i]), 0);
                break;
            }
        }
        function isPossiblyInputKey() {
            if (!event || !WebInspector.isBeingEdited((event.target)) || /^F\d+|Control|Shift|Alt|Meta|Win|U\+001B$/.test(keyIdentifier))
                return false;
            if (!keyModifiers)
                return true;
            var modifiers = WebInspector.KeyboardShortcut.Modifiers;
            if ((keyModifiers & (modifiers.Ctrl | modifiers.Alt)) === (modifiers.Ctrl | modifiers.Alt))
                return WebInspector.isWin();
            return !hasModifier(modifiers.Ctrl) && !hasModifier(modifiers.Alt) && !hasModifier(modifiers.Meta);
        }

        function hasModifier(mod) {
            return !!(keyModifiers & mod);
        }

        function handler(actionId) {
            var result = this._actionRegistry.execute(actionId);
            if (result && event)
                event.consume(true);
            delete this._pendingActionTimer;
            return result;
        }
    }, registerShortcut: function (actionId, shortcut) {
        var descriptor = WebInspector.KeyboardShortcut.makeDescriptorFromBindingShortcut(shortcut);
        if (!descriptor)
            return;
        this._defaultActionToShortcut.put(actionId, descriptor);
        this._defaultKeyToActions.put(String(descriptor.key), actionId);
    }, _onInput: function (event) {
        if (this._pendingActionTimer) {
            clearTimeout(this._pendingActionTimer);
            delete this._pendingActionTimer;
        }
    }, _registerBindings: function () {
        document.addEventListener("input", this._onInput.bind(this), true);
        var extensions = self.runtime.extensions(WebInspector.ActionDelegate);
        extensions.forEach(registerExtension, this);
        function registerExtension(extension) {
            var descriptor = extension.descriptor();
            var bindings = descriptor["bindings"];
            for (var i = 0; bindings && i < bindings.length; ++i) {
                if (!platformMatches(bindings[i].platform))
                    continue;
                var shortcuts = bindings[i]["shortcut"].split(/\s+/);
                shortcuts.forEach(this.registerShortcut.bind(this, descriptor["actionId"]));
            }
        }

        function platformMatches(platformsString) {
            if (!platformsString)
                return true;
            var platforms = platformsString.split(",");
            var isMatch = false;
            var currentPlatform = WebInspector.platform();
            for (var i = 0; !isMatch && i < platforms.length; ++i)
                isMatch = platforms[i] === currentPlatform;
            return isMatch;
        }
    }
}
WebInspector.ShortcutRegistry.ForwardedShortcut = function () {
}
WebInspector.ShortcutRegistry.ForwardedShortcut.instance = new WebInspector.ShortcutRegistry.ForwardedShortcut();
WebInspector.shortcutRegistry;
WebInspector.SuggestBoxDelegate = function () {
}
WebInspector.SuggestBoxDelegate.prototype = {
    applySuggestion: function (suggestion, isIntermediateSuggestion) {
    }, acceptSuggestion: function () {
    },
}
WebInspector.SuggestBox = function (suggestBoxDelegate, maxItemsHeight) {
    this._suggestBoxDelegate = suggestBoxDelegate;
    this._length = 0;
    this._selectedIndex = -1;
    this._selectedElement = null;
    this._maxItemsHeight = maxItemsHeight;
    this._bodyElement = document.body;
    this._maybeHideBound = this._maybeHide.bind(this);
    this._element = document.createElementWithClass("div", "suggest-box");
    this._element.addEventListener("mousedown", this._onBoxMouseDown.bind(this), true);
}
WebInspector.SuggestBox.prototype = {
    visible: function () {
        return !!this._element.parentElement;
    }, setPosition: function (anchorBox) {
        this._updateBoxPosition(anchorBox);
    }, _updateBoxPosition: function (anchorBox) {
        console.assert(this._overlay);
        if (this._lastAnchorBox && this._lastAnchorBox.equals(anchorBox))
            return;
        this._lastAnchorBox = anchorBox;
        var container = WebInspector.Dialog.modalHostView().element;
        anchorBox = anchorBox.relativeToElement(container);
        var totalWidth = container.offsetWidth;
        var totalHeight = container.offsetHeight;
        var aboveHeight = anchorBox.y;
        var underHeight = totalHeight - anchorBox.y - anchorBox.height;
        var rowHeight = 17;
        const spacer = 6;
        var maxHeight = this._maxItemsHeight ? this._maxItemsHeight * rowHeight : Math.max(underHeight, aboveHeight) - spacer;
        var under = underHeight >= aboveHeight;
        this._leftSpacerElement.style.flexBasis = anchorBox.x + "px";
        this._overlay.element.classList.toggle("under-anchor", under);
        if (under) {
            this._bottomSpacerElement.style.flexBasis = "auto";
            this._topSpacerElement.style.flexBasis = (anchorBox.y + anchorBox.height) + "px";
        } else {
            this._bottomSpacerElement.style.flexBasis = (totalHeight - anchorBox.y) + "px";
            this._topSpacerElement.style.flexBasis = "auto";
        }
        this._element.style.maxHeight = maxHeight + "px";
    }, _onBoxMouseDown: function (event) {
        if (this._hideTimeoutId) {
            window.clearTimeout(this._hideTimeoutId);
            delete this._hideTimeoutId;
        }
        event.preventDefault();
    }, _maybeHide: function () {
        if (!this._hideTimeoutId)
            this._hideTimeoutId = window.setTimeout(this.hide.bind(this), 0);
    }, _show: function () {
        if (this.visible())
            return;
        this._overlay = new WebInspector.SuggestBox.Overlay();
        this._bodyElement.addEventListener("mousedown", this._maybeHideBound, true);
        this._leftSpacerElement = this._overlay.element.createChild("div", "suggest-box-left-spacer");
        this._horizontalElement = this._overlay.element.createChild("div", "suggest-box-horizontal");
        this._topSpacerElement = this._horizontalElement.createChild("div", "suggest-box-top-spacer");
        this._horizontalElement.appendChild(this._element);
        this._bottomSpacerElement = this._horizontalElement.createChild("div", "suggest-box-bottom-spacer");
    }, hide: function () {
        if (!this.visible())
            return;
        this._bodyElement.removeEventListener("mousedown", this._maybeHideBound, true);
        this._element.remove();
        this._overlay.dispose();
        delete this._overlay;
        delete this._selectedElement;
        this._selectedIndex = -1;
        delete this._lastAnchorBox;
    }, removeFromElement: function () {
        this.hide();
    }, _applySuggestion: function (isIntermediateSuggestion) {
        if (!this.visible() || !this._selectedElement)
            return false;
        var suggestion = this._selectedElement.textContent;
        if (!suggestion)
            return false;
        this._suggestBoxDelegate.applySuggestion(suggestion, isIntermediateSuggestion);
        return true;
    }, acceptSuggestion: function () {
        var result = this._applySuggestion();
        this.hide();
        if (!result)
            return false;
        this._suggestBoxDelegate.acceptSuggestion();
        return true;
    }, _selectClosest: function (shift, isCircular) {
        if (!this._length)
            return false;
        if (this._selectedIndex === -1 && shift < 0)
            shift += 1;
        var index = this._selectedIndex + shift;
        if (isCircular)
            index = (this._length + index) % this._length; else
            index = Number.constrain(index, 0, this._length - 1);
        this._selectItem(index, true);
        this._applySuggestion(true);
        return true;
    }, _onItemMouseDown: function (event) {
        this._selectedElement = event.currentTarget;
        this.acceptSuggestion();
        event.consume(true);
    }, _createItemElement: function (prefix, text) {
        var element = document.createElementWithClass("div", "suggest-box-content-item source-code");
        element.tabIndex = -1;
        if (prefix && prefix.length && !text.indexOf(prefix)) {
            element.createChild("span", "prefix").textContent = prefix;
            element.createChild("span", "suffix").textContent = text.substring(prefix.length);
        } else {
            element.createChild("span", "suffix").textContent = text;
        }
        element.createChild("span", "spacer");
        element.addEventListener("mousedown", this._onItemMouseDown.bind(this), false);
        return element;
    }, _updateItems: function (items, userEnteredText) {
        this._length = items.length;
        this._element.removeChildren();
        delete this._selectedElement;
        for (var i = 0; i < items.length; ++i) {
            var item = items[i];
            var currentItemElement = this._createItemElement(userEnteredText, item);
            this._element.appendChild(currentItemElement);
        }
    }, _selectItem: function (index, scrollIntoView) {
        if (this._selectedElement)
            this._selectedElement.classList.remove("selected");
        this._selectedIndex = index;
        if (index < 0)
            return;
        this._selectedElement = this._element.children[index];
        this._selectedElement.classList.add("selected");
        if (scrollIntoView)
            this._selectedElement.scrollIntoViewIfNeeded(false);
    }, _canShowBox: function (completions, canShowForSingleItem, userEnteredText) {
        if (!completions || !completions.length)
            return false;
        if (completions.length > 1)
            return true;
        return canShowForSingleItem && completions[0] !== userEnteredText;
    }, _ensureRowCountPerViewport: function () {
        if (this._rowCountPerViewport)
            return;
        if (!this._element.firstChild)
            return;
        this._rowCountPerViewport = Math.floor(this._element.offsetHeight / this._element.firstChild.offsetHeight);
    }, updateSuggestions: function (anchorBox, completions, selectedIndex, canShowForSingleItem, userEnteredText) {
        if (this._canShowBox(completions, canShowForSingleItem, userEnteredText)) {
            this._updateItems(completions, userEnteredText);
            this._show();
            this._updateBoxPosition(anchorBox);
            this._selectItem(selectedIndex, selectedIndex > 0);
            delete this._rowCountPerViewport;
        } else
            this.hide();
    }, keyPressed: function (event) {
        switch (event.keyIdentifier) {
            case"Up":
                return this.upKeyPressed();
            case"Down":
                return this.downKeyPressed();
            case"PageUp":
                return this.pageUpKeyPressed();
            case"PageDown":
                return this.pageDownKeyPressed();
            case"Enter":
                return this.enterKeyPressed();
        }
        return false;
    }, upKeyPressed: function () {
        return this._selectClosest(-1, true);
    }, downKeyPressed: function () {
        return this._selectClosest(1, true);
    }, pageUpKeyPressed: function () {
        this._ensureRowCountPerViewport();
        return this._selectClosest(-this._rowCountPerViewport, false);
    }, pageDownKeyPressed: function () {
        this._ensureRowCountPerViewport();
        return this._selectClosest(this._rowCountPerViewport, false);
    }, enterKeyPressed: function () {
        var hasSelectedItem = !!this._selectedElement;
        this.acceptSuggestion();
        return hasSelectedItem;
    }
}
WebInspector.SuggestBox.Overlay = function () {
    this.element = document.createElementWithClass("div", "suggest-box-overlay");
    this._resize();
    document.body.appendChild(this.element);
}
WebInspector.SuggestBox.Overlay.prototype = {
    _resize: function () {
        var container = WebInspector.Dialog.modalHostView().element;
        var containerBox = container.boxInWindow(container.ownerDocument.defaultView);
        this.element.style.left = containerBox.x + "px";
        this.element.style.top = containerBox.y + "px";
        this.element.style.height = containerBox.height + "px";
        this.element.style.width = containerBox.width + "px";
    }, dispose: function () {
        this.element.remove();
    }
}
WebInspector.TextPrompt = function (completions, stopCharacters) {
    this._proxyElement;
    this._proxyElementDisplay = "inline-block";
    this._loadCompletions = completions;
    this._completionStopCharacters = stopCharacters || " =:[({;,!+-*/&|^<>.";
}
WebInspector.TextPrompt.Events = {ItemApplied: "text-prompt-item-applied", ItemAccepted: "text-prompt-item-accepted"};
WebInspector.TextPrompt.prototype = {
    get proxyElement() {
        return this._proxyElement;
    }, setSuggestBoxEnabled: function (suggestBoxEnabled) {
        this._suggestBoxEnabled = suggestBoxEnabled;
    }, renderAsBlock: function () {
        this._proxyElementDisplay = "block";
    }, attach: function (element) {
        return this._attachInternal(element);
    }, attachAndStartEditing: function (element, blurListener) {
        this._attachInternal(element);
        this._startEditing(blurListener);
        return this.proxyElement;
    }, _attachInternal: function (element) {
        if (this.proxyElement)
            throw"Cannot attach an attached TextPrompt";
        this._element = element;
        this._boundOnKeyDown = this.onKeyDown.bind(this);
        this._boundOnInput = this.onInput.bind(this);
        this._boundOnMouseWheel = this.onMouseWheel.bind(this);
        this._boundSelectStart = this._selectStart.bind(this);
        this._boundRemoveSuggestionAids = this._removeSuggestionAids.bind(this);
        this._proxyElement = element.ownerDocument.createElement("span");
        this._proxyElement.style.display = this._proxyElementDisplay;
        element.parentElement.insertBefore(this.proxyElement, element);
        this.proxyElement.appendChild(element);
        this._element.classList.add("text-prompt");
        this._element.addEventListener("keydown", this._boundOnKeyDown, false);
        this._element.addEventListener("input", this._boundOnInput, false);
        this._element.addEventListener("mousewheel", this._boundOnMouseWheel, false);
        this._element.addEventListener("selectstart", this._boundSelectStart, false);
        this._element.addEventListener("blur", this._boundRemoveSuggestionAids, false);
        if (this._suggestBoxEnabled)
            this._suggestBox = new WebInspector.SuggestBox(this);
        return this.proxyElement;
    }, detach: function () {
        this._removeFromElement();
        this.proxyElement.parentElement.insertBefore(this._element, this.proxyElement);
        this.proxyElement.remove();
        delete this._proxyElement;
        this._element.classList.remove("text-prompt");
        WebInspector.restoreFocusFromElement(this._element);
    }, get text() {
        return this._element.textContent;
    }, set text(x) {
        this._removeSuggestionAids();
        if (!x) {
            this._element.removeChildren();
            this._element.createChild("br");
        } else {
            this._element.textContent = x;
        }
        this.moveCaretToEndOfPrompt();
        this._element.scrollIntoView();
    }, _removeFromElement: function () {
        this.clearAutoComplete(true);
        this._element.removeEventListener("keydown", this._boundOnKeyDown, false);
        this._element.removeEventListener("input", this._boundOnInput, false);
        this._element.removeEventListener("selectstart", this._boundSelectStart, false);
        this._element.removeEventListener("blur", this._boundRemoveSuggestionAids, false);
        if (this._isEditing)
            this._stopEditing();
        if (this._suggestBox)
            this._suggestBox.removeFromElement();
    }, _startEditing: function (blurListener) {
        this._isEditing = true;
        this._element.classList.add("editing");
        if (blurListener) {
            this._blurListener = blurListener;
            this._element.addEventListener("blur", this._blurListener, false);
        }
        this._oldTabIndex = this._element.tabIndex;
        if (this._element.tabIndex < 0)
            this._element.tabIndex = 0;
        WebInspector.setCurrentFocusElement(this._element);
        if (!this.text)
            this._updateAutoComplete();
    }, _stopEditing: function () {
        this._element.tabIndex = this._oldTabIndex;
        if (this._blurListener)
            this._element.removeEventListener("blur", this._blurListener, false);
        this._element.classList.remove("editing");
        delete this._isEditing;
    }, _removeSuggestionAids: function () {
        this.clearAutoComplete();
        this.hideSuggestBox();
    }, _selectStart: function () {
        if (this._selectionTimeout)
            clearTimeout(this._selectionTimeout);
        this._removeSuggestionAids();
        function moveBackIfOutside() {
            delete this._selectionTimeout;
            if (!this.isCaretInsidePrompt() && window.getSelection().isCollapsed) {
                this.moveCaretToEndOfPrompt();
                this.autoCompleteSoon();
            }
        }

        this._selectionTimeout = setTimeout(moveBackIfOutside.bind(this), 100);
    }, _updateAutoComplete: function (force) {
        this.clearAutoComplete();
        this.autoCompleteSoon(force);
    }, onMouseWheel: function (event) {
    }, onKeyDown: function (event) {
        var handled = false;
        delete this._needUpdateAutocomplete;
        switch (event.keyIdentifier) {
            case"U+0009":
                handled = this.tabKeyPressed(event);
                break;
            case"Left":
            case"Home":
                this._removeSuggestionAids();
                break;
            case"Right":
            case"End":
                if (this.isCaretAtEndOfPrompt())
                    handled = this.acceptAutoComplete(); else
                    this._removeSuggestionAids();
                break;
            case"U+001B":
                if (this.isSuggestBoxVisible()) {
                    this._removeSuggestionAids();
                    handled = true;
                }
                break;
            case"U+0020":
                if (event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
                    this._updateAutoComplete(true);
                    handled = true;
                }
                break;
            case"Alt":
            case"Meta":
            case"Shift":
            case"Control":
                break;
        }
        if (!handled && this.isSuggestBoxVisible())
            handled = this._suggestBox.keyPressed(event);
        if (!handled)
            this._needUpdateAutocomplete = true;
        if (handled)
            event.consume(true);
    }, onInput: function (event) {
        if (this._needUpdateAutocomplete)
            this._updateAutoComplete();
    }, acceptAutoComplete: function () {
        var result = false;
        if (this.isSuggestBoxVisible())
            result = this._suggestBox.acceptSuggestion();
        if (!result)
            result = this._acceptSuggestionInternal();
        return result;
    }, clearAutoComplete: function (includeTimeout) {
        if (includeTimeout && this._completeTimeout) {
            clearTimeout(this._completeTimeout);
            delete this._completeTimeout;
        }
        delete this._waitingForCompletions;
        if (!this.autoCompleteElement)
            return;
        this.autoCompleteElement.remove();
        delete this.autoCompleteElement;
        delete this._userEnteredRange;
        delete this._userEnteredText;
    }, autoCompleteSoon: function (force) {
        var immediately = this.isSuggestBoxVisible() || force;
        if (!this._completeTimeout)
            this._completeTimeout = setTimeout(this.complete.bind(this, force), immediately ? 0 : 250);
    }, complete: function (force, reverse) {
        this.clearAutoComplete(true);
        var selection = window.getSelection();
        if (!selection.rangeCount)
            return;
        var selectionRange = selection.getRangeAt(0);
        var shouldExit;
        if (!force && !this.isCaretAtEndOfPrompt() && !this.isSuggestBoxVisible())
            shouldExit = true; else if (!selection.isCollapsed)
            shouldExit = true; else if (!force) {
            var wordSuffixRange = selectionRange.startContainer.rangeOfWord(selectionRange.endOffset, this._completionStopCharacters, this._element, "forward");
            if (wordSuffixRange.toString().length)
                shouldExit = true;
        }
        if (shouldExit) {
            this.hideSuggestBox();
            return;
        }
        var wordPrefixRange = selectionRange.startContainer.rangeOfWord(selectionRange.startOffset, this._completionStopCharacters, this._element, "backward");
        this._waitingForCompletions = true;
        this._loadCompletions(this.proxyElement, wordPrefixRange, force || false, this._completionsReady.bind(this, selection, wordPrefixRange, !!reverse));
    }, disableDefaultSuggestionForEmptyInput: function () {
        this._disableDefaultSuggestionForEmptyInput = true;
    }, _boxForAnchorAtStart: function (selection, textRange) {
        var rangeCopy = selection.getRangeAt(0).cloneRange();
        var anchorElement = document.createElement("span");
        anchorElement.textContent = "\u200B";
        textRange.insertNode(anchorElement);
        var box = anchorElement.boxInWindow(window);
        anchorElement.remove();
        selection.removeAllRanges();
        selection.addRange(rangeCopy);
        return box;
    }, _buildCommonPrefix: function (completions, wordPrefixLength) {
        var commonPrefix = completions[0];
        for (var i = 0; i < completions.length; ++i) {
            var completion = completions[i];
            var lastIndex = Math.min(commonPrefix.length, completion.length);
            for (var j = wordPrefixLength; j < lastIndex; ++j) {
                if (commonPrefix[j] !== completion[j]) {
                    commonPrefix = commonPrefix.substr(0, j);
                    break;
                }
            }
        }
        return commonPrefix;
    }, _completionsReady: function (selection, originalWordPrefixRange, reverse, completions, selectedIndex) {
        if (!this._waitingForCompletions || !completions.length) {
            this.hideSuggestBox();
            return;
        }
        delete this._waitingForCompletions;
        var selectionRange = selection.getRangeAt(0);
        var fullWordRange = document.createRange();
        fullWordRange.setStart(originalWordPrefixRange.startContainer, originalWordPrefixRange.startOffset);
        fullWordRange.setEnd(selectionRange.endContainer, selectionRange.endOffset);
        if (originalWordPrefixRange.toString() + selectionRange.toString() !== fullWordRange.toString())
            return;
        selectedIndex = (this._disableDefaultSuggestionForEmptyInput && !this.text) ? -1 : (selectedIndex || 0);
        this._userEnteredRange = fullWordRange;
        this._userEnteredText = fullWordRange.toString();
        if (this._suggestBox)
            this._suggestBox.updateSuggestions(this._boxForAnchorAtStart(selection, fullWordRange), completions, selectedIndex, !this.isCaretAtEndOfPrompt(), this._userEnteredText);
        if (selectedIndex === -1)
            return;
        var wordPrefixLength = originalWordPrefixRange.toString().length;
        this._commonPrefix = this._buildCommonPrefix(completions, wordPrefixLength);
        if (this.isCaretAtEndOfPrompt()) {
            var completionText = completions[selectedIndex];
            var prefixText = this._userEnteredRange.toString();
            var suffixText = completionText.substring(wordPrefixLength);
            this._userEnteredRange.deleteContents();
            this._element.normalize();
            var finalSelectionRange = document.createRange();
            var prefixTextNode = document.createTextNode(prefixText);
            fullWordRange.insertNode(prefixTextNode);
            this.autoCompleteElement = document.createElementWithClass("span", "auto-complete-text");
            this.autoCompleteElement.textContent = suffixText;
            prefixTextNode.parentNode.insertBefore(this.autoCompleteElement, prefixTextNode.nextSibling);
            finalSelectionRange.setStart(prefixTextNode, wordPrefixLength);
            finalSelectionRange.setEnd(prefixTextNode, wordPrefixLength);
            selection.removeAllRanges();
            selection.addRange(finalSelectionRange);
            this.dispatchEventToListeners(WebInspector.TextPrompt.Events.ItemApplied);
        }
    }, _completeCommonPrefix: function () {
        if (!this.autoCompleteElement || !this._commonPrefix || !this._userEnteredText || !this._commonPrefix.startsWith(this._userEnteredText))
            return;
        if (!this.isSuggestBoxVisible()) {
            this.acceptAutoComplete();
            return;
        }
        this.autoCompleteElement.textContent = this._commonPrefix.substring(this._userEnteredText.length);
        this._acceptSuggestionInternal(true);
    }, applySuggestion: function (completionText, isIntermediateSuggestion) {
        this._applySuggestion(completionText, isIntermediateSuggestion);
    }, _applySuggestion: function (completionText, isIntermediateSuggestion, originalPrefixRange) {
        var wordPrefixLength;
        if (originalPrefixRange)
            wordPrefixLength = originalPrefixRange.toString().length; else
            wordPrefixLength = this._userEnteredText ? this._userEnteredText.length : 0;
        this._userEnteredRange.deleteContents();
        this._element.normalize();
        var finalSelectionRange = document.createRange();
        var completionTextNode = document.createTextNode(completionText);
        this._userEnteredRange.insertNode(completionTextNode);
        if (this.autoCompleteElement) {
            this.autoCompleteElement.remove();
            delete this.autoCompleteElement;
        }
        if (isIntermediateSuggestion)
            finalSelectionRange.setStart(completionTextNode, wordPrefixLength); else
            finalSelectionRange.setStart(completionTextNode, completionText.length);
        finalSelectionRange.setEnd(completionTextNode, completionText.length);
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(finalSelectionRange);
        if (isIntermediateSuggestion)
            this.dispatchEventToListeners(WebInspector.TextPrompt.Events.ItemApplied, {itemText: completionText});
    }, acceptSuggestion: function () {
        this._acceptSuggestionInternal();
    }, _acceptSuggestionInternal: function (prefixAccepted) {
        if (this._isAcceptingSuggestion)
            return false;
        if (!this.autoCompleteElement || !this.autoCompleteElement.parentNode)
            return false;
        var text = this.autoCompleteElement.textContent;
        var textNode = document.createTextNode(text);
        this.autoCompleteElement.parentNode.replaceChild(textNode, this.autoCompleteElement);
        delete this.autoCompleteElement;
        var finalSelectionRange = document.createRange();
        finalSelectionRange.setStart(textNode, text.length);
        finalSelectionRange.setEnd(textNode, text.length);
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(finalSelectionRange);
        if (!prefixAccepted) {
            this.hideSuggestBox();
            this.dispatchEventToListeners(WebInspector.TextPrompt.Events.ItemAccepted);
        } else
            this.autoCompleteSoon(true);
        return true;
    }, hideSuggestBox: function () {
        if (this.isSuggestBoxVisible())
            this._suggestBox.hide();
    }, isSuggestBoxVisible: function () {
        return this._suggestBox && this._suggestBox.visible();
    }, isCaretInsidePrompt: function () {
        return this._element.isInsertionCaretInside();
    }, isCaretAtEndOfPrompt: function () {
        var selection = window.getSelection();
        if (!selection.rangeCount || !selection.isCollapsed)
            return false;
        var selectionRange = selection.getRangeAt(0);
        var node = selectionRange.startContainer;
        if (!node.isSelfOrDescendant(this._element))
            return false;
        if (node.nodeType === Node.TEXT_NODE && selectionRange.startOffset < node.nodeValue.length)
            return false;
        var foundNextText = false;
        while (node) {
            if (node.nodeType === Node.TEXT_NODE && node.nodeValue.length) {
                if (foundNextText && (!this.autoCompleteElement || !this.autoCompleteElement.isAncestor(node)))
                    return false;
                foundNextText = true;
            }
            node = node.traverseNextNode(this._element);
        }
        return true;
    }, isCaretOnFirstLine: function () {
        var selection = window.getSelection();
        var focusNode = selection.focusNode;
        if (!focusNode || focusNode.nodeType !== Node.TEXT_NODE || focusNode.parentNode !== this._element)
            return true;
        if (focusNode.textContent.substring(0, selection.focusOffset).indexOf("\n") !== -1)
            return false;
        focusNode = focusNode.previousSibling;
        while (focusNode) {
            if (focusNode.nodeType !== Node.TEXT_NODE)
                return true;
            if (focusNode.textContent.indexOf("\n") !== -1)
                return false;
            focusNode = focusNode.previousSibling;
        }
        return true;
    }, isCaretOnLastLine: function () {
        var selection = window.getSelection();
        var focusNode = selection.focusNode;
        if (!focusNode || focusNode.nodeType !== Node.TEXT_NODE || focusNode.parentNode !== this._element)
            return true;
        if (focusNode.textContent.substring(selection.focusOffset).indexOf("\n") !== -1)
            return false;
        focusNode = focusNode.nextSibling;
        while (focusNode) {
            if (focusNode.nodeType !== Node.TEXT_NODE)
                return true;
            if (focusNode.textContent.indexOf("\n") !== -1)
                return false;
            focusNode = focusNode.nextSibling;
        }
        return true;
    }, moveCaretToEndOfPrompt: function () {
        var selection = window.getSelection();
        var selectionRange = document.createRange();
        var offset = this._element.childNodes.length;
        selectionRange.setStart(this._element, offset);
        selectionRange.setEnd(this._element, offset);
        selection.removeAllRanges();
        selection.addRange(selectionRange);
    }, tabKeyPressed: function (event) {
        this._completeCommonPrefix();
        return true;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.TextPromptWithHistory = function (completions, stopCharacters) {
    WebInspector.TextPrompt.call(this, completions, stopCharacters);
    this._data = [];
    this._historyOffset = 1;
    this._coalesceHistoryDupes = true;
}
WebInspector.TextPromptWithHistory.prototype = {
    get historyData() {
        return this._data;
    }, setCoalesceHistoryDupes: function (x) {
        this._coalesceHistoryDupes = x;
    }, setHistoryData: function (data) {
        this._data = [].concat(data);
        this._historyOffset = 1;
    }, pushHistoryItem: function (text) {
        if (this._uncommittedIsTop) {
            this._data.pop();
            delete this._uncommittedIsTop;
        }
        this._historyOffset = 1;
        if (this._coalesceHistoryDupes && text === this._currentHistoryItem())
            return;
        this._data.push(text);
    }, _pushCurrentText: function () {
        if (this._uncommittedIsTop)
            this._data.pop();
        this._uncommittedIsTop = true;
        this.clearAutoComplete(true);
        this._data.push(this.text);
    }, _previous: function () {
        if (this._historyOffset > this._data.length)
            return undefined;
        if (this._historyOffset === 1)
            this._pushCurrentText();
        ++this._historyOffset;
        return this._currentHistoryItem();
    }, _next: function () {
        if (this._historyOffset === 1)
            return undefined;
        --this._historyOffset;
        return this._currentHistoryItem();
    }, _currentHistoryItem: function () {
        return this._data[this._data.length - this._historyOffset];
    }, onKeyDown: function (event) {
        var newText;
        var isPrevious;
        switch (event.keyIdentifier) {
            case"Up":
                if (!this.isCaretOnFirstLine() || this.isSuggestBoxVisible())
                    break;
                newText = this._previous();
                isPrevious = true;
                break;
            case"Down":
                if (!this.isCaretOnLastLine() || this.isSuggestBoxVisible())
                    break;
                newText = this._next();
                break;
            case"U+0050":
                if (WebInspector.isMac() && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
                    newText = this._previous();
                    isPrevious = true;
                }
                break;
            case"U+004E":
                if (WebInspector.isMac() && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey)
                    newText = this._next();
                break;
        }
        if (newText !== undefined) {
            event.consume(true);
            this.text = newText;
            if (isPrevious) {
                var firstNewlineIndex = this.text.indexOf("\n");
                if (firstNewlineIndex === -1)
                    this.moveCaretToEndOfPrompt(); else {
                    var selection = window.getSelection();
                    var selectionRange = document.createRange();
                    selectionRange.setStart(this._element.firstChild, firstNewlineIndex);
                    selectionRange.setEnd(this._element.firstChild, firstNewlineIndex);
                    selection.removeAllRanges();
                    selection.addRange(selectionRange);
                }
            }
            return;
        }
        WebInspector.TextPrompt.prototype.onKeyDown.apply(this, arguments);
    }, __proto__: WebInspector.TextPrompt.prototype
}
WebInspector.Popover = function (popoverHelper) {
    WebInspector.View.call(this);
    this.markAsRoot();
    this.element.className = "popover custom-popup-vertical-scroll custom-popup-horizontal-scroll";
    this._containerElement = document.createElementWithClass("div", "fill popover-container");
    this._popupArrowElement = this.element.createChild("div", "arrow");
    this._contentDiv = this.element.createChild("div", "content");
    this._popoverHelper = popoverHelper;
    this._hideBound = this.hide.bind(this);
}
WebInspector.Popover.prototype = {
    show: function (element, anchor, preferredWidth, preferredHeight, arrowDirection) {
        this._innerShow(null, element, anchor, preferredWidth, preferredHeight, arrowDirection);
    }, showView: function (view, anchor, preferredWidth, preferredHeight) {
        this._innerShow(view, view.element, anchor, preferredWidth, preferredHeight);
    }, _innerShow: function (view, contentElement, anchor, preferredWidth, preferredHeight, arrowDirection) {
        if (this._disposed)
            return;
        this.contentElement = contentElement;
        if (WebInspector.Popover._popover)
            WebInspector.Popover._popover.hide();
        WebInspector.Popover._popover = this;
        var preferredSize = view ? view.measurePreferredSize() : this.contentElement.measurePreferredSize();
        preferredWidth = preferredWidth || preferredSize.width;
        preferredHeight = preferredHeight || preferredSize.height;
        window.addEventListener("resize", this._hideBound, false);
        document.body.appendChild(this._containerElement);
        WebInspector.View.prototype.show.call(this, this._containerElement);
        if (view)
            view.show(this._contentDiv); else
            this._contentDiv.appendChild(this.contentElement);
        this._positionElement(anchor, preferredWidth, preferredHeight, arrowDirection);
        if (this._popoverHelper) {
            this._contentDiv.addEventListener("mousemove", this._popoverHelper._killHidePopoverTimer.bind(this._popoverHelper), true);
            this.element.addEventListener("mouseout", this._popoverHelper._popoverMouseOut.bind(this._popoverHelper), true);
        }
    }, hide: function () {
        window.removeEventListener("resize", this._hideBound, false);
        this.detach();
        this._containerElement.remove();
        delete WebInspector.Popover._popover;
    }, get disposed() {
        return this._disposed;
    }, dispose: function () {
        if (this.isShowing())
            this.hide();
        this._disposed = true;
    }, setCanShrink: function (canShrink) {
        this._hasFixedHeight = !canShrink;
        this._contentDiv.classList.add("fixed-height");
    }, _positionElement: function (anchorElement, preferredWidth, preferredHeight, arrowDirection) {
        const borderWidth = 25;
        const scrollerWidth = this._hasFixedHeight ? 0 : 11;
        const arrowHeight = 15;
        const arrowOffset = 10;
        const borderRadius = 10;
        preferredWidth = Math.max(preferredWidth, 50);
        const container = WebInspector.Dialog.modalHostView().element;
        const totalWidth = container.offsetWidth;
        const totalHeight = container.offsetHeight;
        var anchorBox = anchorElement instanceof AnchorBox ? anchorElement : anchorElement.boxInWindow(window);
        anchorBox = anchorBox.relativeToElement(container);
        var newElementPosition = {x: 0, y: 0, width: preferredWidth + scrollerWidth, height: preferredHeight};
        var verticalAlignment;
        var roomAbove = anchorBox.y;
        var roomBelow = totalHeight - anchorBox.y - anchorBox.height;
        if ((roomAbove > roomBelow) || (arrowDirection === WebInspector.Popover.Orientation.Bottom)) {
            if ((anchorBox.y > newElementPosition.height + arrowHeight + borderRadius) || (arrowDirection === WebInspector.Popover.Orientation.Bottom))
                newElementPosition.y = anchorBox.y - newElementPosition.height - arrowHeight; else {
                newElementPosition.y = borderRadius;
                newElementPosition.height = anchorBox.y - borderRadius * 2 - arrowHeight;
                if (this._hasFixedHeight && newElementPosition.height < preferredHeight) {
                    newElementPosition.y = borderRadius;
                    newElementPosition.height = preferredHeight;
                }
            }
            verticalAlignment = WebInspector.Popover.Orientation.Bottom;
        } else {
            newElementPosition.y = anchorBox.y + anchorBox.height + arrowHeight;
            if ((newElementPosition.y + newElementPosition.height + borderRadius >= totalHeight) && (arrowDirection !== WebInspector.Popover.Orientation.Top)) {
                newElementPosition.height = totalHeight - borderRadius - newElementPosition.y;
                if (this._hasFixedHeight && newElementPosition.height < preferredHeight) {
                    newElementPosition.y = totalHeight - preferredHeight - borderRadius;
                    newElementPosition.height = preferredHeight;
                }
            }
            verticalAlignment = WebInspector.Popover.Orientation.Top;
        }
        var horizontalAlignment;
        if (anchorBox.x + newElementPosition.width < totalWidth) {
            newElementPosition.x = Math.max(borderRadius, anchorBox.x - borderRadius - arrowOffset);
            horizontalAlignment = "left";
        } else if (newElementPosition.width + borderRadius * 2 < totalWidth) {
            newElementPosition.x = totalWidth - newElementPosition.width - borderRadius;
            horizontalAlignment = "right";
            var arrowRightPosition = Math.max(0, totalWidth - anchorBox.x - anchorBox.width - borderRadius - arrowOffset);
            arrowRightPosition += anchorBox.width / 2;
            arrowRightPosition = Math.min(arrowRightPosition, newElementPosition.width - borderRadius - arrowOffset);
            this._popupArrowElement.style.right = arrowRightPosition + "px";
        } else {
            newElementPosition.x = borderRadius;
            newElementPosition.width = totalWidth - borderRadius * 2;
            newElementPosition.height += scrollerWidth;
            horizontalAlignment = "left";
            if (verticalAlignment === WebInspector.Popover.Orientation.Bottom)
                newElementPosition.y -= scrollerWidth;
            this._popupArrowElement.style.left = Math.max(0, anchorBox.x - borderRadius * 2 - arrowOffset) + "px";
            this._popupArrowElement.style.left += anchorBox.width / 2;
        }
        this.element.className = "popover custom-popup-vertical-scroll custom-popup-horizontal-scroll " + verticalAlignment + "-" + horizontalAlignment + "-arrow";
        this.element.positionAt(newElementPosition.x - borderWidth, newElementPosition.y - borderWidth, container);
        this.element.style.width = newElementPosition.width + borderWidth * 2 + "px";
        this.element.style.height = newElementPosition.height + borderWidth * 2 + "px";
    }, __proto__: WebInspector.View.prototype
}
WebInspector.PopoverHelper = function (panelElement, getAnchor, showPopover, onHide, disableOnClick) {
    this._panelElement = panelElement;
    this._getAnchor = getAnchor;
    this._showPopover = showPopover;
    this._onHide = onHide;
    this._disableOnClick = !!disableOnClick;
    panelElement.addEventListener("mousedown", this._mouseDown.bind(this), false);
    panelElement.addEventListener("mousemove", this._mouseMove.bind(this), false);
    panelElement.addEventListener("mouseout", this._mouseOut.bind(this), false);
    this.setTimeout(1000, 500);
}
WebInspector.PopoverHelper.prototype = {
    setTimeout: function (timeout, hideTimeout) {
        this._timeout = timeout;
        if (typeof hideTimeout === "number")
            this._hideTimeout = hideTimeout; else
            this._hideTimeout = timeout / 2;
    }, _eventInHoverElement: function (event) {
        if (!this._hoverElement)
            return false;
        var box = this._hoverElement instanceof AnchorBox ? this._hoverElement : this._hoverElement.boxInWindow();
        return (box.x <= event.clientX && event.clientX <= box.x + box.width && box.y <= event.clientY && event.clientY <= box.y + box.height);
    }, _mouseDown: function (event) {
        if (this._disableOnClick || !this._eventInHoverElement(event))
            this.hidePopover(); else {
            this._killHidePopoverTimer();
            this._handleMouseAction(event, true);
        }
    }, _mouseMove: function (event) {
        if (this._eventInHoverElement(event))
            return;
        this._startHidePopoverTimer();
        this._handleMouseAction(event, false);
    }, _popoverMouseOut: function (event) {
        if (!this.isPopoverVisible())
            return;
        if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(this._popover._contentDiv))
            this._startHidePopoverTimer();
    }, _mouseOut: function (event) {
        if (!this.isPopoverVisible())
            return;
        if (!this._eventInHoverElement(event))
            this._startHidePopoverTimer();
    }, _startHidePopoverTimer: function () {
        if (!this._popover || this._hidePopoverTimer)
            return;
        function doHide() {
            this._hidePopover();
            delete this._hidePopoverTimer;
        }

        this._hidePopoverTimer = setTimeout(doHide.bind(this), this._hideTimeout);
    }, _handleMouseAction: function (event, isMouseDown) {
        this._resetHoverTimer();
        if (event.which && this._disableOnClick)
            return;
        this._hoverElement = this._getAnchor(event.target, event);
        if (!this._hoverElement)
            return;
        const toolTipDelay = isMouseDown ? 0 : (this._popup ? this._timeout * 0.6 : this._timeout);
        this._hoverTimer = setTimeout(this._mouseHover.bind(this, this._hoverElement), toolTipDelay);
    }, _resetHoverTimer: function () {
        if (this._hoverTimer) {
            clearTimeout(this._hoverTimer);
            delete this._hoverTimer;
        }
    }, isPopoverVisible: function () {
        return !!this._popover;
    }, hidePopover: function () {
        this._resetHoverTimer();
        this._hidePopover();
    }, _hidePopover: function () {
        if (!this._popover)
            return;
        if (this._onHide)
            this._onHide();
        this._popover.dispose();
        delete this._popover;
        this._hoverElement = null;
    }, _mouseHover: function (element) {
        delete this._hoverTimer;
        this._hidePopover();
        this._popover = new WebInspector.Popover(this);
        this._showPopover(element, this._popover);
    }, _killHidePopoverTimer: function () {
        if (this._hidePopoverTimer) {
            clearTimeout(this._hidePopoverTimer);
            delete this._hidePopoverTimer;
            this._resetHoverTimer();
        }
    }
}
WebInspector.Popover.Orientation = {Top: "top", Bottom: "bottom"}
WebInspector.TabbedPane = function () {
    WebInspector.VBox.call(this);
    this.element.classList.add("tabbed-pane");
    this.element.tabIndex = -1;
    this._headerElement = this.element.createChild("div", "tabbed-pane-header");
    this._headerContentsElement = this._headerElement.createChild("div", "tabbed-pane-header-contents");
    this._tabsElement = this._headerContentsElement.createChild("div", "tabbed-pane-header-tabs");
    this._contentElement = this.element.createChild("div", "tabbed-pane-content");
    this._tabs = [];
    this._tabsHistory = [];
    this._tabsById = {};
    this._currentTabLocked = false;
    this._dropDownButton = this._createDropDownButton();
    WebInspector.zoomManager.addEventListener(WebInspector.ZoomManager.Events.ZoomChanged, this._zoomChanged, this);
}
WebInspector.TabbedPane.EventTypes = {TabSelected: "TabSelected", TabClosed: "TabClosed"}
WebInspector.TabbedPane.prototype = {
    setCurrentTabLocked: function (locked) {
        this._currentTabLocked = locked;
        this._headerElement.classList.toggle("locked", this._currentTabLocked);
    }, get visibleView() {
        return this._currentTab ? this._currentTab.view : null;
    }, tabViews: function () {
        function tabToView(tab) {
            return tab.view;
        }

        return this._tabs.map(tabToView);
    }, get selectedTabId() {
        return this._currentTab ? this._currentTab.id : null;
    }, set shrinkableTabs(shrinkableTabs) {
        this._shrinkableTabs = shrinkableTabs;
    }, set verticalTabLayout(verticalTabLayout) {
        this._verticalTabLayout = verticalTabLayout;
        this.invalidateConstraints();
    }, set closeableTabs(closeableTabs) {
        this._closeableTabs = closeableTabs;
    }, setRetainTabOrder: function (retainTabOrder, tabOrderComparator) {
        this._retainTabOrder = retainTabOrder;
        this._tabOrderComparator = tabOrderComparator;
    }, defaultFocusedElement: function () {
        return this.visibleView ? this.visibleView.defaultFocusedElement() : null;
    }, focus: function () {
        if (this.visibleView)
            this.visibleView.focus(); else
            this.element.focus();
    }, headerElement: function () {
        return this._headerElement;
    }, isTabCloseable: function (id) {
        var tab = this._tabsById[id];
        return tab ? tab.isCloseable() : false;
    }, setTabDelegate: function (delegate) {
        var tabs = this._tabs.slice();
        for (var i = 0; i < tabs.length; ++i)
            tabs[i].setDelegate(delegate);
        this._delegate = delegate;
    }, appendTab: function (id, tabTitle, view, tabTooltip, userGesture, isCloseable) {
        isCloseable = typeof isCloseable === "boolean" ? isCloseable : this._closeableTabs;
        var tab = new WebInspector.TabbedPaneTab(this, id, tabTitle, isCloseable, view, tabTooltip);
        tab.setDelegate(this._delegate);
        this._tabsById[id] = tab;
        function comparator(tab1, tab2) {
            return this._tabOrderComparator(tab1.id, tab2.id);
        }

        if (this._retainTabOrder && this._tabOrderComparator)
            this._tabs.splice(insertionIndexForObjectInListSortedByFunction(tab, this._tabs, comparator.bind(this)), 0, tab); else
            this._tabs.push(tab);
        this._tabsHistory.push(tab);
        if (this._tabsHistory[0] === tab && this.isShowing())
            this.selectTab(tab.id, userGesture);
        this._updateTabElements();
    }, closeTab: function (id, userGesture) {
        this.closeTabs([id], userGesture);
    }, closeTabs: function (ids, userGesture) {
        var focused = this.hasFocus();
        for (var i = 0; i < ids.length; ++i)
            this._innerCloseTab(ids[i], userGesture);
        this._updateTabElements();
        if (this._tabsHistory.length)
            this.selectTab(this._tabsHistory[0].id, false);
        if (focused)
            this.focus();
    }, _innerCloseTab: function (id, userGesture) {
        if (!this._tabsById[id])
            return;
        if (userGesture && !this._tabsById[id]._closeable)
            return;
        if (this._currentTab && this._currentTab.id === id)
            this._hideCurrentTab();
        var tab = this._tabsById[id];
        delete this._tabsById[id];
        this._tabsHistory.splice(this._tabsHistory.indexOf(tab), 1);
        this._tabs.splice(this._tabs.indexOf(tab), 1);
        if (tab._shown)
            this._hideTabElement(tab);
        var eventData = {tabId: id, view: tab.view, isUserGesture: userGesture};
        this.dispatchEventToListeners(WebInspector.TabbedPane.EventTypes.TabClosed, eventData);
        return true;
    }, hasTab: function (tabId) {
        return !!this._tabsById[tabId];
    }, allTabs: function () {
        var result = [];
        var tabs = this._tabs.slice();
        for (var i = 0; i < tabs.length; ++i)
            result.push(tabs[i].id);
        return result;
    }, otherTabs: function (id) {
        var result = [];
        var tabs = this._tabs.slice();
        for (var i = 0; i < tabs.length; ++i) {
            if (tabs[i].id !== id)
                result.push(tabs[i].id);
        }
        return result;
    }, selectTab: function (id, userGesture) {
        if (this._currentTabLocked)
            return false;
        var focused = this.hasFocus();
        var tab = this._tabsById[id];
        if (!tab)
            return false;
        if (this._currentTab && this._currentTab.id === id)
            return true;
        this._hideCurrentTab();
        this._showTab(tab);
        this._currentTab = tab;
        this._tabsHistory.splice(this._tabsHistory.indexOf(tab), 1);
        this._tabsHistory.splice(0, 0, tab);
        this._updateTabElements();
        if (focused)
            this.focus();
        var eventData = {tabId: id, view: tab.view, isUserGesture: userGesture};
        this.dispatchEventToListeners(WebInspector.TabbedPane.EventTypes.TabSelected, eventData);
        return true;
    }, lastOpenedTabIds: function (tabsCount) {
        function tabToTabId(tab) {
            return tab.id;
        }

        return this._tabsHistory.slice(0, tabsCount).map(tabToTabId);
    }, setTabIcon: function (id, iconClass, iconTooltip) {
        var tab = this._tabsById[id];
        if (tab._setIconClass(iconClass, iconTooltip))
            this._updateTabElements();
    }, _zoomChanged: function (event) {
        for (var i = 0; i < this._tabs.length; ++i)
            delete this._tabs[i]._measuredWidth;
        if (this.isShowing())
            this._updateTabElements();
    }, changeTabTitle: function (id, tabTitle) {
        var tab = this._tabsById[id];
        if (tab.title === tabTitle)
            return;
        tab.title = tabTitle;
        this._updateTabElements();
    }, changeTabView: function (id, view) {
        var tab = this._tabsById[id];
        if (this._currentTab && this._currentTab.id === tab.id) {
            if (tab.view !== view)
                this._hideTab(tab);
            tab.view = view;
            this._showTab(tab);
        } else
            tab.view = view;
    }, changeTabTooltip: function (id, tabTooltip) {
        var tab = this._tabsById[id];
        tab.tooltip = tabTooltip;
    }, onResize: function () {
        this._updateTabElements();
    }, headerResized: function () {
        this._updateTabElements();
    }, wasShown: function () {
        var effectiveTab = this._currentTab || this._tabsHistory[0];
        if (effectiveTab)
            this.selectTab(effectiveTab.id);
    }, calculateConstraints: function () {
        var constraints = WebInspector.VBox.prototype.calculateConstraints.call(this);
        var minContentConstraints = new Constraints(new Size(0, 0), new Size(50, 50));
        constraints = constraints.widthToMax(minContentConstraints).heightToMax(minContentConstraints);
        if (this._verticalTabLayout)
            constraints = constraints.addWidth(new Constraints(new Size(this._headerElement.offsetWidth, 0))); else
            constraints = constraints.addHeight(new Constraints(new Size(0, this._headerElement.offsetHeight)));
        return constraints;
    }, _updateTabElements: function () {
        WebInspector.invokeOnceAfterBatchUpdate(this, this._innerUpdateTabElements);
    }, setPlaceholderText: function (text) {
        this._noTabsMessage = text;
    }, _innerUpdateTabElements: function () {
        if (!this.isShowing())
            return;
        if (!this._tabs.length) {
            this._contentElement.classList.add("has-no-tabs");
            if (this._noTabsMessage && !this._noTabsMessageElement) {
                this._noTabsMessageElement = this._contentElement.createChild("div", "tabbed-pane-placeholder fill");
                this._noTabsMessageElement.textContent = this._noTabsMessage;
            }
        } else {
            this._contentElement.classList.remove("has-no-tabs");
            if (this._noTabsMessageElement) {
                this._noTabsMessageElement.remove();
                delete this._noTabsMessageElement;
            }
        }
        if (!this._measuredDropDownButtonWidth)
            this._measureDropDownButton();
        this._updateWidths();
        this._updateTabsDropDown();
    }, _showTabElement: function (index, tab) {
        if (index >= this._tabsElement.children.length)
            this._tabsElement.appendChild(tab.tabElement); else
            this._tabsElement.insertBefore(tab.tabElement, this._tabsElement.children[index]);
        tab._shown = true;
    }, _hideTabElement: function (tab) {
        this._tabsElement.removeChild(tab.tabElement);
        tab._shown = false;
    }, _createDropDownButton: function () {
        var dropDownContainer = document.createElementWithClass("div", "tabbed-pane-header-tabs-drop-down-container");
        var dropDownButton = dropDownContainer.createChild("div", "tabbed-pane-header-tabs-drop-down");
        dropDownButton.createTextChild("\u00bb");
        this._dropDownMenu = new WebInspector.DropDownMenu();
        this._dropDownMenu.addEventListener(WebInspector.DropDownMenu.Events.ItemSelected, this._dropDownMenuItemSelected, this);
        dropDownButton.appendChild(this._dropDownMenu.element);
        return dropDownContainer;
    }, _dropDownMenuItemSelected: function (event) {
        var tabId = (event.data);
        this.selectTab(tabId, true);
    }, _totalWidth: function () {
        return this._headerContentsElement.getBoundingClientRect().width;
    }, _updateTabsDropDown: function () {
        var tabsToShowIndexes = this._tabsToShowIndexes(this._tabs, this._tabsHistory, this._totalWidth(), this._measuredDropDownButtonWidth);
        for (var i = 0; i < this._tabs.length; ++i) {
            if (this._tabs[i]._shown && tabsToShowIndexes.indexOf(i) === -1)
                this._hideTabElement(this._tabs[i]);
        }
        for (var i = 0; i < tabsToShowIndexes.length; ++i) {
            var tab = this._tabs[tabsToShowIndexes[i]];
            if (!tab._shown)
                this._showTabElement(i, tab);
        }
        this._populateDropDownFromIndex();
    }, _populateDropDownFromIndex: function () {
        if (this._dropDownButton.parentElement)
            this._headerContentsElement.removeChild(this._dropDownButton);
        this._dropDownMenu.clear();
        var tabsToShow = [];
        for (var i = 0; i < this._tabs.length; ++i) {
            if (!this._tabs[i]._shown)
                tabsToShow.push(this._tabs[i]);
            continue;
        }
        function compareFunction(tab1, tab2) {
            return tab1.title.localeCompare(tab2.title);
        }

        if (!this._retainTabOrder)
            tabsToShow.sort(compareFunction);
        var selectedId = null;
        for (var i = 0; i < tabsToShow.length; ++i) {
            var tab = tabsToShow[i];
            this._dropDownMenu.addItem(tab.id, tab.title);
            if (this._tabsHistory[0] === tab)
                selectedId = tab.id;
        }
        if (tabsToShow.length) {
            this._headerContentsElement.appendChild(this._dropDownButton);
            this._dropDownMenu.selectItem(selectedId);
        }
    }, _measureDropDownButton: function () {
        this._dropDownButton.classList.add("measuring");
        this._headerContentsElement.appendChild(this._dropDownButton);
        this._measuredDropDownButtonWidth = this._dropDownButton.getBoundingClientRect().width;
        this._headerContentsElement.removeChild(this._dropDownButton);
        this._dropDownButton.classList.remove("measuring");
    }, _updateWidths: function () {
        var measuredWidths = this._measureWidths();
        var maxWidth = this._shrinkableTabs ? this._calculateMaxWidth(measuredWidths.slice(), this._totalWidth()) : Number.MAX_VALUE;
        var i = 0;
        for (var tabId in this._tabs) {
            var tab = this._tabs[tabId];
            tab.setWidth(this._verticalTabLayout ? -1 : Math.min(maxWidth, measuredWidths[i++]));
        }
    }, _measureWidths: function () {
        this._tabsElement.style.setProperty("width", "2000px");
        var measuringTabElements = [];
        for (var tabId in this._tabs) {
            var tab = this._tabs[tabId];
            if (typeof tab._measuredWidth === "number")
                continue;
            var measuringTabElement = tab._createTabElement(true);
            measuringTabElement.__tab = tab;
            measuringTabElements.push(measuringTabElement);
            this._tabsElement.appendChild(measuringTabElement);
        }
        for (var i = 0; i < measuringTabElements.length; ++i)
            measuringTabElements[i].__tab._measuredWidth = measuringTabElements[i].getBoundingClientRect().width;
        for (var i = 0; i < measuringTabElements.length; ++i)
            measuringTabElements[i].remove();
        var measuredWidths = [];
        for (var tabId in this._tabs)
            measuredWidths.push(this._tabs[tabId]._measuredWidth);
        this._tabsElement.style.removeProperty("width");
        return measuredWidths;
    }, _calculateMaxWidth: function (measuredWidths, totalWidth) {
        if (!measuredWidths.length)
            return 0;
        measuredWidths.sort(function (x, y) {
            return x - y
        });
        var totalMeasuredWidth = 0;
        for (var i = 0; i < measuredWidths.length; ++i)
            totalMeasuredWidth += measuredWidths[i];
        if (totalWidth >= totalMeasuredWidth)
            return measuredWidths[measuredWidths.length - 1];
        var totalExtraWidth = 0;
        for (var i = measuredWidths.length - 1; i > 0; --i) {
            var extraWidth = measuredWidths[i] - measuredWidths[i - 1];
            totalExtraWidth += (measuredWidths.length - i) * extraWidth;
            if (totalWidth + totalExtraWidth >= totalMeasuredWidth)
                return measuredWidths[i - 1] + (totalWidth + totalExtraWidth - totalMeasuredWidth) / (measuredWidths.length - i);
        }
        return totalWidth / measuredWidths.length;
    }, _tabsToShowIndexes: function (tabsOrdered, tabsHistory, totalWidth, measuredDropDownButtonWidth) {
        var tabsToShowIndexes = [];
        var totalTabsWidth = 0;
        var tabCount = tabsOrdered.length;
        for (var i = 0; i < tabCount; ++i) {
            var tab = this._retainTabOrder ? tabsOrdered[i] : tabsHistory[i];
            totalTabsWidth += tab.width();
            var minimalRequiredWidth = totalTabsWidth;
            if (i !== tabCount - 1)
                minimalRequiredWidth += measuredDropDownButtonWidth;
            if (!this._verticalTabLayout && minimalRequiredWidth > totalWidth)
                break;
            tabsToShowIndexes.push(tabsOrdered.indexOf(tab));
        }
        tabsToShowIndexes.sort(function (x, y) {
            return x - y
        });
        return tabsToShowIndexes;
    }, _hideCurrentTab: function () {
        if (!this._currentTab)
            return;
        this._hideTab(this._currentTab);
        delete this._currentTab;
    }, _showTab: function (tab) {
        tab.tabElement.classList.add("selected");
        tab.view.show(this._contentElement);
    }, _hideTab: function (tab) {
        tab.tabElement.classList.remove("selected");
        tab.view.detach();
    }, elementsToRestoreScrollPositionsFor: function () {
        return [this._contentElement];
    }, _insertBefore: function (tab, index) {
        this._tabsElement.insertBefore(tab._tabElement, this._tabsElement.childNodes[index]);
        var oldIndex = this._tabs.indexOf(tab);
        this._tabs.splice(oldIndex, 1);
        if (oldIndex < index)
            --index;
        this._tabs.splice(index, 0, tab);
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.TabbedPaneTab = function (tabbedPane, id, title, closeable, view, tooltip) {
    this._closeable = closeable;
    this._tabbedPane = tabbedPane;
    this._id = id;
    this._title = title;
    this._tooltip = tooltip;
    this._view = view;
    this._shown = false;
    this._measuredWidth;
    this._tabElement;
}
WebInspector.TabbedPaneTab.prototype = {
    get id() {
        return this._id;
    }, get title() {
        return this._title;
    }, set title(title) {
        if (title === this._title)
            return;
        this._title = title;
        if (this._titleElement)
            this._titleElement.textContent = title;
        delete this._measuredWidth;
    }, iconClass: function () {
        return this._iconClass;
    }, isCloseable: function () {
        return this._closeable;
    }, _setIconClass: function (iconClass, iconTooltip) {
        if (iconClass === this._iconClass && iconTooltip === this._iconTooltip)
            return false;
        this._iconClass = iconClass;
        this._iconTooltip = iconTooltip;
        if (this._iconElement)
            this._iconElement.remove();
        if (this._iconClass && this._tabElement)
            this._iconElement = this._createIconElement(this._tabElement, this._titleElement);
        delete this._measuredWidth;
        return true;
    }, get view() {
        return this._view;
    }, set view(view) {
        this._view = view;
    }, get tooltip() {
        return this._tooltip;
    }, set tooltip(tooltip) {
        this._tooltip = tooltip;
        if (this._titleElement)
            this._titleElement.title = tooltip || "";
    }, get tabElement() {
        if (!this._tabElement)
            this._tabElement = this._createTabElement(false);
        return this._tabElement;
    }, width: function () {
        return this._width;
    }, setWidth: function (width) {
        this.tabElement.style.width = width === -1 ? "" : (width + "px");
        this._width = width;
    }, setDelegate: function (delegate) {
        this._delegate = delegate;
    }, _createIconElement: function (tabElement, titleElement) {
        var iconElement = document.createElementWithClass("span", "tabbed-pane-header-tab-icon " + this._iconClass);
        if (this._iconTooltip)
            iconElement.title = this._iconTooltip;
        tabElement.insertBefore(iconElement, titleElement);
        return iconElement;
    }, _createTabElement: function (measuring) {
        var tabElement = document.createElementWithClass("div", "tabbed-pane-header-tab");
        tabElement.id = "tab-" + this._id;
        tabElement.tabIndex = -1;
        tabElement.selectTabForTest = this._tabbedPane.selectTab.bind(this._tabbedPane, this.id, true);
        var titleElement = tabElement.createChild("span", "tabbed-pane-header-tab-title");
        titleElement.textContent = this.title;
        titleElement.title = this.tooltip || "";
        if (this._iconClass)
            this._createIconElement(tabElement, titleElement);
        if (!measuring)
            this._titleElement = titleElement;
        if (this._closeable)
            tabElement.createChild("div", "close-button-gray");
        if (measuring) {
            tabElement.classList.add("measuring");
        } else {
            tabElement.addEventListener("click", this._tabClicked.bind(this), false);
            tabElement.addEventListener("mousedown", this._tabMouseDown.bind(this), false);
            tabElement.addEventListener("mouseup", this._tabMouseUp.bind(this), false);
            if (this._closeable) {
                tabElement.addEventListener("contextmenu", this._tabContextMenu.bind(this), false);
                WebInspector.installDragHandle(tabElement, this._startTabDragging.bind(this), this._tabDragging.bind(this), this._endTabDragging.bind(this), "pointer");
            }
        }
        return tabElement;
    }, _tabClicked: function (event) {
        var middleButton = event.button === 1;
        var shouldClose = this._closeable && (middleButton || event.target.classList.contains("close-button-gray"));
        if (!shouldClose) {
            this._tabbedPane.focus();
            return;
        }
        this._closeTabs([this.id]);
        event.consume(true);
    }, _tabMouseDown: function (event) {
        if (event.target.classList.contains("close-button-gray") || event.button === 1)
            return;
        this._tabbedPane.selectTab(this.id, true);
    }, _tabMouseUp: function (event) {
        if (event.button === 1)
            event.consume(true);
    }, _closeTabs: function (ids) {
        if (this._delegate) {
            this._delegate.closeTabs(this._tabbedPane, ids);
            return;
        }
        this._tabbedPane.closeTabs(ids, true);
    }, _tabContextMenu: function (event) {
        function close() {
            this._closeTabs([this.id]);
        }

        function closeOthers() {
            this._closeTabs(this._tabbedPane.otherTabs(this.id));
        }

        function closeAll() {
            this._closeTabs(this._tabbedPane.allTabs());
        }

        var contextMenu = new WebInspector.ContextMenu(event);
        contextMenu.appendItem(WebInspector.UIString("Close"), close.bind(this));
        contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Close others" : "Close Others"), closeOthers.bind(this));
        contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Close all" : "Close All"), closeAll.bind(this));
        contextMenu.show();
    }, _startTabDragging: function (event) {
        if (event.target.classList.contains("close-button-gray"))
            return false;
        this._dragStartX = event.pageX;
        return true;
    }, _tabDragging: function (event) {
        var tabElements = this._tabbedPane._tabsElement.childNodes;
        for (var i = 0; i < tabElements.length; ++i) {
            var tabElement = tabElements[i];
            if (tabElement === this._tabElement)
                continue;
            var intersects = tabElement.offsetLeft + tabElement.clientWidth > this._tabElement.offsetLeft && this._tabElement.offsetLeft + this._tabElement.clientWidth > tabElement.offsetLeft;
            if (!intersects)
                continue;
            if (Math.abs(event.pageX - this._dragStartX) < tabElement.clientWidth / 2 + 5)
                break;
            if (event.pageX - this._dragStartX > 0) {
                tabElement = tabElement.nextSibling;
                ++i;
            }
            var oldOffsetLeft = this._tabElement.offsetLeft;
            this._tabbedPane._insertBefore(this, i);
            this._dragStartX += this._tabElement.offsetLeft - oldOffsetLeft;
            break;
        }
        if (!this._tabElement.previousSibling && event.pageX - this._dragStartX < 0) {
            this._tabElement.style.setProperty("left", "0px");
            return;
        }
        if (!this._tabElement.nextSibling && event.pageX - this._dragStartX > 0) {
            this._tabElement.style.setProperty("left", "0px");
            return;
        }
        this._tabElement.style.setProperty("position", "relative");
        this._tabElement.style.setProperty("left", (event.pageX - this._dragStartX) + "px");
    }, _endTabDragging: function (event) {
        this._tabElement.style.removeProperty("position");
        this._tabElement.style.removeProperty("left");
        delete this._dragStartX;
    }
}
WebInspector.TabbedPaneTabDelegate = function () {
}
WebInspector.TabbedPaneTabDelegate.prototype = {
    closeTabs: function (tabbedPane, ids) {
    }
}
WebInspector.ExtensibleTabbedPaneController = function (tabbedPane, extensionPoint, viewCallback) {
    this._tabbedPane = tabbedPane;
    this._extensionPoint = extensionPoint;
    this._viewCallback = viewCallback;
    this._tabbedPane.setRetainTabOrder(true, self.runtime.orderComparator(extensionPoint, "name", "order"));
    this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this);
    this._views = new StringMap();
    this._initialize();
}
WebInspector.ExtensibleTabbedPaneController.prototype = {
    _initialize: function () {
        this._extensions = {};
        var extensions = self.runtime.extensions(this._extensionPoint);
        for (var i = 0; i < extensions.length; ++i) {
            var descriptor = extensions[i].descriptor();
            var id = descriptor["name"];
            var title = WebInspector.UIString(descriptor["title"]);
            var settingName = descriptor["setting"];
            var setting = settingName ? (WebInspector.settings[settingName]) : null;
            this._extensions[id] = extensions[i];
            if (setting) {
                setting.addChangeListener(this._toggleSettingBasedView.bind(this, id, title, setting));
                if (setting.get())
                    this._tabbedPane.appendTab(id, title, new WebInspector.View());
            } else {
                this._tabbedPane.appendTab(id, title, new WebInspector.View());
            }
        }
    }, _toggleSettingBasedView: function (id, title, setting) {
        this._tabbedPane.closeTab(id);
        if (setting.get())
            this._tabbedPane.appendTab(id, title, new WebInspector.View());
    }, _tabSelected: function (event) {
        var tabId = this._tabbedPane.selectedTabId;
        if (!tabId)
            return;
        var view = this._viewForId(tabId);
        if (view)
            this._tabbedPane.changeTabView(tabId, view);
    }, _viewForId: function (id) {
        if (this._views.contains(id))
            return (this._views.get(id));
        var view = this._extensions[id] ? (this._extensions[id].instance()) : null;
        this._views.put(id, view);
        if (this._viewCallback && view)
            this._viewCallback(id, view);
        return view;
    }
}
WebInspector.ViewportControl = function (provider) {
    this.element = document.createElement("div");
    this.element.style.overflow = "auto";
    this._topGapElement = this.element.createChild("div", "viewport-control-gap-element");
    this._topGapElement.textContent = ".";
    this._topGapElement.style.height = "0px";
    this._contentElement = this.element.createChild("div");
    this._bottomGapElement = this.element.createChild("div", "viewport-control-gap-element");
    this._bottomGapElement.textContent = ".";
    this._bottomGapElement.style.height = "0px";
    this._provider = provider;
    this.element.addEventListener("scroll", this._onScroll.bind(this), false);
    this.element.addEventListener("copy", this._onCopy.bind(this), false);
    this.element.addEventListener("dragstart", this._onDragStart.bind(this), false);
    this._firstVisibleIndex = 0;
    this._lastVisibleIndex = -1;
    this._renderedItems = [];
    this._anchorSelection = null;
    this._headSelection = null;
    this._stickToBottom = false;
    this._scrolledToBottom = true;
}
WebInspector.ViewportControl.Provider = function () {
}
WebInspector.ViewportControl.Provider.prototype = {
    fastHeight: function (index) {
        return 0;
    }, itemCount: function () {
        return 0;
    }, minimumRowHeight: function () {
        return 0;
    }, itemElement: function (index) {
        return null;
    }
}
WebInspector.ViewportElement = function () {
}
WebInspector.ViewportElement.prototype = {
    cacheFastHeight: function () {
    }, willHide: function () {
    }, wasShown: function () {
    }, element: function () {
    },
}
WebInspector.StaticViewportElement = function (element) {
    this._element = element;
}
WebInspector.StaticViewportElement.prototype = {
    cacheFastHeight: function () {
    }, willHide: function () {
    }, wasShown: function () {
    }, element: function () {
        return this._element;
    },
}
WebInspector.ViewportControl.prototype = {
    scrolledToBottom: function () {
        return this._scrolledToBottom;
    }, setStickToBottom: function (value) {
        this._stickToBottom = value;
    }, _onCopy: function (event) {
        var text = this._selectedText();
        if (!text)
            return;
        event.preventDefault();
        event.clipboardData.setData("text/plain", text);
    }, _onDragStart: function (event) {
        var text = this._selectedText();
        if (!text)
            return false;
        event.dataTransfer.clearData();
        event.dataTransfer.setData("text/plain", text);
        event.dataTransfer.effectAllowed = "copy";
        return true;
    }, contentElement: function () {
        return this._contentElement;
    }, invalidate: function () {
        delete this._cumulativeHeights;
        delete this._cachedProviderElements;
        this.refresh();
    }, _providerElement: function (index) {
        if (!this._cachedProviderElements)
            this._cachedProviderElements = new Array(this._provider.itemCount());
        var element = this._cachedProviderElements[index];
        if (!element) {
            element = this._provider.itemElement(index);
            this._cachedProviderElements[index] = element;
        }
        return element;
    }, _rebuildCumulativeHeightsIfNeeded: function () {
        if (this._cumulativeHeights)
            return;
        var itemCount = this._provider.itemCount();
        if (!itemCount)
            return;
        this._cumulativeHeights = new Int32Array(itemCount);
        this._cumulativeHeights[0] = this._provider.fastHeight(0);
        for (var i = 1; i < itemCount; ++i)
            this._cumulativeHeights[i] = this._cumulativeHeights[i - 1] + this._provider.fastHeight(i);
    }, _cachedItemHeight: function (index) {
        return index === 0 ? this._cumulativeHeights[0] : this._cumulativeHeights[index] - this._cumulativeHeights[index - 1];
    }, _isSelectionBackwards: function (selection) {
        if (!selection || !selection.rangeCount)
            return false;
        var range = document.createRange();
        range.setStart(selection.anchorNode, selection.anchorOffset);
        range.setEnd(selection.focusNode, selection.focusOffset);
        return range.collapsed;
    }, _createSelectionModel: function (itemIndex, node, offset) {
        return {item: itemIndex, node: node, offset: offset};
    }, _updateSelectionModel: function (selection) {
        if (!selection || !selection.rangeCount) {
            this._headSelection = null;
            this._anchorSelection = null;
            return false;
        }
        var firstSelected = Number.MAX_VALUE;
        var lastSelected = -1;
        var range = selection.getRangeAt(0);
        var hasVisibleSelection = false;
        for (var i = 0; i < this._renderedItems.length; ++i) {
            if (range.intersectsNode(this._renderedItems[i].element())) {
                var index = i + this._firstVisibleIndex;
                firstSelected = Math.min(firstSelected, index);
                lastSelected = Math.max(lastSelected, index);
                hasVisibleSelection = true;
            }
        }
        if (hasVisibleSelection) {
            firstSelected = this._createSelectionModel(firstSelected, (range.startContainer), range.startOffset);
            lastSelected = this._createSelectionModel(lastSelected, (range.endContainer), range.endOffset);
        }
        var topOverlap = range.intersectsNode(this._topGapElement) && this._topGapElement._active;
        var bottomOverlap = range.intersectsNode(this._bottomGapElement) && this._bottomGapElement._active;
        if (!topOverlap && !bottomOverlap && !hasVisibleSelection) {
            this._headSelection = null;
            this._anchorSelection = null;
            return false;
        }
        if (!this._anchorSelection || !this._headSelection) {
            this._anchorSelection = this._createSelectionModel(0, this.element, 0);
            this._headSelection = this._createSelectionModel(this._provider.itemCount() - 1, this.element, this.element.children.length);
            this._selectionIsBackward = false;
        }
        var isBackward = this._isSelectionBackwards(selection);
        var startSelection = this._selectionIsBackward ? this._headSelection : this._anchorSelection;
        var endSelection = this._selectionIsBackward ? this._anchorSelection : this._headSelection;
        if (topOverlap && bottomOverlap && hasVisibleSelection) {
            firstSelected = firstSelected.item < startSelection.item ? firstSelected : startSelection;
            lastSelected = lastSelected.item > endSelection.item ? lastSelected : endSelection;
        } else if (!hasVisibleSelection) {
            firstSelected = startSelection;
            lastSelected = endSelection;
        } else if (topOverlap)
            firstSelected = isBackward ? this._headSelection : this._anchorSelection; else if (bottomOverlap)
            lastSelected = isBackward ? this._anchorSelection : this._headSelection;
        if (isBackward) {
            this._anchorSelection = lastSelected;
            this._headSelection = firstSelected;
        } else {
            this._anchorSelection = firstSelected;
            this._headSelection = lastSelected;
        }
        this._selectionIsBackward = isBackward;
        return true;
    }, _restoreSelection: function (selection) {
        var anchorElement = null;
        var anchorOffset;
        if (this._firstVisibleIndex <= this._anchorSelection.item && this._anchorSelection.item <= this._lastVisibleIndex) {
            anchorElement = this._anchorSelection.node;
            anchorOffset = this._anchorSelection.offset;
        } else {
            if (this._anchorSelection.item < this._firstVisibleIndex)
                anchorElement = this._topGapElement; else if (this._anchorSelection.item > this._lastVisibleIndex)
                anchorElement = this._bottomGapElement;
            anchorOffset = this._selectionIsBackward ? 1 : 0;
        }
        var headElement = null;
        var headOffset;
        if (this._firstVisibleIndex <= this._headSelection.item && this._headSelection.item <= this._lastVisibleIndex) {
            headElement = this._headSelection.node;
            headOffset = this._headSelection.offset;
        } else {
            if (this._headSelection.item < this._firstVisibleIndex)
                headElement = this._topGapElement; else if (this._headSelection.item > this._lastVisibleIndex)
                headElement = this._bottomGapElement;
            headOffset = this._selectionIsBackward ? 0 : 1;
        }
        selection.setBaseAndExtent(anchorElement, anchorOffset, headElement, headOffset);
    }, refresh: function () {
        if (!this._visibleHeight())
            return;
        var itemCount = this._provider.itemCount();
        if (!itemCount) {
            for (var i = 0; i < this._renderedItems.length; ++i)
                this._renderedItems[i].cacheFastHeight();
            for (var i = 0; i < this._renderedItems.length; ++i)
                this._renderedItems[i].willHide();
            this._renderedItems = [];
            this._contentElement.removeChildren();
            this._topGapElement.style.height = "0px";
            this._bottomGapElement.style.height = "0px";
            this._firstVisibleIndex = -1;
            this._lastVisibleIndex = -1;
            return;
        }
        var selection = window.getSelection();
        var shouldRestoreSelection = this._updateSelectionModel(selection);
        var visibleFrom = this.element.scrollTop;
        var visibleHeight = this._visibleHeight();
        this._scrolledToBottom = this.element.isScrolledToBottom();
        var isInvalidating = !this._cumulativeHeights;
        if (this._cumulativeHeights && itemCount !== this._cumulativeHeights.length)
            delete this._cumulativeHeights;
        for (var i = 0; i < this._renderedItems.length; ++i) {
            this._renderedItems[i].cacheFastHeight();
            if (this._cumulativeHeights && Math.abs(this._cachedItemHeight(this._firstVisibleIndex + i) - this._provider.fastHeight(i + this._firstVisibleIndex)) > 1)
                delete this._cumulativeHeights;
        }
        this._rebuildCumulativeHeightsIfNeeded();
        var oldFirstVisibleIndex = this._firstVisibleIndex;
        var oldLastVisibleIndex = this._lastVisibleIndex;
        var shouldStickToBottom = this._stickToBottom && this._scrolledToBottom;
        if (shouldStickToBottom) {
            this._lastVisibleIndex = itemCount - 1;
            this._firstVisibleIndex = Math.max(itemCount - Math.ceil(visibleHeight / this._provider.minimumRowHeight()), 0);
        } else {
            this._firstVisibleIndex = Math.max(Array.prototype.lowerBound.call(this._cumulativeHeights, visibleFrom + 1), 0);
            this._lastVisibleIndex = this._firstVisibleIndex + Math.ceil(visibleHeight / this._provider.minimumRowHeight()) - 1;
            this._lastVisibleIndex = Math.min(this._lastVisibleIndex, itemCount - 1);
        }
        var topGapHeight = this._cumulativeHeights[this._firstVisibleIndex - 1] || 0;
        var bottomGapHeight = this._cumulativeHeights[this._cumulativeHeights.length - 1] - this._cumulativeHeights[this._lastVisibleIndex];
        this._topGapElement.style.height = topGapHeight + "px";
        this._bottomGapElement.style.height = bottomGapHeight + "px";
        this._topGapElement._active = !!topGapHeight;
        this._bottomGapElement._active = !!bottomGapHeight;
        this._contentElement.style.setProperty("height", "10000000px");
        if (isInvalidating)
            this._fullViewportUpdate(); else
            this._partialViewportUpdate(oldFirstVisibleIndex, oldLastVisibleIndex);
        this._contentElement.style.removeProperty("height");
        if (shouldRestoreSelection)
            this._restoreSelection(selection);
        if (shouldStickToBottom)
            this.element.scrollTop = this.element.scrollHeight;
    }, _fullViewportUpdate: function () {
        for (var i = 0; i < this._renderedItems.length; ++i)
            this._renderedItems[i].willHide();
        this._renderedItems = [];
        this._contentElement.removeChildren();
        for (var i = this._firstVisibleIndex; i <= this._lastVisibleIndex; ++i) {
            var viewportElement = this._providerElement(i);
            this._contentElement.appendChild(viewportElement.element());
            this._renderedItems.push(viewportElement);
            viewportElement.wasShown();
        }
    }, _partialViewportUpdate: function (oldFirstVisibleIndex, oldLastVisibleIndex) {
        var willBeHidden = [];
        for (var i = 0; i < this._renderedItems.length; ++i) {
            var index = oldFirstVisibleIndex + i;
            if (index < this._firstVisibleIndex || this._lastVisibleIndex < index)
                willBeHidden.push(this._renderedItems[i]);
        }
        for (var i = 0; i < willBeHidden.length; ++i)
            willBeHidden[i].willHide();
        for (var i = 0; i < willBeHidden.length; ++i)
            willBeHidden[i].element().remove();
        this._renderedItems = [];
        var anchor = this._contentElement.firstChild;
        for (var i = this._firstVisibleIndex; i <= this._lastVisibleIndex; ++i) {
            var viewportElement = this._providerElement(i);
            var element = viewportElement.element();
            if (element !== anchor) {
                this._contentElement.insertBefore(element, anchor);
                viewportElement.wasShown();
            } else {
                anchor = anchor.nextSibling;
            }
            this._renderedItems.push(viewportElement);
        }
    }, _selectedText: function () {
        this._updateSelectionModel(window.getSelection());
        if (!this._headSelection || !this._anchorSelection)
            return null;
        var startSelection = null;
        var endSelection = null;
        if (this._selectionIsBackward) {
            startSelection = this._headSelection;
            endSelection = this._anchorSelection;
        } else {
            startSelection = this._anchorSelection;
            endSelection = this._headSelection;
        }
        var textLines = [];
        for (var i = startSelection.item; i <= endSelection.item; ++i)
            textLines.push(this._providerElement(i).element().textContent);
        var endSelectionElement = this._providerElement(endSelection.item).element();
        if (endSelection.node && endSelection.node.isSelfOrDescendant(endSelectionElement)) {
            var itemTextOffset = this._textOffsetInNode(endSelectionElement, endSelection.node, endSelection.offset);
            textLines[textLines.length - 1] = textLines.peekLast().substring(0, itemTextOffset);
        }
        var startSelectionElement = this._providerElement(startSelection.item).element();
        if (startSelection.node && startSelection.node.isSelfOrDescendant(startSelectionElement)) {
            var itemTextOffset = this._textOffsetInNode(startSelectionElement, startSelection.node, startSelection.offset);
            textLines[0] = textLines[0].substring(itemTextOffset);
        }
        return textLines.join("\n");
    }, _textOffsetInNode: function (itemElement, container, offset) {
        var chars = 0;
        var node = itemElement;
        while ((node = node.traverseNextTextNode()) && node !== container)
            chars += node.textContent.length;
        return chars + offset;
    }, _onScroll: function (event) {
        this.refresh();
    }, firstVisibleIndex: function () {
        return this._firstVisibleIndex;
    }, lastVisibleIndex: function () {
        return this._lastVisibleIndex;
    }, renderedElementAt: function (index) {
        if (index < this._firstVisibleIndex)
            return null;
        if (index > this._lastVisibleIndex)
            return null;
        return this._renderedItems[index - this._firstVisibleIndex].element();
    }, scrollItemIntoView: function (index, makeLast) {
        if (index > this._firstVisibleIndex && index < this._lastVisibleIndex)
            return;
        if (makeLast)
            this.forceScrollItemToBeLast(index); else if (index <= this._firstVisibleIndex)
            this.forceScrollItemToBeFirst(index); else if (index >= this._lastVisibleIndex)
            this.forceScrollItemToBeLast(index);
    }, forceScrollItemToBeFirst: function (index) {
        this._rebuildCumulativeHeightsIfNeeded();
        this.element.scrollTop = index > 0 ? this._cumulativeHeights[index - 1] : 0;
        this.refresh();
    }, forceScrollItemToBeLast: function (index) {
        this._rebuildCumulativeHeightsIfNeeded();
        this.element.scrollTop = this._cumulativeHeights[index] - this._visibleHeight();
        this.refresh();
    }, _visibleHeight: function () {
        return this.element.offsetHeight;
    }
}
WebInspector.Drawer = function (splitView) {
    WebInspector.VBox.call(this);
    this.element.id = "drawer-contents";
    this._splitView = splitView;
    splitView.hideDefaultResizer();
    this.show(splitView.sidebarElement());
    this._toggleDrawerButton = new WebInspector.StatusBarButton(WebInspector.UIString("Show drawer."), "console-status-bar-item");
    this._toggleDrawerButton.addEventListener("click", this.toggle, this);
    this._tabbedPane = new WebInspector.TabbedPane();
    this._tabbedPane.element.id = "drawer-tabbed-pane";
    this._tabbedPane.closeableTabs = false;
    this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this);
    new WebInspector.ExtensibleTabbedPaneController(this._tabbedPane, "drawer-view");
    splitView.installResizer(this._tabbedPane.headerElement());
    this._lastSelectedViewSetting = WebInspector.settings.createSetting("WebInspector.Drawer.lastSelectedView", "console");
    this._tabbedPane.show(this.element);
}
WebInspector.Drawer.prototype = {
    toggleButton: function () {
        return this._toggleDrawerButton;
    }, closeView: function (id) {
        this._tabbedPane.closeTab(id);
    }, showView: function (id, immediate) {
        if (!this._tabbedPane.hasTab(id)) {
            this._innerShow(immediate);
            return;
        }
        this._innerShow(immediate);
        this._tabbedPane.selectTab(id, true);
        this._lastSelectedViewSetting.set(id);
    }, showCloseableView: function (id, title, view) {
        if (!this._tabbedPane.hasTab(id)) {
            this._tabbedPane.appendTab(id, title, view, undefined, false, true);
        } else {
            this._tabbedPane.changeTabView(id, view);
            this._tabbedPane.changeTabTitle(id, title);
        }
        this._innerShow();
        this._tabbedPane.selectTab(id, true);
    }, showDrawer: function () {
        this.showView(this._lastSelectedViewSetting.get());
    }, wasShown: function () {
        this.showView(this._lastSelectedViewSetting.get());
        this._toggleDrawerButton.toggled = true;
        this._toggleDrawerButton.title = WebInspector.UIString("Hide drawer.");
    }, willHide: function () {
        this._toggleDrawerButton.toggled = false;
        this._toggleDrawerButton.title = WebInspector.UIString("Show drawer.");
    }, _innerShow: function (immediate) {
        if (this.isShowing())
            return;
        this._splitView.showBoth(!immediate);
        if (this._visibleView())
            this._visibleView().focus();
    }, closeDrawer: function () {
        if (!this.isShowing())
            return;
        WebInspector.restoreFocusFromElement(this.element);
        this._splitView.hideSidebar(true);
    }, _visibleView: function () {
        return this._tabbedPane.visibleView;
    }, _tabSelected: function (event) {
        var tabId = this._tabbedPane.selectedTabId;
        if (tabId && event.data["isUserGesture"] && !this._tabbedPane.isTabCloseable(tabId))
            this._lastSelectedViewSetting.set(tabId);
    }, toggle: function () {
        if (this._toggleDrawerButton.toggled)
            this.closeDrawer(); else
            this.showDrawer();
    }, visible: function () {
        return this._toggleDrawerButton.toggled;
    }, selectedViewId: function () {
        return this._tabbedPane.selectedTabId;
    }, initialPanelShown: function () {
        this._initialPanelWasShown = true;
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.Drawer.ViewFactory = function () {
}
WebInspector.Drawer.ViewFactory.prototype = {
    createView: function () {
    }
}
WebInspector.Drawer.SingletonViewFactory = function (constructor) {
    this._constructor = constructor;
}
WebInspector.Drawer.SingletonViewFactory.prototype = {
    createView: function () {
        if (!this._instance)
            this._instance = (new this._constructor());
        return this._instance;
    }
}
WebInspector.ConsoleModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.ConsoleModel, target);
    this._messages = [];
    this.warnings = 0;
    this.errors = 0;
    this._consoleAgent = target.consoleAgent();
    target.registerConsoleDispatcher(new WebInspector.ConsoleDispatcher(this));
    this._enableAgent();
}
WebInspector.ConsoleModel.Events = {ConsoleCleared: "ConsoleCleared", MessageAdded: "MessageAdded", CommandEvaluated: "CommandEvaluated",}
WebInspector.ConsoleModel.prototype = {
    _enableAgent: function () {
        if (WebInspector.settings.monitoringXHREnabled.get())
            this._consoleAgent.setMonitoringXHREnabled(true);
        this._enablingConsole = true;
        function callback() {
            delete this._enablingConsole;
        }

        this._consoleAgent.enable(callback.bind(this));
    }, enablingConsole: function () {
        return !!this._enablingConsole;
    }, addMessage: function (msg) {
        if (WebInspector.NetworkManager.hasDevToolsRequestHeader(msg.request))
            return;
        msg.index = this._messages.length;
        this._messages.push(msg);
        this._incrementErrorWarningCount(msg);
        this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.MessageAdded, msg);
    }, _incrementErrorWarningCount: function (msg) {
        switch (msg.level) {
            case WebInspector.ConsoleMessage.MessageLevel.Warning:
                this.warnings++;
                break;
            case WebInspector.ConsoleMessage.MessageLevel.Error:
                this.errors++;
                break;
        }
    }, messages: function () {
        return this._messages;
    }, requestClearMessages: function () {
        this._consoleAgent.clearMessages();
        this._messagesCleared();
    }, _messagesCleared: function () {
        this._messages = [];
        this.errors = 0;
        this.warnings = 0;
        this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.ConsoleCleared);
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.ConsoleModel.evaluateCommandInConsole = function (executionContext, text, useCommandLineAPI) {
    useCommandLineAPI = !!useCommandLineAPI;
    var target = executionContext.target();
    var commandMessage = new WebInspector.ConsoleMessage(target, WebInspector.ConsoleMessage.MessageSource.JS, null, text, WebInspector.ConsoleMessage.MessageType.Command);
    commandMessage.setExecutionContextId(executionContext.id);
    target.consoleModel.addMessage(commandMessage);
    function printResult(result, wasThrown, valueResult, exceptionDetails) {
        if (!result)
            return;
        WebInspector.console.show();
        this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.CommandEvaluated, {result: result, wasThrown: wasThrown, text: text, commandMessage: commandMessage, exceptionDetails: exceptionDetails});
    }

    executionContext.evaluate(text, "console", useCommandLineAPI, false, false, true, printResult.bind(target.consoleModel));
    WebInspector.userMetrics.ConsoleEvaluated.record();
}
WebInspector.ConsoleMessage = function (target, source, level, messageText, type, url, line, column, requestId, parameters, stackTrace, timestamp, isOutdated, executionContextId, asyncStackTrace) {
    this._target = target;
    this.source = source;
    this.level = level;
    this.messageText = messageText;
    this.type = type || WebInspector.ConsoleMessage.MessageType.Log;
    this.url = url || null;
    this.line = line || 0;
    this.column = column || 0;
    this.parameters = parameters;
    this.stackTrace = stackTrace;
    this.timestamp = timestamp || Date.now();
    this.isOutdated = isOutdated;
    this.executionContextId = executionContextId || 0;
    this.asyncStackTrace = asyncStackTrace;
    this.request = requestId ? target.networkLog.requestForId(requestId) : null;
    if (this.request) {
        this.stackTrace = this.request.initiator.stackTrace;
        this.asyncStackTrace = this.request.initiator.asyncStackTrace;
        if (this.request.initiator && this.request.initiator.url) {
            this.url = this.request.initiator.url;
            this.line = this.request.initiator.lineNumber;
        }
    }
}
WebInspector.ConsoleMessage.prototype = {
    target: function () {
        return this._target;
    }, setOriginatingMessage: function (originatingMessage) {
        this._originatingConsoleMessage = originatingMessage;
        this.executionContextId = originatingMessage.executionContextId;
    }, setExecutionContextId: function (executionContextId) {
        this.executionContextId = executionContextId;
    }, originatingMessage: function () {
        return this._originatingConsoleMessage;
    }, isGroupMessage: function () {
        return this.type === WebInspector.ConsoleMessage.MessageType.StartGroup || this.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed || this.type === WebInspector.ConsoleMessage.MessageType.EndGroup;
    }, isGroupStartMessage: function () {
        return this.type === WebInspector.ConsoleMessage.MessageType.StartGroup || this.type === WebInspector.ConsoleMessage.MessageType.StartGroupCollapsed;
    }, isErrorOrWarning: function () {
        return (this.level === WebInspector.ConsoleMessage.MessageLevel.Warning || this.level === WebInspector.ConsoleMessage.MessageLevel.Error);
    }, clone: function () {
        return new WebInspector.ConsoleMessage(this.target(), this.source, this.level, this.messageText, this.type, this.url, this.line, this.column, this.request ? this.request.requestId : undefined, this.parameters, this.stackTrace, this.timestamp, this.isOutdated, this.executionContextId, this.asyncStackTrace);
    }, isEqual: function (msg) {
        if (!msg)
            return false;
        if (!this._isEqualStackTraces(this.stackTrace, msg.stackTrace))
            return false;
        var asyncTrace1 = this.asyncStackTrace;
        var asyncTrace2 = msg.asyncStackTrace;
        while (asyncTrace1 || asyncTrace2) {
            if (!asyncTrace1 || !asyncTrace2)
                return false;
            if (asyncTrace1.description !== asyncTrace2.description)
                return false;
            if (!this._isEqualStackTraces(asyncTrace1.callFrames, asyncTrace2.callFrames))
                return false;
            asyncTrace1 = asyncTrace1.asyncStackTrace;
            asyncTrace2 = asyncTrace2.asyncStackTrace;
        }
        if (this.parameters) {
            if (!msg.parameters || this.parameters.length !== msg.parameters.length)
                return false;
            for (var i = 0; i < msg.parameters.length; ++i) {
                if (this.parameters[i].type !== msg.parameters[i].type || msg.parameters[i].type === "object" || this.parameters[i].value !== msg.parameters[i].value)
                    return false;
            }
        }
        return (this.target() === msg.target()) && (this.source === msg.source) && (this.type === msg.type) && (this.level === msg.level) && (this.line === msg.line) && (this.url === msg.url) && (this.messageText === msg.messageText) && (this.request === msg.request) && (this.executionContextId === msg.executionContextId);
    }, _isEqualStackTraces: function (stackTrace1, stackTrace2) {
        stackTrace1 = stackTrace1 || [];
        stackTrace2 = stackTrace2 || [];
        if (stackTrace1.length !== stackTrace2.length)
            return false;
        for (var i = 0, n = stackTrace1.length; i < n; ++i) {
            if (stackTrace1[i].url !== stackTrace2[i].url || stackTrace1[i].functionName !== stackTrace2[i].functionName || stackTrace1[i].lineNumber !== stackTrace2[i].lineNumber || stackTrace1[i].columnNumber !== stackTrace2[i].columnNumber)
                return false;
        }
        return true;
    }
}
WebInspector.ConsoleMessage.MessageSource = {
    XML: "xml",
    JS: "javascript",
    Network: "network",
    ConsoleAPI: "console-api",
    Storage: "storage",
    AppCache: "appcache",
    Rendering: "rendering",
    CSS: "css",
    Security: "security",
    Other: "other",
    Deprecation: "deprecation"
}
WebInspector.ConsoleMessage.MessageType = {
    Log: "log",
    Dir: "dir",
    DirXML: "dirxml",
    Table: "table",
    Trace: "trace",
    Clear: "clear",
    StartGroup: "startGroup",
    StartGroupCollapsed: "startGroupCollapsed",
    EndGroup: "endGroup",
    Assert: "assert",
    Result: "result",
    Profile: "profile",
    ProfileEnd: "profileEnd",
    Command: "command"
}
WebInspector.ConsoleMessage.MessageLevel = {Log: "log", Info: "info", Warning: "warning", Error: "error", Debug: "debug"};
WebInspector.ConsoleMessage._messageLevelPriority = {"debug": 0, "log": 1, "info": 2, "warning": 3, "error": 4};
WebInspector.ConsoleMessage.messageLevelComparator = function (a, b) {
    return WebInspector.ConsoleMessage._messageLevelPriority[a.level] - WebInspector.ConsoleMessage._messageLevelPriority[b.level];
}
WebInspector.ConsoleMessage.timestampComparator = function (a, b) {
    return a.timestamp - b.timestamp;
}
WebInspector.ConsoleDispatcher = function (console) {
    this._console = console;
}
WebInspector.ConsoleDispatcher.prototype = {
    messageAdded: function (payload) {
        var consoleMessage = new WebInspector.ConsoleMessage(this._console.target(), payload.source, payload.level, payload.text, payload.type, payload.url, payload.line, payload.column, payload.networkRequestId, payload.parameters, payload.stackTrace, payload.timestamp * 1000, this._console._enablingConsole, payload.executionContextId, payload.asyncStackTrace);
        this._console.addMessage(consoleMessage);
    }, messageRepeatCountUpdated: function (count) {
    }, messagesCleared: function () {
        if (!WebInspector.settings.preserveConsoleLog.get())
            this._console._messagesCleared();
    }
}
WebInspector.MultitargetConsoleModel = function () {
    WebInspector.targetManager.observeTargets(this);
    WebInspector.targetManager.addModelListener(WebInspector.ConsoleModel, WebInspector.ConsoleModel.Events.MessageAdded, this._consoleMessageAdded, this);
    WebInspector.targetManager.addModelListener(WebInspector.ConsoleModel, WebInspector.ConsoleModel.Events.CommandEvaluated, this._commandEvaluated, this);
}
WebInspector.MultitargetConsoleModel.prototype = {
    targetAdded: function (target) {
        if (!this._mainTarget) {
            this._mainTarget = target;
            target.consoleModel.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this);
        }
    }, targetRemoved: function (target) {
        if (this._mainTarget === target) {
            delete this._mainTarget;
            target.consoleModel.removeEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this);
        }
    }, messages: function () {
        var targets = WebInspector.targetManager.targets();
        var result = [];
        for (var i = 0; i < targets.length; ++i)
            result = result.concat(targets[i].consoleModel.messages());
        return result;
    }, _consoleCleared: function () {
        this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.ConsoleCleared);
    }, _consoleMessageAdded: function (event) {
        this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.MessageAdded, event.data);
    }, _commandEvaluated: function (event) {
        this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.CommandEvaluated, event.data);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.multitargetConsoleModel;
WebInspector.Panel = function (name) {
    WebInspector.VBox.call(this);
    this.element.classList.add("panel");
    this.element.classList.add(name);
    this._panelName = name;
    this._shortcuts = ({});
}
WebInspector.Panel.counterRightMargin = 25;
WebInspector.Panel.prototype = {
    get name() {
        return this._panelName;
    }, reset: function () {
    }, defaultFocusedElement: function () {
        return this.element;
    }, searchableView: function () {
        return null;
    }, replaceSelectionWith: function (text) {
    }, replaceAllWith: function (query, text) {
    }, elementsToRestoreScrollPositionsFor: function () {
        return [];
    }, handleShortcut: function (event) {
        var shortcutKey = WebInspector.KeyboardShortcut.makeKeyFromEvent(event);
        var handler = this._shortcuts[shortcutKey];
        if (handler && handler(event)) {
            event.handled = true;
            return;
        }
        var searchableView = this.searchableView();
        if (!searchableView)
            return;
        function handleSearchShortcuts(shortcuts, handler) {
            for (var i = 0; i < shortcuts.length; ++i) {
                if (shortcuts[i].key !== shortcutKey)
                    continue;
                return handler.call(searchableView);
            }
            return false;
        }

        if (handleSearchShortcuts(WebInspector.SearchableView.findShortcuts(), searchableView.handleFindShortcut))
            event.handled = true; else if (handleSearchShortcuts(WebInspector.SearchableView.cancelSearchShortcuts(), searchableView.handleCancelSearchShortcut))
            event.handled = true;
    }, registerShortcuts: function (keys, handler) {
        for (var i = 0; i < keys.length; ++i)
            this._shortcuts[keys[i].key] = handler;
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.PanelWithSidebarTree = function (name, defaultWidth) {
    WebInspector.Panel.call(this, name);
    this._panelSplitView = new WebInspector.SplitView(true, false, this._panelName + "PanelSplitViewState", defaultWidth || 200);
    this._panelSplitView.show(this.element);
    var sidebarView = new WebInspector.VBox();
    sidebarView.setMinimumSize(100, 25);
    sidebarView.show(this._panelSplitView.sidebarElement());
    this._sidebarElement = sidebarView.element;
    this._sidebarElement.classList.add("sidebar");
    var sidebarTreeElement = this._sidebarElement.createChild("ol", "sidebar-tree");
    this.sidebarTree = new TreeOutline(sidebarTreeElement);
}
WebInspector.PanelWithSidebarTree.prototype = {
    sidebarElement: function () {
        return this._sidebarElement;
    }, mainElement: function () {
        return this._panelSplitView.mainElement();
    }, defaultFocusedElement: function () {
        return this.sidebarTree.element || this.element;
    }, __proto__: WebInspector.Panel.prototype
}
WebInspector.PanelDescriptor = function () {
}
WebInspector.PanelDescriptor.prototype = {
    name: function () {
    }, title: function () {
    }, panel: function () {
    }
}
WebInspector.RuntimeExtensionPanelDescriptor = function (extension) {
    this._name = extension.descriptor()["name"];
    this._title = WebInspector.UIString(extension.descriptor()["title"]);
    this._extension = extension;
}
WebInspector.RuntimeExtensionPanelDescriptor.prototype = {
    name: function () {
        return this._name;
    }, title: function () {
        return this._title;
    }, panel: function () {
        return (this._extension.instance());
    }
}
WebInspector.InspectorView = function () {
    WebInspector.VBox.call(this);
    WebInspector.Dialog.setModalHostView(this);
    WebInspector.GlassPane.DefaultFocusedViewStack.push(this);
    this.setMinimumSize(180, 72);
    this._drawerSplitView = new WebInspector.SplitView(false, true, "Inspector.drawerSplitViewState", 200, 200);
    this._drawerSplitView.hideSidebar();
    this._drawerSplitView.enableShowModeSaving();
    this._drawerSplitView.show(this.element);
    this._tabbedPane = new WebInspector.TabbedPane();
    this._tabbedPane.setRetainTabOrder(true, self.runtime.orderComparator(WebInspector.Panel, "name", "order"));
    this._tabbedPane.show(this._drawerSplitView.mainElement());
    this._drawer = new WebInspector.Drawer(this._drawerSplitView);
    this._toolbarElement = document.createElement("div");
    this._toolbarElement.className = "toolbar toolbar-background toolbar-colors";
    var headerElement = this._tabbedPane.headerElement();
    headerElement.parentElement.insertBefore(this._toolbarElement, headerElement);
    this._leftToolbarElement = this._toolbarElement.createChild("div", "toolbar-controls-left");
    this._toolbarElement.appendChild(headerElement);
    this._rightToolbarElement = this._toolbarElement.createChild("div", "toolbar-controls-right");
    this._toolbarItems = [];
    this._closeButtonToolbarItem = document.createElementWithClass("div", "toolbar-close-button-item");
    var closeButtonElement = this._closeButtonToolbarItem.createChild("div", "close-button");
    closeButtonElement.addEventListener("click", InspectorFrontendHost.closeWindow.bind(InspectorFrontendHost), true);
    this._rightToolbarElement.appendChild(this._closeButtonToolbarItem);
    this._panels = {};
    WebInspector["panels"] = this._panels;
    this._history = [];
    this._historyIterator = -1;
    document.addEventListener("keydown", this._keyDown.bind(this), false);
    document.addEventListener("keypress", this._keyPress.bind(this), false);
    this._panelDescriptors = {};
    this._openBracketIdentifiers = ["U+005B", "U+00DB"].keySet();
    this._closeBracketIdentifiers = ["U+005D", "U+00DD"].keySet();
    this._lastActivePanelSetting = WebInspector.settings.createSetting("lastActivePanel", "elements");
    this._loadPanelDesciptors();
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ShowConsole, this.showPanel.bind(this, "console"));
};
WebInspector.InspectorView.prototype = {
    _loadPanelDesciptors: function () {
        WebInspector.startBatchUpdate();
        self.runtime.extensions(WebInspector.Panel).forEach(processPanelExtensions.bind(this));
        function processPanelExtensions(extension) {
            this.addPanel(new WebInspector.RuntimeExtensionPanelDescriptor(extension));
        }

        WebInspector.endBatchUpdate();
    }, appendToLeftToolbar: function (item) {
        this._toolbarItems.push(item);
        this._leftToolbarElement.appendChild(item.element);
    }, appendToRightToolbar: function (item) {
        this._toolbarItems.push(item);
        this._rightToolbarElement.insertBefore(item.element, this._closeButtonToolbarItem);
    }, addPanel: function (panelDescriptor) {
        var panelName = panelDescriptor.name();
        this._panelDescriptors[panelName] = panelDescriptor;
        this._tabbedPane.appendTab(panelName, panelDescriptor.title(), new WebInspector.View());
        if (this._lastActivePanelSetting.get() === panelName)
            this._tabbedPane.selectTab(panelName);
    }, hasPanel: function (panelName) {
        return !!this._panelDescriptors[panelName];
    }, panel: function (panelName) {
        var panelDescriptor = this._panelDescriptors[panelName];
        var panelOrder = this._tabbedPane.allTabs();
        if (!panelDescriptor && panelOrder.length)
            panelDescriptor = this._panelDescriptors[panelOrder[0]];
        var panel = panelDescriptor ? panelDescriptor.panel() : null;
        if (panel)
            this._panels[panelName] = panel;
        return panel;
    }, setCurrentPanelLocked: function (locked) {
        this._currentPanelLocked = locked;
        this._tabbedPane.setCurrentTabLocked(locked);
        for (var i = 0; i < this._toolbarItems.length; ++i)
            this._toolbarItems[i].setEnabled(!locked);
    }, showPanel: function (panelName) {
        if (this._currentPanelLocked)
            return this._currentPanel === this._panels[panelName] ? this._currentPanel : null;
        var panel = this.panel(panelName);
        if (panel)
            this.setCurrentPanel(panel);
        return panel;
    }, currentPanel: function () {
        return this._currentPanel;
    }, showInitialPanel: function () {
        this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this);
        this._tabSelected();
        this._drawer.initialPanelShown();
    }, _tabSelected: function () {
        var panelName = this._tabbedPane.selectedTabId;
        if (!panelName)
            return;
        var panel = this._panelDescriptors[this._tabbedPane.selectedTabId].panel();
        this._panels[panelName] = panel;
        this._tabbedPane.changeTabView(panelName, panel);
        this._currentPanel = panel;
        this._lastActivePanelSetting.set(panel.name);
        this._pushToHistory(panel.name);
        WebInspector.userMetrics.panelShown(panel.name);
        panel.focus();
    }, setCurrentPanel: function (x) {
        if (this._currentPanelLocked)
            return;
        InspectorFrontendHost.bringToFront();
        if (this._currentPanel === x)
            return;
        this._tabbedPane.changeTabView(x.name, x);
        this._tabbedPane.selectTab(x.name);
    }, closeViewInDrawer: function (id) {
        this._drawer.closeView(id);
    }, showCloseableViewInDrawer: function (id, title, view) {
        this._drawer.showCloseableView(id, title, view);
    }, showDrawer: function () {
        this._drawer.showDrawer();
    }, drawerVisible: function () {
        return this._drawer.isShowing();
    }, showViewInDrawer: function (id, immediate) {
        this._drawer.showView(id, immediate);
    }, selectedViewInDrawer: function () {
        return this._drawer.selectedViewId();
    }, closeDrawer: function () {
        this._drawer.closeDrawer();
    }, defaultFocusedElement: function () {
        return this._currentPanel ? this._currentPanel.defaultFocusedElement() : null;
    }, _keyPress: function (event) {
        if (event.charCode < 32 && WebInspector.isWin())
            return;
        clearTimeout(this._keyDownTimer);
        delete this._keyDownTimer;
    }, _keyDown: function (event) {
        if (!WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event))
            return;
        var keyboardEvent = (event);
        var panelShortcutEnabled = WebInspector.settings.shortcutPanelSwitch.get();
        if (panelShortcutEnabled && !event.shiftKey && !event.altKey) {
            var panelIndex = -1;
            if (event.keyCode > 0x30 && event.keyCode < 0x3A)
                panelIndex = event.keyCode - 0x31; else if (event.keyCode > 0x60 && event.keyCode < 0x6A && keyboardEvent.location === KeyboardEvent.DOM_KEY_LOCATION_NUMPAD)
                panelIndex = event.keyCode - 0x61;
            if (panelIndex !== -1) {
                var panelName = this._tabbedPane.allTabs()[panelIndex];
                if (panelName) {
                    if (!WebInspector.Dialog.currentInstance() && !this._currentPanelLocked)
                        this.showPanel(panelName);
                    event.consume(true);
                }
                return;
            }
        }
        if (!WebInspector.isWin() || (!this._openBracketIdentifiers[event.keyIdentifier] && !this._closeBracketIdentifiers[event.keyIdentifier])) {
            this._keyDownInternal(event);
            return;
        }
        this._keyDownTimer = setTimeout(this._keyDownInternal.bind(this, event), 0);
    }, _keyDownInternal: function (event) {
        if (this._currentPanelLocked)
            return;
        var direction = 0;
        if (this._openBracketIdentifiers[event.keyIdentifier])
            direction = -1;
        if (this._closeBracketIdentifiers[event.keyIdentifier])
            direction = 1;
        if (!direction)
            return;
        if (!event.shiftKey && !event.altKey) {
            if (!WebInspector.Dialog.currentInstance())
                this._changePanelInDirection(direction);
            event.consume(true);
            return;
        }
        if (event.altKey && this._moveInHistory(direction))
            event.consume(true)
    }, _changePanelInDirection: function (direction) {
        var panelOrder = this._tabbedPane.allTabs();
        var index = panelOrder.indexOf(this.currentPanel().name);
        index = (index + panelOrder.length + direction) % panelOrder.length;
        this.showPanel(panelOrder[index]);
    }, _moveInHistory: function (move) {
        var newIndex = this._historyIterator + move;
        if (newIndex >= this._history.length || newIndex < 0)
            return false;
        this._inHistory = true;
        this._historyIterator = newIndex;
        if (!WebInspector.Dialog.currentInstance())
            this.setCurrentPanel(this._panels[this._history[this._historyIterator]]);
        delete this._inHistory;
        return true;
    }, _pushToHistory: function (panelName) {
        if (this._inHistory)
            return;
        this._history.splice(this._historyIterator + 1, this._history.length - this._historyIterator - 1);
        if (!this._history.length || this._history[this._history.length - 1] !== panelName)
            this._history.push(panelName);
        this._historyIterator = this._history.length - 1;
    }, onResize: function () {
        WebInspector.Dialog.modalHostRepositioned();
    }, topResizerElement: function () {
        return this._tabbedPane.headerElement();
    }, toolbarItemResized: function () {
        this._tabbedPane.headerResized();
    }, __proto__: WebInspector.VBox.prototype
};
WebInspector.inspectorView;
WebInspector.InspectorView.DrawerToggleActionDelegate = function () {
}
WebInspector.InspectorView.DrawerToggleActionDelegate.prototype = {
    handleAction: function () {
        if (WebInspector.inspectorView.drawerVisible()) {
            WebInspector.inspectorView.closeDrawer();
            return true;
        }
        WebInspector.inspectorView.showDrawer();
        return true;
    }
}
WebInspector.InspectorView.ToggleDrawerButtonProvider = function () {
}
WebInspector.InspectorView.ToggleDrawerButtonProvider.prototype = {
    item: function () {
        return WebInspector.inspectorView._drawer.toggleButton();
    }
}
WebInspector.TimelineGrid = function () {
    this.element = document.createElement("div");
    this._dividersElement = this.element.createChild("div", "resources-dividers");
    this._gridHeaderElement = document.createElement("div");
    this._gridHeaderElement.id = "timeline-grid-header";
    this._eventDividersElement = this._gridHeaderElement.createChild("div", "resources-event-dividers");
    this._dividersLabelBarElement = this._gridHeaderElement.createChild("div", "resources-dividers-label-bar");
    this.element.appendChild(this._gridHeaderElement);
    this._leftCurtainElement = this.element.createChild("div", "timeline-cpu-curtain-left");
    this._rightCurtainElement = this.element.createChild("div", "timeline-cpu-curtain-right");
}
WebInspector.TimelineGrid.calculateDividerOffsets = function (calculator, clientWidth) {
    const minGridSlicePx = 64;
    const gridFreeZoneAtLeftPx = 50;
    var dividersCount = clientWidth / minGridSlicePx;
    var gridSliceTime = calculator.boundarySpan() / dividersCount;
    var pixelsPerTime = clientWidth / calculator.boundarySpan();
    var logGridSliceTime = Math.ceil(Math.log(gridSliceTime) / Math.LN10);
    gridSliceTime = Math.pow(10, logGridSliceTime);
    if (gridSliceTime * pixelsPerTime >= 5 * minGridSlicePx)
        gridSliceTime = gridSliceTime / 5;
    if (gridSliceTime * pixelsPerTime >= 2 * minGridSlicePx)
        gridSliceTime = gridSliceTime / 2;
    var firstDividerTime = Math.ceil((calculator.minimumBoundary() - calculator.zeroTime()) / gridSliceTime) * gridSliceTime + calculator.zeroTime();
    var lastDividerTime = calculator.maximumBoundary();
    if (calculator.paddingLeft() > 0)
        lastDividerTime = lastDividerTime + minGridSlicePx / pixelsPerTime;
    dividersCount = Math.ceil((lastDividerTime - firstDividerTime) / gridSliceTime);
    var skipLeftmostDividers = calculator.paddingLeft() === 0;
    if (!gridSliceTime)
        dividersCount = 0;
    var offsets = [];
    for (var i = 0; i < dividersCount; ++i) {
        var left = calculator.computePosition(firstDividerTime + gridSliceTime * i);
        if (skipLeftmostDividers && left < gridFreeZoneAtLeftPx)
            continue;
        offsets.push(firstDividerTime + gridSliceTime * i);
    }
    return {offsets: offsets, precision: Math.max(0, -Math.floor(Math.log(gridSliceTime * 1.01) / Math.LN10))};
}
WebInspector.TimelineGrid.drawCanvasGrid = function (canvas, calculator, dividerOffsets) {
    var context = canvas.getContext("2d");
    context.save();
    var ratio = window.devicePixelRatio;
    context.scale(ratio, ratio);
    var printDeltas = !!dividerOffsets;
    var width = canvas.width / window.devicePixelRatio;
    var height = canvas.height / window.devicePixelRatio;
    var precision = 0;
    if (!dividerOffsets) {
        var dividersData = WebInspector.TimelineGrid.calculateDividerOffsets(calculator, width);
        dividerOffsets = dividersData.offsets;
        precision = dividersData.precision;
    }
    context.fillStyle = "rgba(255, 255, 255, 0.5)";
    context.fillRect(0, 0, width, 15);
    context.fillStyle = "#333";
    context.strokeStyle = "rgba(0, 0, 0, 0.1)";
    context.textBaseline = "hanging";
    context.font = (printDeltas ? "italic bold 11px " : " 11px ") + WebInspector.fontFamily();
    context.lineWidth = 1;
    context.translate(0.5, 0.5);
    const minWidthForTitle = 60;
    var lastPosition = 0;
    var time = 0;
    var lastTime = 0;
    var paddingRight = 4;
    var paddingTop = 3;
    for (var i = 0; i < dividerOffsets.length; ++i) {
        time = dividerOffsets[i];
        var position = calculator.computePosition(time);
        context.beginPath();
        if (position - lastPosition > minWidthForTitle) {
            if (!printDeltas || i !== 0) {
                var text = printDeltas ? calculator.formatTime(calculator.zeroTime() + time - lastTime) : calculator.formatTime(time, precision);
                var textWidth = context.measureText(text).width;
                var textPosition = printDeltas ? (position + lastPosition - textWidth) / 2 : position - textWidth - paddingRight;
                context.fillText(text, textPosition, paddingTop);
            }
        }
        context.moveTo(position, 0);
        context.lineTo(position, height);
        context.stroke();
        lastTime = time;
        lastPosition = position;
    }
    context.restore();
}, WebInspector.TimelineGrid.prototype = {
    get dividersElement() {
        return this._dividersElement;
    }, get dividersLabelBarElement() {
        return this._dividersLabelBarElement;
    }, removeDividers: function () {
        this._dividersElement.removeChildren();
        this._dividersLabelBarElement.removeChildren();
    }, updateDividers: function (calculator, dividerOffsets, printDeltas) {
        var precision = 0;
        if (!dividerOffsets) {
            var dividersData = WebInspector.TimelineGrid.calculateDividerOffsets(calculator, this._dividersElement.clientWidth);
            dividerOffsets = dividersData.offsets;
            precision = dividersData.precision;
            printDeltas = false;
        }
        var dividersElementClientWidth = this._dividersElement.clientWidth;
        var divider = (this._dividersElement.firstChild);
        var dividerLabelBar = (this._dividersLabelBarElement.firstChild);
        const minWidthForTitle = 60;
        var lastPosition = 0;
        var lastTime = 0;
        for (var i = 0; i < dividerOffsets.length; ++i) {
            if (!divider) {
                divider = document.createElement("div");
                divider.className = "resources-divider";
                this._dividersElement.appendChild(divider);
                dividerLabelBar = document.createElement("div");
                dividerLabelBar.className = "resources-divider";
                var label = document.createElement("div");
                label.className = "resources-divider-label";
                dividerLabelBar._labelElement = label;
                dividerLabelBar.appendChild(label);
                this._dividersLabelBarElement.appendChild(dividerLabelBar);
            }
            var time = dividerOffsets[i];
            var position = calculator.computePosition(time);
            if (position - lastPosition > minWidthForTitle)
                dividerLabelBar._labelElement.textContent = printDeltas ? calculator.formatTime(time - lastTime) : calculator.formatTime(time, precision); else
                dividerLabelBar._labelElement.textContent = "";
            if (printDeltas)
                dividerLabelBar._labelElement.style.width = Math.ceil(position - lastPosition) + "px"; else
                dividerLabelBar._labelElement.style.removeProperty("width");
            lastPosition = position;
            lastTime = time;
            var percentLeft = 100 * position / dividersElementClientWidth;
            divider.style.left = percentLeft + "%";
            dividerLabelBar.style.left = percentLeft + "%";
            divider = (divider.nextSibling);
            dividerLabelBar = (dividerLabelBar.nextSibling);
        }
        while (divider) {
            var nextDivider = divider.nextSibling;
            this._dividersElement.removeChild(divider);
            divider = nextDivider;
        }
        while (dividerLabelBar) {
            var nextDivider = dividerLabelBar.nextSibling;
            this._dividersLabelBarElement.removeChild(dividerLabelBar);
            dividerLabelBar = nextDivider;
        }
        return true;
    }, addEventDivider: function (divider) {
        this._eventDividersElement.appendChild(divider);
    }, addEventDividers: function (dividers) {
        this._gridHeaderElement.removeChild(this._eventDividersElement);
        for (var i = 0; i < dividers.length; ++i) {
            if (dividers[i])
                this._eventDividersElement.appendChild(dividers[i]);
        }
        this._gridHeaderElement.appendChild(this._eventDividersElement);
    }, removeEventDividers: function () {
        this._eventDividersElement.removeChildren();
    }, hideEventDividers: function () {
        this._eventDividersElement.classList.add("hidden");
    }, showEventDividers: function () {
        this._eventDividersElement.classList.remove("hidden");
    }, hideDividers: function () {
        this._dividersElement.classList.add("hidden");
    }, showDividers: function () {
        this._dividersElement.classList.remove("hidden");
    }, hideCurtains: function () {
        this._leftCurtainElement.classList.add("hidden");
        this._rightCurtainElement.classList.add("hidden");
    }, showCurtains: function (gapOffset, gapWidth) {
        this._leftCurtainElement.style.width = gapOffset + "px";
        this._leftCurtainElement.classList.remove("hidden");
        this._rightCurtainElement.style.left = (gapOffset + gapWidth) + "px";
        this._rightCurtainElement.classList.remove("hidden");
    }, setScrollAndDividerTop: function (scrollTop, dividersTop) {
        this._dividersLabelBarElement.style.top = scrollTop + "px";
        this._eventDividersElement.style.top = scrollTop + "px";
        this._leftCurtainElement.style.top = scrollTop + "px";
        this._rightCurtainElement.style.top = scrollTop + "px";
    }
}
WebInspector.TimelineGrid.Calculator = function () {
}
WebInspector.TimelineGrid.Calculator.prototype = {
    paddingLeft: function () {
    }, computePosition: function (time) {
    }, formatTime: function (time, precision) {
    }, minimumBoundary: function () {
    }, zeroTime: function () {
    }, maximumBoundary: function () {
    }, boundarySpan: function () {
    }
}
WebInspector.OverviewGrid = function (prefix) {
    this.element = document.createElement("div");
    this.element.id = prefix + "-overview-container";
    this._grid = new WebInspector.TimelineGrid();
    this._grid.element.id = prefix + "-overview-grid";
    this._grid.setScrollAndDividerTop(0, 0);
    this.element.appendChild(this._grid.element);
    this._window = new WebInspector.OverviewGrid.Window(this.element, this._grid.dividersLabelBarElement);
}
WebInspector.OverviewGrid.prototype = {
    clientWidth: function () {
        return this.element.clientWidth;
    }, updateDividers: function (calculator) {
        this._grid.updateDividers(calculator);
    }, addEventDividers: function (dividers) {
        this._grid.addEventDividers(dividers);
    }, removeEventDividers: function () {
        this._grid.removeEventDividers();
    }, setWindowPosition: function (start, end) {
        this._window._setWindowPosition(start, end);
    }, reset: function () {
        this._window.reset();
    }, windowLeft: function () {
        return this._window.windowLeft;
    }, windowRight: function () {
        return this._window.windowRight;
    }, setWindow: function (left, right) {
        this._window._setWindow(left, right);
    }, addEventListener: function (eventType, listener, thisObject) {
        this._window.addEventListener(eventType, listener, thisObject);
    }, zoom: function (zoomFactor, referencePoint) {
        this._window._zoom(zoomFactor, referencePoint);
    }, setResizeEnabled: function (enabled) {
        this._window._setEnabled(!!enabled);
    }
}
WebInspector.OverviewGrid.MinSelectableSize = 14;
WebInspector.OverviewGrid.WindowScrollSpeedFactor = .3;
WebInspector.OverviewGrid.ResizerOffset = 3.5;
WebInspector.OverviewGrid.Window = function (parentElement, dividersLabelBarElement) {
    this._parentElement = parentElement;
    WebInspector.installDragHandle(this._parentElement, this._startWindowSelectorDragging.bind(this), this._windowSelectorDragging.bind(this), this._endWindowSelectorDragging.bind(this), "ew-resize", null);
    if (dividersLabelBarElement)
        WebInspector.installDragHandle(dividersLabelBarElement, this._startWindowDragging.bind(this), this._windowDragging.bind(this), null, "move");
    this.windowLeft = 0.0;
    this.windowRight = 1.0;
    this._parentElement.addEventListener("mousewheel", this._onMouseWheel.bind(this), true);
    this._parentElement.addEventListener("dblclick", this._resizeWindowMaximum.bind(this), true);
    this._overviewWindowElement = parentElement.createChild("div", "overview-grid-window");
    this._overviewWindowBordersElement = parentElement.createChild("div", "overview-grid-window-rulers");
    parentElement.createChild("div", "overview-grid-dividers-background");
    this._leftResizeElement = parentElement.createChild("div", "overview-grid-window-resizer");
    this._leftResizeElement.style.left = 0;
    WebInspector.installDragHandle(this._leftResizeElement, this._resizerElementStartDragging.bind(this), this._leftResizeElementDragging.bind(this), null, "ew-resize");
    this._rightResizeElement = parentElement.createChild("div", "overview-grid-window-resizer overview-grid-window-resizer-right");
    this._rightResizeElement.style.right = 0;
    WebInspector.installDragHandle(this._rightResizeElement, this._resizerElementStartDragging.bind(this), this._rightResizeElementDragging.bind(this), null, "ew-resize");
    this._setEnabled(true);
}
WebInspector.OverviewGrid.Events = {WindowChanged: "WindowChanged"}
WebInspector.OverviewGrid.Window.prototype = {
    reset: function () {
        this.windowLeft = 0.0;
        this.windowRight = 1.0;
        this._overviewWindowElement.style.left = "0%";
        this._overviewWindowElement.style.width = "100%";
        this._overviewWindowBordersElement.style.left = "0%";
        this._overviewWindowBordersElement.style.right = "0%";
        this._leftResizeElement.style.left = "0%";
        this._rightResizeElement.style.left = "100%";
        this._setEnabled(true);
    }, _setEnabled: function (enabled) {
        enabled = !!enabled;
        if (this._enabled === enabled)
            return;
        this._enabled = enabled;
    }, _resizerElementStartDragging: function (event) {
        if (!this._enabled)
            return false;
        this._resizerParentOffsetLeft = event.pageX - event.offsetX - event.target.offsetLeft;
        event.preventDefault();
        return true;
    }, _leftResizeElementDragging: function (event) {
        this._resizeWindowLeft(event.pageX - this._resizerParentOffsetLeft);
        event.preventDefault();
    }, _rightResizeElementDragging: function (event) {
        this._resizeWindowRight(event.pageX - this._resizerParentOffsetLeft);
        event.preventDefault();
    }, _startWindowSelectorDragging: function (event) {
        if (!this._enabled)
            return false;
        this._offsetLeft = this._parentElement.totalOffsetLeft();
        var position = event.x - this._offsetLeft;
        this._overviewWindowSelector = new WebInspector.OverviewGrid.WindowSelector(this._parentElement, position);
        return true;
    }, _windowSelectorDragging: function (event) {
        this._overviewWindowSelector._updatePosition(event.x - this._offsetLeft);
        event.preventDefault();
    }, _endWindowSelectorDragging: function (event) {
        var window = this._overviewWindowSelector._close(event.x - this._offsetLeft);
        delete this._overviewWindowSelector;
        if (window.end === window.start) {
            var middle = window.end;
            window.start = Math.max(0, middle - WebInspector.OverviewGrid.MinSelectableSize / 2);
            window.end = Math.min(this._parentElement.clientWidth, middle + WebInspector.OverviewGrid.MinSelectableSize / 2);
        } else if (window.end - window.start < WebInspector.OverviewGrid.MinSelectableSize) {
            if (this._parentElement.clientWidth - window.end > WebInspector.OverviewGrid.MinSelectableSize)
                window.end = window.start + WebInspector.OverviewGrid.MinSelectableSize; else
                window.start = window.end - WebInspector.OverviewGrid.MinSelectableSize;
        }
        this._setWindowPosition(window.start, window.end);
    }, _startWindowDragging: function (event) {
        this._dragStartPoint = event.pageX;
        this._dragStartLeft = this.windowLeft;
        this._dragStartRight = this.windowRight;
        return true;
    }, _windowDragging: function (event) {
        event.preventDefault();
        var delta = (event.pageX - this._dragStartPoint) / this._parentElement.clientWidth;
        if (this._dragStartLeft + delta < 0)
            delta = -this._dragStartLeft;
        if (this._dragStartRight + delta > 1)
            delta = 1 - this._dragStartRight;
        this._setWindow(this._dragStartLeft + delta, this._dragStartRight + delta);
    }, _resizeWindowLeft: function (start) {
        if (start < 10)
            start = 0; else if (start > this._rightResizeElement.offsetLeft - 4)
            start = this._rightResizeElement.offsetLeft - 4;
        this._setWindowPosition(start, null);
    }, _resizeWindowRight: function (end) {
        if (end > this._parentElement.clientWidth - 10)
            end = this._parentElement.clientWidth; else if (end < this._leftResizeElement.offsetLeft + WebInspector.OverviewGrid.MinSelectableSize)
            end = this._leftResizeElement.offsetLeft + WebInspector.OverviewGrid.MinSelectableSize;
        this._setWindowPosition(null, end);
    }, _resizeWindowMaximum: function () {
        this._setWindowPosition(0, this._parentElement.clientWidth);
    }, _setWindow: function (windowLeft, windowRight) {
        var left = windowLeft;
        var right = windowRight;
        var width = windowRight - windowLeft;
        var widthInPixels = width * this._parentElement.clientWidth;
        var minWidthInPixels = WebInspector.OverviewGrid.MinSelectableSize / 2;
        if (widthInPixels < minWidthInPixels) {
            var factor = minWidthInPixels / widthInPixels;
            left = ((windowRight + windowLeft) - width * factor) / 2;
            right = ((windowRight + windowLeft) + width * factor) / 2;
        }
        this.windowLeft = windowLeft;
        this._leftResizeElement.style.left = left * 100 + "%";
        this.windowRight = windowRight;
        this._rightResizeElement.style.left = right * 100 + "%";
        this._overviewWindowElement.style.left = left * 100 + "%";
        this._overviewWindowBordersElement.style.left = left * 100 + "%";
        this._overviewWindowElement.style.width = (right - left) * 100 + "%";
        this._overviewWindowBordersElement.style.right = (1 - right) * 100 + "%";
        this.dispatchEventToListeners(WebInspector.OverviewGrid.Events.WindowChanged);
    }, _setWindowPosition: function (start, end) {
        var clientWidth = this._parentElement.clientWidth;
        var windowLeft = typeof start === "number" ? start / clientWidth : this.windowLeft;
        var windowRight = typeof end === "number" ? end / clientWidth : this.windowRight;
        this._setWindow(windowLeft, windowRight);
    }, _onMouseWheel: function (event) {
        if (typeof event.wheelDeltaY === "number" && event.wheelDeltaY) {
            const zoomFactor = 1.1;
            const mouseWheelZoomSpeed = 1 / 120;
            var reference = event.offsetX / event.target.clientWidth;
            this._zoom(Math.pow(zoomFactor, -event.wheelDeltaY * mouseWheelZoomSpeed), reference);
        }
        if (typeof event.wheelDeltaX === "number" && event.wheelDeltaX) {
            var offset = Math.round(event.wheelDeltaX * WebInspector.OverviewGrid.WindowScrollSpeedFactor);
            var windowLeft = this._leftResizeElement.offsetLeft + WebInspector.OverviewGrid.ResizerOffset;
            var windowRight = this._rightResizeElement.offsetLeft + WebInspector.OverviewGrid.ResizerOffset;
            if (windowLeft - offset < 0)
                offset = windowLeft;
            if (windowRight - offset > this._parentElement.clientWidth)
                offset = windowRight - this._parentElement.clientWidth;
            this._setWindowPosition(windowLeft - offset, windowRight - offset);
            event.preventDefault();
        }
    }, _zoom: function (factor, reference) {
        var left = this.windowLeft;
        var right = this.windowRight;
        var windowSize = right - left;
        var newWindowSize = factor * windowSize;
        if (newWindowSize > 1) {
            newWindowSize = 1;
            factor = newWindowSize / windowSize;
        }
        left = reference + (left - reference) * factor;
        left = Number.constrain(left, 0, 1 - newWindowSize);
        right = reference + (right - reference) * factor;
        right = Number.constrain(right, newWindowSize, 1);
        this._setWindow(left, right);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.OverviewGrid.WindowSelector = function (parent, position) {
    this._startPosition = position;
    this._width = parent.offsetWidth;
    this._windowSelector = document.createElement("div");
    this._windowSelector.className = "overview-grid-window-selector";
    this._windowSelector.style.left = this._startPosition + "px";
    this._windowSelector.style.right = this._width - this._startPosition + "px";
    parent.appendChild(this._windowSelector);
}
WebInspector.OverviewGrid.WindowSelector.prototype = {
    _close: function (position) {
        position = Math.max(0, Math.min(position, this._width));
        this._windowSelector.remove();
        return this._startPosition < position ? {start: this._startPosition, end: position} : {start: position, end: this._startPosition};
    }, _updatePosition: function (position) {
        position = Math.max(0, Math.min(position, this._width));
        if (position < this._startPosition) {
            this._windowSelector.style.left = position + "px";
            this._windowSelector.style.right = this._width - this._startPosition + "px";
        } else {
            this._windowSelector.style.left = this._startPosition + "px";
            this._windowSelector.style.right = this._width - position + "px";
        }
    }
}
WebInspector.SearchConfig = function (query, ignoreCase, isRegex) {
    this._query = query;
    this._ignoreCase = ignoreCase;
    this._isRegex = isRegex;
    this._parse();
}
WebInspector.SearchConfig.RegexQuery;
WebInspector.SearchConfig.fromPlainObject = function (object) {
    return new WebInspector.SearchConfig(object.query, object.ignoreCase, object.isRegex);
}
WebInspector.SearchConfig.prototype = {
    query: function () {
        return this._query;
    }, ignoreCase: function () {
        return this._ignoreCase;
    }, isRegex: function () {
        return this._isRegex;
    }, toPlainObject: function () {
        return {query: this.query(), ignoreCase: this.ignoreCase(), isRegex: this.isRegex()};
    }, _parse: function () {
        var filePattern = "-?file:(([^\\\\ ]|\\\\.)+)";
        var quotedPattern = "\"(([^\\\\\"]|\\\\.)+)\"";
        var unquotedWordPattern = "((?!-?file:)[^\\\\ ]|\\\\.)+";
        var unquotedPattern = unquotedWordPattern + "( +" + unquotedWordPattern + ")*";
        var pattern = "(" + filePattern + ")|(" + quotedPattern + ")|(" + unquotedPattern + ")";
        var regexp = new RegExp(pattern, "g");
        var queryParts = this._query.match(regexp) || [];
        this._fileQueries = [];
        this._queries = [];
        for (var i = 0; i < queryParts.length; ++i) {
            var queryPart = queryParts[i];
            if (!queryPart)
                continue;
            var fileQuery = this._parseFileQuery(queryPart);
            if (fileQuery) {
                this._fileQueries.push(fileQuery);
                this._fileRegexQueries = this._fileRegexQueries || [];
                this._fileRegexQueries.push({regex: new RegExp(fileQuery.text, this.ignoreCase ? "i" : ""), isNegative: fileQuery.isNegative});
                continue;
            }
            if (queryPart.startsWith("\"")) {
                if (!queryPart.endsWith("\""))
                    continue;
                this._queries.push(this._parseQuotedQuery(queryPart));
                continue;
            }
            this._queries.push(this._parseUnquotedQuery(queryPart));
        }
    }, filePathMatchesFileQuery: function (filePath) {
        if (!this._fileRegexQueries)
            return true;
        for (var i = 0; i < this._fileRegexQueries.length; ++i) {
            if (!!filePath.match(this._fileRegexQueries[i].regex) === this._fileRegexQueries[i].isNegative)
                return false;
        }
        return true;
    }, queries: function () {
        return this._queries;
    }, _parseUnquotedQuery: function (query) {
        return query.replace(/\\(.)/g, "$1");
    }, _parseQuotedQuery: function (query) {
        return query.substring(1, query.length - 1).replace(/\\(.)/g, "$1");
    }, _parseFileQuery: function (query) {
        var match = query.match(/^(-)?file:/);
        if (!match)
            return null;
        var isNegative = !!match[1];
        query = query.substr(match[0].length);
        var result = "";
        for (var i = 0; i < query.length; ++i) {
            var char = query[i];
            if (char === "*") {
                result += ".*";
            } else if (char === "\\") {
                ++i;
                var nextChar = query[i];
                if (nextChar === " ")
                    result += " ";
            } else {
                if (String.regexSpecialCharacters().indexOf(query.charAt(i)) !== -1)
                    result += "\\";
                result += query.charAt(i);
            }
        }
        return new WebInspector.SearchConfig.QueryTerm(result, isNegative);
    }
}
WebInspector.SearchConfig.QueryTerm = function (text, isNegative) {
    this.text = text;
    this.isNegative = isNegative;
}
WebInspector.ContentProvider = function () {
}
WebInspector.ContentProvider.prototype = {
    contentURL: function () {
    }, contentType: function () {
    }, requestContent: function (callback) {
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
    }
}
WebInspector.ContentProvider.SearchMatch = function (lineNumber, lineContent) {
    this.lineNumber = lineNumber;
    this.lineContent = lineContent;
}
WebInspector.ContentProvider.performSearchInContent = function (content, query, caseSensitive, isRegex) {
    var regex = createSearchRegex(query, caseSensitive, isRegex);
    var contentString = new String(content);
    var result = [];
    for (var i = 0; i < contentString.lineCount(); ++i) {
        var lineContent = contentString.lineAt(i);
        regex.lastIndex = 0;
        if (regex.exec(lineContent))
            result.push(new WebInspector.ContentProvider.SearchMatch(i, lineContent));
    }
    return result;
}
WebInspector.StaticContentProvider = function (contentType, content) {
    this._content = content;
    this._contentType = contentType;
}
WebInspector.StaticContentProvider.prototype = {
    contentURL: function () {
        return "";
    }, contentType: function () {
        return this._contentType;
    }, requestContent: function (callback) {
        callback(this._content);
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        function performSearch() {
            callback(WebInspector.ContentProvider.performSearchInContent(this._content, query, caseSensitive, isRegex));
        }

        self.setTimeout(performSearch.bind(this), 0);
    }
}
WebInspector.Resource = function (target, request, url, documentURL, frameId, loaderId, type, mimeType, isHidden) {
    WebInspector.SDKObject.call(this, target);
    this._request = request;
    this.url = url;
    this._documentURL = documentURL;
    this._frameId = frameId;
    this._loaderId = loaderId;
    this._type = type || WebInspector.resourceTypes.Other;
    this._mimeType = mimeType;
    this._isHidden = isHidden;
    this._content;
    this._contentEncoded;
    this._pendingContentCallbacks = [];
    if (this._request && !this._request.finished)
        this._request.addEventListener(WebInspector.NetworkRequest.Events.FinishedLoading, this._requestFinished, this);
}
WebInspector.Resource.Events = {MessageAdded: "message-added", MessagesCleared: "messages-cleared",}
WebInspector.Resource.contentAsDataURL = function (content, mimeType, contentEncoded) {
    const maxDataUrlSize = 1024 * 1024;
    if (content === null || content.length > maxDataUrlSize)
        return null;
    return "data:" + mimeType + (contentEncoded ? ";base64," : ",") + content;
}
WebInspector.Resource.prototype = {
    get request() {
        return this._request;
    }, get url() {
        return this._url;
    }, set url(x) {
        this._url = x;
        this._parsedURL = new WebInspector.ParsedURL(x);
    }, get parsedURL() {
        return this._parsedURL;
    }, get documentURL() {
        return this._documentURL;
    }, get frameId() {
        return this._frameId;
    }, get loaderId() {
        return this._loaderId;
    }, get displayName() {
        return this._parsedURL.displayName;
    }, get type() {
        return this._request ? this._request.type : this._type;
    }, get mimeType() {
        return this._request ? this._request.mimeType : this._mimeType;
    }, get messages() {
        return this._messages || [];
    }, addMessage: function (msg) {
        if (!msg.isErrorOrWarning() || !msg.messageText)
            return;
        if (!this._messages)
            this._messages = [];
        this._messages.push(msg);
        this.dispatchEventToListeners(WebInspector.Resource.Events.MessageAdded, msg);
    }, get errors() {
        return this._errors || 0;
    }, set errors(x) {
        this._errors = x;
    }, get warnings() {
        return this._warnings || 0;
    }, set warnings(x) {
        this._warnings = x;
    }, clearErrorsAndWarnings: function () {
        this._messages = [];
        this._warnings = 0;
        this._errors = 0;
        this.dispatchEventToListeners(WebInspector.Resource.Events.MessagesCleared);
    }, get content() {
        return this._content;
    }, get contentEncoded() {
        return this._contentEncoded;
    }, contentURL: function () {
        return this._url;
    }, contentType: function () {
        return this.type;
    }, requestContent: function (callback) {
        if (typeof this._content !== "undefined") {
            callback(this._content);
            return;
        }
        this._pendingContentCallbacks.push(callback);
        if (!this._request || this._request.finished)
            this._innerRequestContent();
    }, canonicalMimeType: function () {
        return this.type.canonicalMimeType() || this.mimeType;
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        function callbackWrapper(error, searchMatches) {
            callback(searchMatches || []);
        }

        if (this.type === WebInspector.resourceTypes.Document) {
            callback([]);
            return;
        }
        if (this.frameId)
            this.target().pageAgent().searchInResource(this.frameId, this.url, query, caseSensitive, isRegex, callbackWrapper); else
            callback([]);
    }, populateImageSource: function (image) {
        function onResourceContent(content) {
            var imageSrc = WebInspector.Resource.contentAsDataURL(this._content, this.mimeType, this._contentEncoded);
            if (imageSrc === null)
                imageSrc = this.url;
            image.src = imageSrc;
        }

        this.requestContent(onResourceContent.bind(this));
    }, _requestFinished: function () {
        this._request.removeEventListener(WebInspector.NetworkRequest.Events.FinishedLoading, this._requestFinished, this);
        if (this._pendingContentCallbacks.length)
            this._innerRequestContent();
    }, _innerRequestContent: function () {
        if (this._contentRequested)
            return;
        this._contentRequested = true;
        function contentLoaded(error, content, contentEncoded) {
            if (error || content === null) {
                replyWithContent.call(this, null, false);
                return;
            }
            replyWithContent.call(this, content, contentEncoded);
        }

        function replyWithContent(content, contentEncoded) {
            this._content = content;
            this._contentEncoded = contentEncoded;
            var callbacks = this._pendingContentCallbacks.slice();
            for (var i = 0; i < callbacks.length; ++i)
                callbacks[i](this._content);
            this._pendingContentCallbacks.length = 0;
            delete this._contentRequested;
        }

        function resourceContentLoaded(error, content, contentEncoded) {
            contentLoaded.call(this, error, content, contentEncoded);
        }

        if (this.request) {
            this.request.requestContent(requestContentLoaded.bind(this));
            return;
        }
        function requestContentLoaded(content) {
            contentLoaded.call(this, null, content, this.request.contentEncoded);
        }

        this.target().pageAgent().getResourceContent(this.frameId, this.url, resourceContentLoaded.bind(this));
    }, isHidden: function () {
        return !!this._isHidden;
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.NetworkRequest = function (target, requestId, url, documentURL, frameId, loaderId) {
    WebInspector.SDKObject.call(this, target);
    this._requestId = requestId;
    this.url = url;
    this._documentURL = documentURL;
    this._frameId = frameId;
    this._loaderId = loaderId;
    this._startTime = -1;
    this._endTime = -1;
    this.statusCode = 0;
    this.statusText = "";
    this.requestMethod = "";
    this.requestTime = 0;
    this._type = WebInspector.resourceTypes.Other;
    this._contentEncoded = false;
    this._pendingContentCallbacks = [];
    this._frames = [];
    this._responseHeaderValues = {};
    this._remoteAddress = "";
}
WebInspector.NetworkRequest.Events = {
    FinishedLoading: "FinishedLoading",
    TimingChanged: "TimingChanged",
    RemoteAddressChanged: "RemoteAddressChanged",
    RequestHeadersChanged: "RequestHeadersChanged",
    ResponseHeadersChanged: "ResponseHeadersChanged",
}
WebInspector.NetworkRequest.InitiatorType = {Other: "other", Parser: "parser", Redirect: "redirect", Script: "script"}
WebInspector.NetworkRequest.NameValue;
WebInspector.NetworkRequest.WebSocketFrameType = {Send: "send", Receive: "receive", Error: "error"}
WebInspector.NetworkRequest.WebSocketFrame;
WebInspector.NetworkRequest.prototype = {
    indentityCompare: function (other) {
        if (this._requestId > other._requestId)
            return 1;
        if (this._requestId < other._requestId)
            return -1;
        return 0;
    }, get requestId() {
        return this._requestId;
    }, set requestId(requestId) {
        this._requestId = requestId;
    }, get url() {
        return this._url;
    }, set url(x) {
        if (this._url === x)
            return;
        this._url = x;
        this._parsedURL = new WebInspector.ParsedURL(x);
        delete this._queryString;
        delete this._parsedQueryParameters;
        delete this._name;
        delete this._path;
    }, get documentURL() {
        return this._documentURL;
    }, get parsedURL() {
        return this._parsedURL;
    }, get frameId() {
        return this._frameId;
    }, get loaderId() {
        return this._loaderId;
    }, setRemoteAddress: function (ip, port) {
        if (ip.indexOf(":") !== -1)
            ip = "[" + ip + "]";
        this._remoteAddress = ip + ":" + port;
        this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.RemoteAddressChanged, this);
    }, remoteAddress: function () {
        return this._remoteAddress;
    }, get startTime() {
        return this._startTime || -1;
    }, set startTime(x) {
        this._startTime = x;
    }, get responseReceivedTime() {
        return this._responseReceivedTime || -1;
    }, set responseReceivedTime(x) {
        this._responseReceivedTime = x;
    }, get endTime() {
        return this._endTime || -1;
    }, set endTime(x) {
        if (this.timing && this.timing.requestTime) {
            this._endTime = Math.max(x, this.responseReceivedTime);
        } else {
            this._endTime = x;
            if (this._responseReceivedTime > x)
                this._responseReceivedTime = x;
        }
        this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.TimingChanged, this);
    }, get duration() {
        if (this._endTime === -1 || this._startTime === -1)
            return -1;
        return this._endTime - this._startTime;
    }, get latency() {
        if (this._responseReceivedTime === -1 || this._startTime === -1)
            return -1;
        return this._responseReceivedTime - this._startTime;
    }, get resourceSize() {
        return this._resourceSize || 0;
    }, set resourceSize(x) {
        this._resourceSize = x;
    }, get transferSize() {
        return this._transferSize || 0;
    }, increaseTransferSize: function (x) {
        this._transferSize = (this._transferSize || 0) + x;
    }, setTransferSize: function (x) {
        this._transferSize = x;
    }, get finished() {
        return this._finished;
    }, set finished(x) {
        if (this._finished === x)
            return;
        this._finished = x;
        if (x) {
            this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.FinishedLoading, this);
            if (this._pendingContentCallbacks.length)
                this._innerRequestContent();
        }
    }, get failed() {
        return this._failed;
    }, set failed(x) {
        this._failed = x;
    }, get canceled() {
        return this._canceled;
    }, set canceled(x) {
        this._canceled = x;
    }, get cached() {
        return !!this._cached && !this._transferSize;
    }, set cached(x) {
        this._cached = x;
        if (x)
            delete this._timing;
    }, get timing() {
        return this._timing;
    }, set timing(x) {
        if (x && !this._cached) {
            this._startTime = x.requestTime;
            this._responseReceivedTime = x.requestTime + x.receiveHeadersEnd / 1000.0;
            this._timing = x;
            this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.TimingChanged, this);
        }
    }, get mimeType() {
        return this._mimeType;
    }, set mimeType(x) {
        this._mimeType = x;
    }, get displayName() {
        return this._parsedURL.displayName;
    }, name: function () {
        if (this._name)
            return this._name;
        this._parseNameAndPathFromURL();
        return this._name;
    }, path: function () {
        if (this._path)
            return this._path;
        this._parseNameAndPathFromURL();
        return this._path;
    }, _parseNameAndPathFromURL: function () {
        if (this._parsedURL.isDataURL()) {
            this._name = this._parsedURL.dataURLDisplayName();
            this._path = "";
        } else if (this._parsedURL.isAboutBlank()) {
            this._name = this._parsedURL.url;
            this._path = "";
        } else {
            this._path = this._parsedURL.host + this._parsedURL.folderPathComponents;
            this._path = this._path.trimURL(this.target().resourceTreeModel.inspectedPageDomain());
            if (this._parsedURL.lastPathComponent || this._parsedURL.queryParams)
                this._name = this._parsedURL.lastPathComponent + (this._parsedURL.queryParams ? "?" + this._parsedURL.queryParams : ""); else if (this._parsedURL.folderPathComponents) {
                this._name = this._parsedURL.folderPathComponents.substring(this._parsedURL.folderPathComponents.lastIndexOf("/") + 1) + "/";
                this._path = this._path.substring(0, this._path.lastIndexOf("/"));
            } else {
                this._name = this._parsedURL.host;
                this._path = "";
            }
        }
    }, get folder() {
        var path = this._parsedURL.path;
        var indexOfQuery = path.indexOf("?");
        if (indexOfQuery !== -1)
            path = path.substring(0, indexOfQuery);
        var lastSlashIndex = path.lastIndexOf("/");
        return lastSlashIndex !== -1 ? path.substring(0, lastSlashIndex) : "";
    }, get type() {
        return this._type;
    }, set type(x) {
        this._type = x;
    }, get domain() {
        return this._parsedURL.host;
    }, get scheme() {
        return this._parsedURL.scheme;
    }, get redirectSource() {
        if (this.redirects && this.redirects.length > 0)
            return this.redirects[this.redirects.length - 1];
        return this._redirectSource;
    }, set redirectSource(x) {
        this._redirectSource = x;
        delete this._initiatorInfo;
    }, requestHeaders: function () {
        return this._requestHeaders || [];
    }, setRequestHeaders: function (headers) {
        this._requestHeaders = headers;
        delete this._requestCookies;
        this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.RequestHeadersChanged);
    }, requestHeadersText: function () {
        return this._requestHeadersText;
    }, setRequestHeadersText: function (text) {
        this._requestHeadersText = text;
        this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.RequestHeadersChanged);
    }, requestHeaderValue: function (headerName) {
        return this._headerValue(this.requestHeaders(), headerName);
    }, get requestCookies() {
        if (!this._requestCookies)
            this._requestCookies = WebInspector.CookieParser.parseCookie(this.requestHeaderValue("Cookie"));
        return this._requestCookies;
    }, get requestFormData() {
        return this._requestFormData;
    }, set requestFormData(x) {
        this._requestFormData = x;
        delete this._parsedFormParameters;
    }, requestHttpVersion: function () {
        var headersText = this.requestHeadersText();
        if (!headersText)
            return this.requestHeaderValue("version") || this.requestHeaderValue(":version") || "unknown";
        var firstLine = headersText.split(/\r\n/)[0];
        var match = firstLine.match(/(HTTP\/\d+\.\d+)$/);
        return match ? match[1] : "HTTP/0.9";
    }, get responseHeaders() {
        return this._responseHeaders || [];
    }, set responseHeaders(x) {
        this._responseHeaders = x;
        delete this._sortedResponseHeaders;
        delete this._responseCookies;
        this._responseHeaderValues = {};
        this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.ResponseHeadersChanged);
    }, get responseHeadersText() {
        return this._responseHeadersText;
    }, set responseHeadersText(x) {
        this._responseHeadersText = x;
        this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.ResponseHeadersChanged);
    }, get sortedResponseHeaders() {
        if (this._sortedResponseHeaders !== undefined)
            return this._sortedResponseHeaders;
        this._sortedResponseHeaders = this.responseHeaders.slice();
        this._sortedResponseHeaders.sort(function (a, b) {
            return a.name.toLowerCase().compareTo(b.name.toLowerCase());
        });
        return this._sortedResponseHeaders;
    }, responseHeaderValue: function (headerName) {
        var value = this._responseHeaderValues[headerName];
        if (value === undefined) {
            value = this._headerValue(this.responseHeaders, headerName);
            this._responseHeaderValues[headerName] = (value !== undefined) ? value : null;
        }
        return (value !== null) ? value : undefined;
    }, get responseCookies() {
        if (!this._responseCookies)
            this._responseCookies = WebInspector.CookieParser.parseSetCookie(this.responseHeaderValue("Set-Cookie"));
        return this._responseCookies;
    }, queryString: function () {
        if (this._queryString !== undefined)
            return this._queryString;
        var queryString = null;
        var url = this.url;
        var questionMarkPosition = url.indexOf("?");
        if (questionMarkPosition !== -1) {
            queryString = url.substring(questionMarkPosition + 1);
            var hashSignPosition = queryString.indexOf("#");
            if (hashSignPosition !== -1)
                queryString = queryString.substring(0, hashSignPosition);
        }
        this._queryString = queryString;
        return this._queryString;
    }, get queryParameters() {
        if (this._parsedQueryParameters)
            return this._parsedQueryParameters;
        var queryString = this.queryString();
        if (!queryString)
            return null;
        this._parsedQueryParameters = this._parseParameters(queryString);
        return this._parsedQueryParameters;
    }, get formParameters() {
        if (this._parsedFormParameters)
            return this._parsedFormParameters;
        if (!this.requestFormData)
            return null;
        var requestContentType = this.requestContentType();
        if (!requestContentType || !requestContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i))
            return null;
        this._parsedFormParameters = this._parseParameters(this.requestFormData);
        return this._parsedFormParameters;
    }, responseHttpVersion: function () {
        var headersText = this._responseHeadersText;
        if (!headersText)
            return this.responseHeaderValue("version") || this.responseHeaderValue(":version") || "unknown";
        var firstLine = headersText.split(/\r\n/)[0];
        var match = firstLine.match(/^(HTTP\/\d+\.\d+)/);
        return match ? match[1] : "HTTP/0.9";
    }, _parseParameters: function (queryString) {
        function parseNameValue(pair) {
            var position = pair.indexOf("=");
            if (position === -1)
                return {name: pair, value: ""}; else
                return {name: pair.substring(0, position), value: pair.substring(position + 1)};
        }

        return queryString.split("&").map(parseNameValue);
    }, _headerValue: function (headers, headerName) {
        headerName = headerName.toLowerCase();
        var values = [];
        for (var i = 0; i < headers.length; ++i) {
            if (headers[i].name.toLowerCase() === headerName)
                values.push(headers[i].value);
        }
        if (!values.length)
            return undefined;
        if (headerName === "set-cookie")
            return values.join("\n");
        return values.join(", ");
    }, get content() {
        return this._content;
    }, contentError: function () {
        return this._contentError;
    }, get contentEncoded() {
        return this._contentEncoded;
    }, contentURL: function () {
        return this._url;
    }, contentType: function () {
        return this._type;
    }, requestContent: function (callback) {
        if (this.type === WebInspector.resourceTypes.WebSocket) {
            callback(null);
            return;
        }
        if (typeof this._content !== "undefined") {
            callback(this.content || null);
            return;
        }
        this._pendingContentCallbacks.push(callback);
        if (this.finished)
            this._innerRequestContent();
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        callback([]);
    }, isHttpFamily: function () {
        return !!this.url.match(/^https?:/i);
    }, requestContentType: function () {
        return this.requestHeaderValue("Content-Type");
    }, isPingRequest: function () {
        return "text/ping" === this.requestContentType();
    }, hasErrorStatusCode: function () {
        return this.statusCode >= 400;
    }, populateImageSource: function (image) {
        function onResourceContent(content) {
            var imageSrc = this.asDataURL();
            if (imageSrc === null)
                imageSrc = this.url;
            image.src = imageSrc;
        }

        this.requestContent(onResourceContent.bind(this));
    }, asDataURL: function () {
        return WebInspector.Resource.contentAsDataURL(this._content, this.mimeType, this._contentEncoded);
    }, _innerRequestContent: function () {
        if (this._contentRequested)
            return;
        this._contentRequested = true;
        function onResourceContent(error, content, contentEncoded) {
            this._content = error ? null : content;
            this._contentError = error;
            this._contentEncoded = contentEncoded;
            var callbacks = this._pendingContentCallbacks.slice();
            for (var i = 0; i < callbacks.length; ++i)
                callbacks[i](this._content);
            this._pendingContentCallbacks.length = 0;
            delete this._contentRequested;
        }

        NetworkAgent.getResponseBody(this._requestId, onResourceContent.bind(this));
    }, initiatorInfo: function () {
        if (this._initiatorInfo)
            return this._initiatorInfo;
        var type = WebInspector.NetworkRequest.InitiatorType.Other;
        var url = "";
        var lineNumber = -Infinity;
        var columnNumber = -Infinity;
        if (this.redirectSource) {
            type = WebInspector.NetworkRequest.InitiatorType.Redirect;
            url = this.redirectSource.url;
        } else if (this.initiator) {
            if (this.initiator.type === NetworkAgent.InitiatorType.Parser) {
                type = WebInspector.NetworkRequest.InitiatorType.Parser;
                url = this.initiator.url;
                lineNumber = this.initiator.lineNumber;
            } else if (this.initiator.type === NetworkAgent.InitiatorType.Script) {
                var topFrame = this.initiator.stackTrace[0];
                if (topFrame.url) {
                    type = WebInspector.NetworkRequest.InitiatorType.Script;
                    url = topFrame.url;
                    lineNumber = topFrame.lineNumber;
                    columnNumber = topFrame.columnNumber;
                }
            }
        }
        this._initiatorInfo = {type: type, url: url, lineNumber: lineNumber, columnNumber: columnNumber};
        return this._initiatorInfo;
    }, frames: function () {
        return this._frames;
    }, addFrameError: function (errorMessage, time) {
        this._frames.push({type: WebInspector.NetworkRequest.WebSocketFrameType.Error, text: errorMessage, time: time, opCode: -1, mask: false});
    }, addFrame: function (response, time, sent) {
        var type = sent ? WebInspector.NetworkRequest.WebSocketFrameType.Send : WebInspector.NetworkRequest.WebSocketFrameType.Receive;
        this._frames.push({type: type, text: response.payloadData, time: time, opCode: response.opcode, mask: response.mask});
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.UISourceCode = function (project, parentPath, name, originURL, url, contentType) {
    this._project = project;
    this._parentPath = parentPath;
    this._name = name;
    this._originURL = originURL;
    this._url = url;
    this._contentType = contentType;
    this._requestContentCallbacks = [];
    this._consoleMessages = [];
    this.history = [];
}
WebInspector.UISourceCode.Events = {
    WorkingCopyChanged: "WorkingCopyChanged",
    WorkingCopyCommitted: "WorkingCopyCommitted",
    TitleChanged: "TitleChanged",
    SavedStateUpdated: "SavedStateUpdated",
    ConsoleMessageAdded: "ConsoleMessageAdded",
    ConsoleMessageRemoved: "ConsoleMessageRemoved",
    ConsoleMessagesCleared: "ConsoleMessagesCleared",
    SourceMappingChanged: "SourceMappingChanged",
}
WebInspector.UISourceCode.prototype = {
    get url() {
        return this._url;
    }, name: function () {
        return this._name;
    }, parentPath: function () {
        return this._parentPath;
    }, path: function () {
        return this._parentPath ? this._parentPath + "/" + this._name : this._name;
    }, fullDisplayName: function () {
        return this._project.displayName() + "/" + (this._parentPath ? this._parentPath + "/" : "") + this.displayName(true);
    }, displayName: function (skipTrim) {
        var displayName = this.name() || WebInspector.UIString("(index)");
        return skipTrim ? displayName : displayName.trimEnd(100);
    }, uri: function () {
        var path = this.path();
        if (!this._project.id())
            return path;
        if (!path)
            return this._project.id();
        return this._project.id() + "/" + path;
    }, originURL: function () {
        return this._originURL;
    }, canRename: function () {
        return this._project.canRename();
    }, rename: function (newName, callback) {
        this._project.rename(this, newName, innerCallback.bind(this));
        function innerCallback(success, newName, newURL, newOriginURL, newContentType) {
            if (success)
                this._updateName((newName), (newURL), (newOriginURL), (newContentType));
            callback(success);
        }
    }, remove: function () {
        this._project.deleteFile(this.path());
    }, _updateName: function (name, url, originURL, contentType) {
        var oldURI = this.uri();
        this._name = name;
        if (url)
            this._url = url;
        if (originURL)
            this._originURL = originURL;
        if (contentType)
            this._contentType = contentType;
        this.dispatchEventToListeners(WebInspector.UISourceCode.Events.TitleChanged, oldURI);
    }, contentURL: function () {
        return this.originURL();
    }, contentType: function () {
        return this._contentType;
    }, project: function () {
        return this._project;
    }, requestMetadata: function (callback) {
        this._project.requestMetadata(this, callback);
    }, requestContent: function (callback) {
        if (this._content || this._contentLoaded) {
            callback(this._content);
            return;
        }
        this._requestContentCallbacks.push(callback);
        if (this._requestContentCallbacks.length === 1)
            this._project.requestFileContent(this, this._fireContentAvailable.bind(this));
    }, _pushCheckContentUpdatedCallback: function (callback) {
        if (!this._checkContentUpdatedCallbacks)
            this._checkContentUpdatedCallbacks = [];
        this._checkContentUpdatedCallbacks.push(callback);
    }, _terminateContentCheck: function () {
        delete this._checkingContent;
        if (this._checkContentUpdatedCallbacks) {
            this._checkContentUpdatedCallbacks.forEach(function (callback) {
                callback();
            });
            delete this._checkContentUpdatedCallbacks;
        }
    }, checkContentUpdated: function (callback) {
        callback = callback || function () {
        };
        if (!this._project.canSetFileContent()) {
            callback();
            return;
        }
        this._pushCheckContentUpdatedCallback(callback);
        if (this._checkingContent) {
            return;
        }
        this._checkingContent = true;
        this._project.requestFileContent(this, contentLoaded.bind(this));
        function contentLoaded(updatedContent) {
            if (updatedContent === null) {
                var workingCopy = this.workingCopy();
                this._commitContent("", false);
                this.setWorkingCopy(workingCopy);
                this._terminateContentCheck();
                return;
            }
            if (typeof this._lastAcceptedContent === "string" && this._lastAcceptedContent === updatedContent) {
                this._terminateContentCheck();
                return;
            }
            if (this._content === updatedContent) {
                delete this._lastAcceptedContent;
                this._terminateContentCheck();
                return;
            }
            if (!this.isDirty()) {
                this._commitContent(updatedContent, false);
                this._terminateContentCheck();
                return;
            }
            var shouldUpdate = window.confirm(WebInspector.UIString("This file was changed externally. Would you like to reload it?"));
            if (shouldUpdate)
                this._commitContent(updatedContent, false); else
                this._lastAcceptedContent = updatedContent;
            this._terminateContentCheck();
        }
    }, requestOriginalContent: function (callback) {
        this._project.requestFileContent(this, callback);
    }, _commitContent: function (content, shouldSetContentInProject) {
        delete this._lastAcceptedContent;
        this._content = content;
        this._contentLoaded = true;
        var lastRevision = this.history.length ? this.history[this.history.length - 1] : null;
        if (!lastRevision || lastRevision._content !== this._content) {
            var revision = new WebInspector.Revision(this, this._content, new Date());
            this.history.push(revision);
        }
        this._innerResetWorkingCopy();
        this._hasCommittedChanges = true;
        this.dispatchEventToListeners(WebInspector.UISourceCode.Events.WorkingCopyCommitted);
        if (this._url && WebInspector.fileManager.isURLSaved(this._url))
            this._saveURLWithFileManager(false, this._content);
        if (shouldSetContentInProject)
            this._project.setFileContent(this, this._content, function () {
            });
    }, _saveURLWithFileManager: function (forceSaveAs, content) {
        WebInspector.fileManager.save(this._url, (content), forceSaveAs, callback.bind(this));
        WebInspector.fileManager.close(this._url);
        function callback(accepted) {
            if (!accepted)
                return;
            this._savedWithFileManager = true;
            this.dispatchEventToListeners(WebInspector.UISourceCode.Events.SavedStateUpdated);
        }
    }, save: function (forceSaveAs) {
        if (this.project().type() === WebInspector.projectTypes.FileSystem || this.project().type() === WebInspector.projectTypes.Snippets) {
            this.commitWorkingCopy();
            return;
        }
        if (this.isDirty()) {
            this._saveURLWithFileManager(forceSaveAs, this.workingCopy());
            this.commitWorkingCopy();
            return;
        }
        this.requestContent(this._saveURLWithFileManager.bind(this, forceSaveAs));
    }, hasUnsavedCommittedChanges: function () {
        if (this._savedWithFileManager || this.project().canSetFileContent() || this._project.isServiceProject())
            return false;
        if (this._project.workspace().hasResourceContentTrackingExtensions())
            return false;
        return !!this._hasCommittedChanges;
    }, addRevision: function (content) {
        this._commitContent(content, true);
    }, revertToOriginal: function () {
        function callback(content) {
            if (typeof content !== "string")
                return;
            this.addRevision(content);
        }

        this.requestOriginalContent(callback.bind(this));
    }, revertAndClearHistory: function (callback) {
        function revert(content) {
            if (typeof content !== "string")
                return;
            this.addRevision(content);
            this.history = [];
            callback(this);
        }

        this.requestOriginalContent(revert.bind(this));
    }, workingCopy: function () {
        if (this._workingCopyGetter) {
            this._workingCopy = this._workingCopyGetter();
            delete this._workingCopyGetter;
        }
        if (this.isDirty())
            return this._workingCopy;
        return this._content;
    }, resetWorkingCopy: function () {
        this._innerResetWorkingCopy();
        this.dispatchEventToListeners(WebInspector.UISourceCode.Events.WorkingCopyChanged);
    }, _innerResetWorkingCopy: function () {
        delete this._workingCopy;
        delete this._workingCopyGetter;
    }, setWorkingCopy: function (newWorkingCopy) {
        this._workingCopy = newWorkingCopy;
        delete this._workingCopyGetter;
        this.dispatchEventToListeners(WebInspector.UISourceCode.Events.WorkingCopyChanged);
    }, setWorkingCopyGetter: function (workingCopyGetter) {
        this._workingCopyGetter = workingCopyGetter;
        this.dispatchEventToListeners(WebInspector.UISourceCode.Events.WorkingCopyChanged);
    }, removeWorkingCopyGetter: function () {
        if (!this._workingCopyGetter)
            return;
        this._workingCopy = this._workingCopyGetter();
        delete this._workingCopyGetter;
    }, commitWorkingCopy: function () {
        if (this.isDirty())
            this._commitContent(this.workingCopy(), true);
    }, isDirty: function () {
        return typeof this._workingCopy !== "undefined" || typeof this._workingCopyGetter !== "undefined";
    }, highlighterType: function () {
        var lastIndexOfDot = this._name.lastIndexOf(".");
        var extension = lastIndexOfDot !== -1 ? this._name.substr(lastIndexOfDot + 1) : "";
        var indexOfQuestionMark = extension.indexOf("?");
        if (indexOfQuestionMark !== -1)
            extension = extension.substr(0, indexOfQuestionMark);
        var mimeType = WebInspector.ResourceType.mimeTypesForExtensions[extension.toLowerCase()];
        return mimeType || this.contentType().canonicalMimeType();
    }, content: function () {
        return this._content;
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        var content = this.content();
        if (content) {
            var provider = new WebInspector.StaticContentProvider(this.contentType(), content);
            provider.searchInContent(query, caseSensitive, isRegex, callback);
            return;
        }
        this._project.searchInFileContent(this, query, caseSensitive, isRegex, callback);
    }, _fireContentAvailable: function (content) {
        this._contentLoaded = true;
        this._content = content;
        var callbacks = this._requestContentCallbacks.slice();
        this._requestContentCallbacks = [];
        for (var i = 0; i < callbacks.length; ++i)
            callbacks[i](content);
    }, contentLoaded: function () {
        return this._contentLoaded;
    }, consoleMessages: function () {
        return this._consoleMessages;
    }, consoleMessageAdded: function (message) {
        this._consoleMessages.push(message);
        this.dispatchEventToListeners(WebInspector.UISourceCode.Events.ConsoleMessageAdded, message);
    }, consoleMessageRemoved: function (message) {
        this._consoleMessages.remove(message);
        this.dispatchEventToListeners(WebInspector.UISourceCode.Events.ConsoleMessageRemoved, message);
    }, consoleMessagesCleared: function () {
        this._consoleMessages = [];
        this.dispatchEventToListeners(WebInspector.UISourceCode.Events.ConsoleMessagesCleared);
    }, uiLocation: function (lineNumber, columnNumber) {
        if (typeof columnNumber === "undefined")
            columnNumber = 0;
        return new WebInspector.UILocation(this, lineNumber, columnNumber);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.PresentationMessage = function () {
}
WebInspector.UILocation = function (uiSourceCode, lineNumber, columnNumber) {
    this.uiSourceCode = uiSourceCode;
    this.lineNumber = lineNumber;
    this.columnNumber = columnNumber;
}
WebInspector.UILocation.prototype = {
    linkText: function () {
        var linkText = this.uiSourceCode.displayName();
        if (typeof this.lineNumber === "number")
            linkText += ":" + (this.lineNumber + 1);
        return linkText;
    }, id: function () {
        return this.uiSourceCode.uri() + ":" + this.lineNumber + ":" + this.columnNumber;
    },
}
WebInspector.Revision = function (uiSourceCode, content, timestamp) {
    this._uiSourceCode = uiSourceCode;
    this._content = content;
    this._timestamp = timestamp;
}
WebInspector.Revision.prototype = {
    get uiSourceCode() {
        return this._uiSourceCode;
    }, get timestamp() {
        return this._timestamp;
    }, get content() {
        return this._content || null;
    }, revertToThis: function () {
        function revert(content) {
            if (this._uiSourceCode._content !== content)
                this._uiSourceCode.addRevision(content);
        }

        this.requestContent(revert.bind(this));
    }, contentURL: function () {
        return this._uiSourceCode.originURL();
    }, contentType: function () {
        return this._uiSourceCode.contentType();
    }, requestContent: function (callback) {
        callback(this._content || "");
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        callback([]);
    }
}
WebInspector.CSSStyleModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.CSSStyleModel, target);
    this._domModel = target.domModel;
    this._agent = target.cssAgent();
    this._pendingCommandsMajorState = [];
    this._styleLoader = new WebInspector.CSSStyleModel.ComputedStyleLoader(this);
    this._domModel.addEventListener(WebInspector.DOMModel.Events.UndoRedoRequested, this._undoRedoRequested, this);
    this._domModel.addEventListener(WebInspector.DOMModel.Events.UndoRedoCompleted, this._undoRedoCompleted, this);
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this);
    target.registerCSSDispatcher(new WebInspector.CSSDispatcher(this));
    this._agent.enable(this._wasEnabled.bind(this));
    this._styleSheetIdToHeader = new StringMap();
    this._styleSheetIdsForURL = new StringMap();
    if (WebInspector.experimentsSettings.disableAgentsWhenProfile.isEnabled())
        WebInspector.profilingLock().addEventListener(WebInspector.Lock.Events.StateChanged, this._profilingStateChanged, this);
}
WebInspector.CSSStyleModel.PseudoStatePropertyName = "pseudoState";
WebInspector.CSSStyleModel.parseRuleMatchArrayPayload = function (cssModel, matchArray) {
    if (!matchArray)
        return [];
    var result = [];
    for (var i = 0; i < matchArray.length; ++i)
        result.push(WebInspector.CSSRule.parsePayload(cssModel, matchArray[i].rule, matchArray[i].matchingSelectors));
    return result;
}
WebInspector.CSSStyleModel.Events = {
    ModelWasEnabled: "ModelWasEnabled",
    StyleSheetAdded: "StyleSheetAdded",
    StyleSheetChanged: "StyleSheetChanged",
    StyleSheetRemoved: "StyleSheetRemoved",
    MediaQueryResultChanged: "MediaQueryResultChanged",
}
WebInspector.CSSStyleModel.MediaTypes = ["all", "braille", "embossed", "handheld", "print", "projection", "screen", "speech", "tty", "tv"];
WebInspector.CSSStyleModel.prototype = {
    _profilingStateChanged: function () {
        if (WebInspector.profilingLock().isAcquired()) {
            this._agent.disable();
            this._isEnabled = false;
            this._resetStyleSheets();
        } else {
            this._agent.enable(this._wasEnabled.bind(this));
        }
    }, getMediaQueries: function (userCallback) {
        function callback(error, payload) {
            var models = [];
            if (!error && payload)
                models = WebInspector.CSSMedia.parseMediaArrayPayload(this, payload);
            userCallback(models);
        }

        this._agent.getMediaQueries(callback.bind(this));
    }, isEnabled: function () {
        return this._isEnabled;
    }, _wasEnabled: function () {
        this._isEnabled = true;
        this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.ModelWasEnabled);
    }, getMatchedStylesAsync: function (nodeId, excludePseudo, excludeInherited, userCallback) {
        function callback(userCallback, error, matchedPayload, pseudoPayload, inheritedPayload) {
            if (error) {
                if (userCallback)
                    userCallback(null);
                return;
            }
            var result = {};
            result.matchedCSSRules = WebInspector.CSSStyleModel.parseRuleMatchArrayPayload(this, matchedPayload);
            result.pseudoElements = [];
            if (pseudoPayload) {
                for (var i = 0; i < pseudoPayload.length; ++i) {
                    var entryPayload = pseudoPayload[i];
                    result.pseudoElements.push({pseudoId: entryPayload.pseudoId, rules: WebInspector.CSSStyleModel.parseRuleMatchArrayPayload(this, entryPayload.matches)});
                }
            }
            result.inherited = [];
            if (inheritedPayload) {
                for (var i = 0; i < inheritedPayload.length; ++i) {
                    var entryPayload = inheritedPayload[i];
                    var entry = {};
                    if (entryPayload.inlineStyle)
                        entry.inlineStyle = WebInspector.CSSStyleDeclaration.parsePayload(this, entryPayload.inlineStyle);
                    if (entryPayload.matchedCSSRules)
                        entry.matchedCSSRules = WebInspector.CSSStyleModel.parseRuleMatchArrayPayload(this, entryPayload.matchedCSSRules);
                    result.inherited.push(entry);
                }
            }
            if (userCallback)
                userCallback(result);
        }

        this._agent.getMatchedStylesForNode(nodeId, excludePseudo, excludeInherited, callback.bind(this, userCallback));
    }, getComputedStyleAsync: function (nodeId, userCallback) {
        this._styleLoader.getComputedStyle(nodeId, userCallback);
    }, getPlatformFontsForNode: function (nodeId, callback) {
        function platformFontsCallback(error, cssFamilyName, fonts) {
            if (error)
                callback(null, null); else
                callback(cssFamilyName, fonts);
        }

        this._agent.getPlatformFontsForNode(nodeId, platformFontsCallback);
    }, allStyleSheets: function () {
        var values = this._styleSheetIdToHeader.values();

        function styleSheetComparator(a, b) {
            if (a.sourceURL < b.sourceURL)
                return -1; else if (a.sourceURL > b.sourceURL)
                return 1;
            return a.startLine - b.startLine || a.startColumn - b.startColumn;
        }

        values.sort(styleSheetComparator);
        return values;
    }, getInlineStylesAsync: function (nodeId, userCallback) {
        function callback(userCallback, error, inlinePayload, attributesStylePayload) {
            if (error || !inlinePayload)
                userCallback(null, null); else
                userCallback(WebInspector.CSSStyleDeclaration.parsePayload(this, inlinePayload), attributesStylePayload ? WebInspector.CSSStyleDeclaration.parsePayload(this, attributesStylePayload) : null);
        }

        this._agent.getInlineStylesForNode(nodeId, callback.bind(this, userCallback));
    }, forcePseudoState: function (node, pseudoClass, enable) {
        var pseudoClasses = node.getUserProperty(WebInspector.CSSStyleModel.PseudoStatePropertyName) || [];
        if (enable) {
            if (pseudoClasses.indexOf(pseudoClass) >= 0)
                return false;
            pseudoClasses.push(pseudoClass);
            node.setUserProperty(WebInspector.CSSStyleModel.PseudoStatePropertyName, pseudoClasses);
        } else {
            if (pseudoClasses.indexOf(pseudoClass) < 0)
                return false;
            pseudoClasses.remove(pseudoClass);
            if (!pseudoClasses.length)
                node.removeUserProperty(WebInspector.CSSStyleModel.PseudoStatePropertyName);
        }
        this._agent.forcePseudoState(node.id, pseudoClasses);
        return true;
    }, setRuleSelector: function (rule, nodeId, newSelector, successCallback, failureCallback) {
        function callback(nodeId, successCallback, failureCallback, newSelector, error, rulePayload) {
            this._pendingCommandsMajorState.pop();
            if (error) {
                failureCallback();
                return;
            }
            this._domModel.markUndoableState();
            this._computeMatchingSelectors(rulePayload, nodeId, successCallback, failureCallback);
        }

        if (!rule.styleSheetId)
            throw"No rule stylesheet id";
        this._pendingCommandsMajorState.push(true);
        this._agent.setRuleSelector(rule.styleSheetId, rule.selectorRange, newSelector, callback.bind(this, nodeId, successCallback, failureCallback, newSelector));
    }, _computeMatchingSelectors: function (rulePayload, nodeId, successCallback, failureCallback) {
        var ownerDocumentId = this._ownerDocumentId(nodeId);
        if (!ownerDocumentId) {
            failureCallback();
            return;
        }
        var rule = WebInspector.CSSRule.parsePayload(this, rulePayload);
        var matchingSelectors = [];
        var allSelectorsBarrier = new CallbackBarrier();
        for (var i = 0; i < rule.selectors.length; ++i) {
            var selector = rule.selectors[i];
            var boundCallback = allSelectorsBarrier.createCallback(selectorQueried.bind(null, i, nodeId, matchingSelectors));
            this._domModel.querySelectorAll(ownerDocumentId, selector.value, boundCallback);
        }
        allSelectorsBarrier.callWhenDone(function () {
            rule.matchingSelectors = matchingSelectors;
            successCallback(rule);
        });
        function selectorQueried(index, nodeId, matchingSelectors, matchingNodeIds) {
            if (!matchingNodeIds)
                return;
            if (matchingNodeIds.indexOf(nodeId) !== -1)
                matchingSelectors.push(index);
        }
    }, addRule: function (styleSheetId, node, ruleText, ruleLocation, successCallback, failureCallback) {
        this._pendingCommandsMajorState.push(true);
        this._agent.addRule(styleSheetId, ruleText, ruleLocation, callback.bind(this));
        function callback(error, rulePayload) {
            this._pendingCommandsMajorState.pop();
            if (error) {
                failureCallback();
            } else {
                this._domModel.markUndoableState();
                this._computeMatchingSelectors(rulePayload, node.id, successCallback, failureCallback);
            }
        }
    }, requestViaInspectorStylesheet: function (node, callback) {
        var frameId = node.frameId() || this.target().resourceTreeModel.mainFrame.id;
        var headers = this._styleSheetIdToHeader.values();
        for (var i = 0; i < headers.length; ++i) {
            var styleSheetHeader = headers[i];
            if (styleSheetHeader.frameId === frameId && styleSheetHeader.isViaInspector()) {
                callback(styleSheetHeader);
                return;
            }
        }
        function innerCallback(error, styleSheetId) {
            if (error) {
                console.error(error);
                callback(null);
            }
            callback(this._styleSheetIdToHeader.get(styleSheetId) || null);
        }

        this._agent.createStyleSheet(frameId, innerCallback.bind(this));
    }, mediaQueryResultChanged: function () {
        this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.MediaQueryResultChanged);
    }, styleSheetHeaderForId: function (id) {
        return this._styleSheetIdToHeader.get(id) || null;
    }, styleSheetHeaders: function () {
        return this._styleSheetIdToHeader.values();
    }, _ownerDocumentId: function (nodeId) {
        var node = this._domModel.nodeForId(nodeId);
        if (!node)
            return null;
        return node.ownerDocument ? node.ownerDocument.id : null;
    }, _fireStyleSheetChanged: function (styleSheetId) {
        if (!this._pendingCommandsMajorState.length)
            return;
        var majorChange = this._pendingCommandsMajorState[this._pendingCommandsMajorState.length - 1];
        if (!styleSheetId || !this.hasEventListeners(WebInspector.CSSStyleModel.Events.StyleSheetChanged))
            return;
        this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.StyleSheetChanged, {styleSheetId: styleSheetId, majorChange: majorChange});
    }, _styleSheetAdded: function (header) {
        console.assert(!this._styleSheetIdToHeader.get(header.styleSheetId));
        var styleSheetHeader = new WebInspector.CSSStyleSheetHeader(this, header);
        this._styleSheetIdToHeader.put(header.styleSheetId, styleSheetHeader);
        var url = styleSheetHeader.resourceURL();
        if (!this._styleSheetIdsForURL.get(url))
            this._styleSheetIdsForURL.put(url, {});
        var frameIdToStyleSheetIds = this._styleSheetIdsForURL.get(url);
        var styleSheetIds = frameIdToStyleSheetIds[styleSheetHeader.frameId];
        if (!styleSheetIds) {
            styleSheetIds = [];
            frameIdToStyleSheetIds[styleSheetHeader.frameId] = styleSheetIds;
        }
        styleSheetIds.push(styleSheetHeader.id);
        this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.StyleSheetAdded, styleSheetHeader);
    }, _styleSheetRemoved: function (id) {
        var header = this._styleSheetIdToHeader.get(id);
        console.assert(header);
        if (!header)
            return;
        this._styleSheetIdToHeader.remove(id);
        var url = header.resourceURL();
        var frameIdToStyleSheetIds = (this._styleSheetIdsForURL.get(url));
        console.assert(frameIdToStyleSheetIds, "No frameId to styleSheetId map is available for given style sheet URL.");
        frameIdToStyleSheetIds[header.frameId].remove(id);
        if (!frameIdToStyleSheetIds[header.frameId].length) {
            delete frameIdToStyleSheetIds[header.frameId];
            if (!Object.keys(frameIdToStyleSheetIds).length)
                this._styleSheetIdsForURL.remove(url);
        }
        this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, header);
    }, styleSheetIdsForURL: function (url) {
        var frameIdToStyleSheetIds = this._styleSheetIdsForURL.get(url);
        if (!frameIdToStyleSheetIds)
            return [];
        var result = [];
        for (var frameId in frameIdToStyleSheetIds)
            result = result.concat(frameIdToStyleSheetIds[frameId]);
        return result;
    }, styleSheetIdsByFrameIdForURL: function (url) {
        var styleSheetIdsForFrame = this._styleSheetIdsForURL.get(url);
        if (!styleSheetIdsForFrame)
            return {};
        return styleSheetIdsForFrame;
    }, setStyleSheetText: function (styleSheetId, newText, majorChange, userCallback) {
        var header = this._styleSheetIdToHeader.get(styleSheetId);
        console.assert(header);
        this._pendingCommandsMajorState.push(majorChange);
        header.setContent(newText, callback.bind(this));
        function callback(error) {
            this._pendingCommandsMajorState.pop();
            if (!error && majorChange)
                this._domModel.markUndoableState();
            if (!error && userCallback)
                userCallback(error);
        }
    }, _undoRedoRequested: function () {
        this._pendingCommandsMajorState.push(true);
    }, _undoRedoCompleted: function () {
        this._pendingCommandsMajorState.pop();
    }, _mainFrameNavigated: function () {
        this._resetStyleSheets();
    }, _resetStyleSheets: function () {
        var headers = this._styleSheetIdToHeader.values();
        this._styleSheetIdsForURL.clear();
        this._styleSheetIdToHeader.clear();
        for (var i = 0; i < headers.length; ++i)
            this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, headers[i]);
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.CSSLocation = function (target, styleSheetId, url, lineNumber, columnNumber) {
    WebInspector.SDKObject.call(this, target);
    this.styleSheetId = styleSheetId;
    this.url = url;
    this.lineNumber = lineNumber;
    this.columnNumber = columnNumber || 0;
}
WebInspector.CSSLocation.prototype = {__proto__: WebInspector.SDKObject.prototype}
WebInspector.CSSStyleDeclaration = function (cssModel, payload) {
    this._cssModel = cssModel;
    this.styleSheetId = payload.styleSheetId;
    this.range = payload.range ? WebInspector.TextRange.fromObject(payload.range) : null;
    this._shorthandValues = WebInspector.CSSStyleDeclaration.buildShorthandValueMap(payload.shorthandEntries);
    this._livePropertyMap = {};
    this._allProperties = [];
    this.__disabledProperties = {};
    var payloadPropertyCount = payload.cssProperties.length;
    for (var i = 0; i < payloadPropertyCount; ++i) {
        var property = WebInspector.CSSProperty.parsePayload(this, i, payload.cssProperties[i]);
        this._allProperties.push(property);
    }
    this._computeActiveProperties();
    var propertyIndex = 0;
    for (var i = 0; i < this._allProperties.length; ++i) {
        var property = this._allProperties[i];
        if (property.disabled)
            this.__disabledProperties[i] = property;
        if (!property.active && !property.styleBased)
            continue;
        var name = property.name;
        this[propertyIndex] = name;
        this._livePropertyMap[name] = property;
        ++propertyIndex;
    }
    this.length = propertyIndex;
    if ("cssText"in payload)
        this.cssText = payload.cssText;
}
WebInspector.CSSStyleDeclaration.buildShorthandValueMap = function (shorthandEntries) {
    var result = {};
    for (var i = 0; i < shorthandEntries.length; ++i)
        result[shorthandEntries[i].name] = shorthandEntries[i].value;
    return result;
}
WebInspector.CSSStyleDeclaration.parsePayload = function (cssModel, payload) {
    return new WebInspector.CSSStyleDeclaration(cssModel, payload);
}
WebInspector.CSSStyleDeclaration.parseComputedStylePayload = function (cssModel, payload) {
    var newPayload = ({cssProperties: [], shorthandEntries: [], width: "", height: ""});
    if (payload)
        newPayload.cssProperties = (payload);
    return new WebInspector.CSSStyleDeclaration(cssModel, newPayload);
}
WebInspector.CSSStyleDeclaration.prototype = {
    target: function () {
        return this._cssModel.target();
    }, sourceStyleSheetEdited: function (styleSheetId, oldRange, newRange) {
        if (this.styleSheetId !== styleSheetId)
            return;
        if (this.range)
            this.range = this.range.rebaseAfterTextEdit(oldRange, newRange);
        for (var i = 0; i < this._allProperties.length; ++i)
            this._allProperties[i].sourceStyleSheetEdited(styleSheetId, oldRange, newRange);
    }, _computeActiveProperties: function () {
        var activeProperties = {};
        for (var i = this._allProperties.length - 1; i >= 0; --i) {
            var property = this._allProperties[i];
            if (property.styleBased || property.disabled)
                continue;
            property._setActive(false);
            if (!property.parsedOk)
                continue;
            var canonicalName = WebInspector.CSSMetadata.canonicalPropertyName(property.name);
            var activeProperty = activeProperties[canonicalName];
            if (!activeProperty || (!activeProperty.important && property.important))
                activeProperties[canonicalName] = property;
        }
        for (var propertyName in activeProperties) {
            var property = activeProperties[propertyName];
            property._setActive(true);
        }
    }, get allProperties() {
        return this._allProperties;
    }, getLiveProperty: function (name) {
        return this._livePropertyMap[name] || null;
    }, getPropertyValue: function (name) {
        var property = this._livePropertyMap[name];
        return property ? property.value : "";
    }, isPropertyImplicit: function (name) {
        var property = this._livePropertyMap[name];
        return property ? property.implicit : "";
    }, longhandProperties: function (name) {
        var longhands = WebInspector.CSSMetadata.cssPropertiesMetainfo.longhands(name);
        var result = [];
        for (var i = 0; longhands && i < longhands.length; ++i) {
            var property = this._livePropertyMap[longhands[i]];
            if (property)
                result.push(property);
        }
        return result;
    }, shorthandValue: function (shorthandProperty) {
        return this._shorthandValues[shorthandProperty];
    }, propertyAt: function (index) {
        return (index < this.allProperties.length) ? this.allProperties[index] : null;
    }, pastLastSourcePropertyIndex: function () {
        for (var i = this.allProperties.length - 1; i >= 0; --i) {
            if (this.allProperties[i].range)
                return i + 1;
        }
        return 0;
    }, _insertionRange: function (index) {
        var property = this.propertyAt(index);
        return property && property.range ? property.range.collapseToStart() : this.range.collapseToEnd();
    }, newBlankProperty: function (index) {
        index = (typeof index === "undefined") ? this.pastLastSourcePropertyIndex() : index;
        var property = new WebInspector.CSSProperty(this, index, "", "", false, false, true, false, "", this._insertionRange(index));
        property._setActive(true);
        return property;
    }, insertPropertyAt: function (index, name, value, userCallback) {
        function callback(error, payload) {
            this._cssModel._pendingCommandsMajorState.pop();
            if (!userCallback)
                return;
            if (error) {
                console.error(error);
                userCallback(null);
            } else
                userCallback(WebInspector.CSSStyleDeclaration.parsePayload(this._cssModel, payload));
        }

        if (!this.styleSheetId)
            throw"No stylesheet id";
        this._cssModel._pendingCommandsMajorState.push(true);
        this._cssModel._agent.setPropertyText(this.styleSheetId, this._insertionRange(index), name + ": " + value + ";", callback.bind(this));
    }, appendProperty: function (name, value, userCallback) {
        this.insertPropertyAt(this.allProperties.length, name, value, userCallback);
    }
}
WebInspector.CSSRuleSelector = function (payload) {
    this.value = payload.value;
    if (payload.range)
        this.range = WebInspector.TextRange.fromObject(payload.range);
}
WebInspector.CSSRuleSelector.parsePayload = function (payload) {
    return new WebInspector.CSSRuleSelector(payload)
}
WebInspector.CSSRuleSelector.prototype = {
    sourceStyleRuleEdited: function (oldRange, newRange) {
        if (!this.range)
            return;
        this.range = this.range.rebaseAfterTextEdit(oldRange, newRange);
    }
}
WebInspector.CSSRule = function (cssModel, payload, matchingSelectors) {
    this._cssModel = cssModel;
    this.styleSheetId = payload.styleSheetId;
    if (matchingSelectors)
        this.matchingSelectors = matchingSelectors;
    this.selectors = [];
    for (var i = 0; i < payload.selectorList.selectors.length; ++i) {
        var selectorPayload = payload.selectorList.selectors[i];
        this.selectors.push(WebInspector.CSSRuleSelector.parsePayload(selectorPayload));
    }
    this.selectorText = this.selectors.select("value").join(", ");
    var firstRange = this.selectors[0].range;
    if (firstRange) {
        var lastRange = this.selectors.peekLast().range;
        this.selectorRange = new WebInspector.TextRange(firstRange.startLine, firstRange.startColumn, lastRange.endLine, lastRange.endColumn);
    }
    if (this.styleSheetId) {
        var styleSheetHeader = cssModel.styleSheetHeaderForId(this.styleSheetId);
        this.sourceURL = styleSheetHeader.sourceURL;
    }
    this.origin = payload.origin;
    this.style = WebInspector.CSSStyleDeclaration.parsePayload(this._cssModel, payload.style);
    this.style.parentRule = this;
    if (payload.media)
        this.media = WebInspector.CSSMedia.parseMediaArrayPayload(cssModel, payload.media);
    this._setFrameId();
}
WebInspector.CSSRule.parsePayload = function (cssModel, payload, matchingIndices) {
    return new WebInspector.CSSRule(cssModel, payload, matchingIndices);
}
WebInspector.CSSRule.prototype = {
    sourceStyleSheetEdited: function (styleSheetId, oldRange, newRange) {
        if (this.styleSheetId === styleSheetId) {
            if (this.selectorRange)
                this.selectorRange = this.selectorRange.rebaseAfterTextEdit(oldRange, newRange);
            for (var i = 0; i < this.selectors.length; ++i)
                this.selectors[i].sourceStyleRuleEdited(oldRange, newRange);
        }
        if (this.media) {
            for (var i = 0; i < this.media.length; ++i)
                this.media[i].sourceStyleSheetEdited(styleSheetId, oldRange, newRange);
        }
        this.style.sourceStyleSheetEdited(styleSheetId, oldRange, newRange);
    }, _setFrameId: function () {
        if (!this.styleSheetId)
            return;
        var styleSheetHeader = this._cssModel.styleSheetHeaderForId(this.styleSheetId);
        this.frameId = styleSheetHeader.frameId;
    }, resourceURL: function () {
        if (!this.styleSheetId)
            return "";
        var styleSheetHeader = this._cssModel.styleSheetHeaderForId(this.styleSheetId);
        return styleSheetHeader.resourceURL();
    }, lineNumberInSource: function (selectorIndex) {
        var selector = this.selectors[selectorIndex];
        if (!selector || !selector.range || !this.styleSheetId)
            return 0;
        var styleSheetHeader = this._cssModel.styleSheetHeaderForId(this.styleSheetId);
        return styleSheetHeader.lineNumberInSource(selector.range.startLine);
    }, columnNumberInSource: function (selectorIndex) {
        var selector = this.selectors[selectorIndex];
        if (!selector || !selector.range || !this.styleSheetId)
            return undefined;
        var styleSheetHeader = this._cssModel.styleSheetHeaderForId(this.styleSheetId);
        console.assert(styleSheetHeader);
        return styleSheetHeader.columnNumberInSource(selector.range.startLine, selector.range.startColumn);
    }, rawSelectorLocation: function (index) {
        var lineNumber = this.lineNumberInSource(index);
        var columnNumber = this.columnNumberInSource(index);
        return new WebInspector.CSSLocation(this._cssModel.target(), this.styleSheetId || null, this.resourceURL(), lineNumber, columnNumber);
    }, get isUserAgent() {
        return this.origin === "user-agent";
    }, get isUser() {
        return this.origin === "user";
    }, get isViaInspector() {
        return this.origin === "inspector";
    }, get isRegular() {
        return this.origin === "regular";
    }
}
WebInspector.CSSProperty = function (ownerStyle, index, name, value, important, disabled, parsedOk, implicit, text, range) {
    this.ownerStyle = ownerStyle;
    this.index = index;
    this.name = name;
    this.value = value;
    this.important = important;
    this.disabled = disabled;
    this.parsedOk = parsedOk;
    this.implicit = implicit;
    this.text = text;
    this.range = range ? WebInspector.TextRange.fromObject(range) : null;
}
WebInspector.CSSProperty.parsePayload = function (ownerStyle, index, payload) {
    var result = new WebInspector.CSSProperty(ownerStyle, index, payload.name, payload.value, payload.important || false, payload.disabled || false, ("parsedOk"in payload) ? !!payload.parsedOk : true, !!payload.implicit, payload.text, payload.range);
    return result;
}
WebInspector.CSSProperty.prototype = {
    sourceStyleSheetEdited: function (styleSheetId, oldRange, newRange) {
        if (this.ownerStyle.styleSheetId !== styleSheetId)
            return;
        if (this.range)
            this.range = this.range.rebaseAfterTextEdit(oldRange, newRange);
    }, _setActive: function (active) {
        this._active = active;
    }, get propertyText() {
        if (this.text !== undefined)
            return this.text;
        if (this.name === "")
            return "";
        return this.name + ": " + this.value + (this.important ? " !important" : "") + ";";
    }, get isLive() {
        return this.active || this.styleBased;
    }, get active() {
        return typeof this._active === "boolean" && this._active;
    }, get styleBased() {
        return !this.range;
    }, get inactive() {
        return typeof this._active === "boolean" && !this._active;
    }, setText: function (propertyText, majorChange, overwrite, userCallback) {
        function enabledCallback(style) {
            if (userCallback)
                userCallback(style);
        }

        function callback(error, stylePayload) {
            this.ownerStyle._cssModel._pendingCommandsMajorState.pop();
            if (!error) {
                if (majorChange)
                    this.ownerStyle._cssModel._domModel.markUndoableState();
                var style = WebInspector.CSSStyleDeclaration.parsePayload(this.ownerStyle._cssModel, stylePayload);
                var newProperty = style.allProperties[this.index];
                if (newProperty && this.disabled && !propertyText.match(/^\s*$/)) {
                    newProperty.setDisabled(false, enabledCallback);
                    return;
                }
                if (userCallback)
                    userCallback(style);
            } else {
                if (userCallback)
                    userCallback(null);
            }
        }

        if (!this.ownerStyle)
            throw"No ownerStyle for property";
        if (!this.ownerStyle.styleSheetId)
            throw"No owner style id";
        var cssModel = this.ownerStyle._cssModel;
        cssModel._pendingCommandsMajorState.push(majorChange);
        var range = (this.range);
        cssModel._agent.setPropertyText(this.ownerStyle.styleSheetId, overwrite ? range : range.collapseToStart(), propertyText, callback.bind(this));
    }, setValue: function (newValue, majorChange, overwrite, userCallback) {
        var text = this.name + ": " + newValue + (this.important ? " !important" : "") + ";"
        this.setText(text, majorChange, overwrite, userCallback);
    }, setDisabled: function (disabled, userCallback) {
        if (!this.ownerStyle && userCallback)
            userCallback(null);
        if (disabled === this.disabled) {
            if (userCallback)
                userCallback(this.ownerStyle);
            return;
        }
        if (disabled)
            this.setText("/* " + this.text + " */", true, true, userCallback); else
            this.setText(this.text.substring(2, this.text.length - 2).trim(), true, true, userCallback);
    }
}
WebInspector.CSSMediaQueryExpression = function (payload) {
    this._value = payload.value;
    this._unit = payload.unit;
    this._feature = payload.feature;
    this._computedLength = payload.computedLength || null;
}
WebInspector.CSSMediaQueryExpression.parsePayload = function (payload) {
    return new WebInspector.CSSMediaQueryExpression(payload);
}
WebInspector.CSSMediaQueryExpression.prototype = {
    value: function () {
        return this._value;
    }, unit: function () {
        return this._unit;
    }, feature: function () {
        return this._feature;
    }, computedLength: function () {
        return this._computedLength;
    }
}
WebInspector.CSSMedia = function (cssModel, payload) {
    this._cssModel = cssModel
    this.text = payload.text;
    this.source = payload.source;
    this.sourceURL = payload.sourceURL || "";
    this.range = payload.range ? WebInspector.TextRange.fromObject(payload.range) : null;
    this.parentStyleSheetId = payload.parentStyleSheetId;
    this.mediaList = null;
    if (payload.mediaList) {
        this.mediaList = [];
        for (var i = 0; i < payload.mediaList.length; ++i) {
            var mediaQueryPayload = payload.mediaList[i];
            var mediaQueryExpressions = [];
            for (var j = 0; j < mediaQueryPayload.length; ++j)
                mediaQueryExpressions.push(WebInspector.CSSMediaQueryExpression.parsePayload(mediaQueryPayload[j]));
            this.mediaList.push(mediaQueryExpressions);
        }
    }
}
WebInspector.CSSMedia.Source = {LINKED_SHEET: "linkedSheet", INLINE_SHEET: "inlineSheet", MEDIA_RULE: "mediaRule", IMPORT_RULE: "importRule"};
WebInspector.CSSMedia.parsePayload = function (cssModel, payload) {
    return new WebInspector.CSSMedia(cssModel, payload);
}
WebInspector.CSSMedia.parseMediaArrayPayload = function (cssModel, payload) {
    var result = [];
    for (var i = 0; i < payload.length; ++i)
        result.push(WebInspector.CSSMedia.parsePayload(cssModel, payload[i]));
    return result;
}
WebInspector.CSSMedia.prototype = {
    sourceStyleSheetEdited: function (styleSheetId, oldRange, newRange) {
        if (this.parentStyleSheetId !== styleSheetId)
            return;
        if (this.range)
            this.range = this.range.rebaseAfterTextEdit(oldRange, newRange);
    }, lineNumberInSource: function () {
        if (!this.range)
            return undefined;
        var header = this.header();
        if (!header)
            return undefined;
        return header.lineNumberInSource(this.range.startLine);
    }, columnNumberInSource: function () {
        if (!this.range)
            return undefined;
        var header = this.header();
        if (!header)
            return undefined;
        return header.columnNumberInSource(this.range.startLine, this.range.startColumn);
    }, header: function () {
        return this.parentStyleSheetId ? this._cssModel.styleSheetHeaderForId(this.parentStyleSheetId) : null;
    }, rawLocation: function () {
        if (!this.header() || this.lineNumberInSource() === undefined)
            return null;
        var lineNumber = Number(this.lineNumberInSource());
        return new WebInspector.CSSLocation(this._cssModel.target(), this.header().id, this.sourceURL, lineNumber, this.columnNumberInSource());
    }
}
WebInspector.CSSStyleSheetHeader = function (cssModel, payload) {
    this._cssModel = cssModel;
    this.id = payload.styleSheetId;
    this.frameId = payload.frameId;
    this.sourceURL = payload.sourceURL;
    this.hasSourceURL = !!payload.hasSourceURL;
    this.sourceMapURL = payload.sourceMapURL;
    this.origin = payload.origin;
    this.title = payload.title;
    this.disabled = payload.disabled;
    this.isInline = payload.isInline;
    this.startLine = payload.startLine;
    this.startColumn = payload.startColumn;
}
WebInspector.CSSStyleSheetHeader.prototype = {
    target: function () {
        return this._cssModel.target();
    }, resourceURL: function () {
        return this.isViaInspector() ? this._viaInspectorResourceURL() : this.sourceURL;
    }, _viaInspectorResourceURL: function () {
        var frame = this._cssModel.target().resourceTreeModel.frameForId(this.frameId);
        console.assert(frame);
        var parsedURL = new WebInspector.ParsedURL(frame.url);
        var fakeURL = "inspector://" + parsedURL.host + parsedURL.folderPathComponents;
        if (!fakeURL.endsWith("/"))
            fakeURL += "/";
        fakeURL += "inspector-stylesheet";
        return fakeURL;
    }, lineNumberInSource: function (lineNumberInStyleSheet) {
        return this.startLine + lineNumberInStyleSheet;
    }, columnNumberInSource: function (lineNumberInStyleSheet, columnNumberInStyleSheet) {
        return (lineNumberInStyleSheet ? 0 : this.startColumn) + columnNumberInStyleSheet;
    }, contentURL: function () {
        return this.resourceURL();
    }, contentType: function () {
        return WebInspector.resourceTypes.Stylesheet;
    }, _trimSourceURL: function (text) {
        var sourceURLRegex = /\n[\040\t]*\/\*[#@][\040\t]sourceURL=[\040\t]*([^\s]*)[\040\t]*\*\/[\040\t]*$/mg;
        return text.replace(sourceURLRegex, "");
    }, requestContent: function (callback) {
        this._cssModel._agent.getStyleSheetText(this.id, textCallback.bind(this));
        function textCallback(error, text) {
            if (error) {
                WebInspector.console.error("Failed to get text for stylesheet " + this.id + ": " + error);
                text = "";
            }
            text = this._trimSourceURL(text);
            callback(text);
        }
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        function performSearch(content) {
            callback(WebInspector.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex));
        }

        this.requestContent(performSearch);
    }, setContent: function (newText, callback) {
        newText = this._trimSourceURL(newText);
        if (this.hasSourceURL)
            newText += "\n/*# sourceURL=" + this.sourceURL + " */";
        this._cssModel._agent.setStyleSheetText(this.id, newText, callback);
    }, isViaInspector: function () {
        return this.origin === "inspector";
    }
}
WebInspector.CSSDispatcher = function (cssModel) {
    this._cssModel = cssModel;
}
WebInspector.CSSDispatcher.prototype = {
    mediaQueryResultChanged: function () {
        this._cssModel.mediaQueryResultChanged();
    }, styleSheetChanged: function (styleSheetId) {
        this._cssModel._fireStyleSheetChanged(styleSheetId);
    }, styleSheetAdded: function (header) {
        this._cssModel._styleSheetAdded(header);
    }, styleSheetRemoved: function (id) {
        this._cssModel._styleSheetRemoved(id);
    },
}
WebInspector.CSSStyleModel.ComputedStyleLoader = function (cssModel) {
    this._cssModel = cssModel;
    this._nodeIdToCallbackData = {};
}
WebInspector.CSSStyleModel.ComputedStyleLoader.prototype = {
    getComputedStyle: function (nodeId, userCallback) {
        if (this._nodeIdToCallbackData[nodeId]) {
            this._nodeIdToCallbackData[nodeId].push(userCallback);
            return;
        }
        this._nodeIdToCallbackData[nodeId] = [userCallback];
        this._cssModel._agent.getComputedStyleForNode(nodeId, resultCallback.bind(this, nodeId));
        function resultCallback(nodeId, error, computedPayload) {
            var computedStyle = (error || !computedPayload) ? null : WebInspector.CSSStyleDeclaration.parseComputedStylePayload(this._cssModel, computedPayload);
            var callbacks = this._nodeIdToCallbackData[nodeId];
            if (!callbacks)
                return;
            delete this._nodeIdToCallbackData[nodeId];
            for (var i = 0; i < callbacks.length; ++i)
                callbacks[i](computedStyle);
        }
    }
}
WebInspector.cssModel;
WebInspector.LiveLocation = function (updateDelegate) {
    this._updateDelegate = updateDelegate;
}
WebInspector.LiveLocation.prototype = {
    update: function () {
        var uiLocation = this.uiLocation();
        if (!uiLocation)
            return;
        if (this._updateDelegate(uiLocation))
            this.dispose();
    }, uiLocation: function () {
        throw"Not implemented";
    }, dispose: function () {
    }
}
WebInspector.CSSWorkspaceBinding = function () {
    this._targetToTargetInfo = new Map();
    WebInspector.targetManager.observeTargets(this);
    WebInspector.targetManager.addModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameCreatedOrNavigated, this);
}
WebInspector.CSSWorkspaceBinding.prototype = {
    targetAdded: function (target) {
        this._targetToTargetInfo.put(target, new WebInspector.CSSWorkspaceBinding.TargetInfo(target, WebInspector.workspace, WebInspector.networkWorkspaceBinding));
    }, targetRemoved: function (target) {
        this._targetToTargetInfo.remove(target)._dispose();
    }, pushSourceMapping: function (header, mapping) {
        this._ensureInfoForHeader(header)._pushSourceMapping(mapping);
    }, _headerInfo: function (header) {
        var map = this._targetToTargetInfo.get(header.target());
        return map._headerInfo(header.id) || null;
    }, _ensureInfoForHeader: function (header) {
        var targetInfo = this._targetToTargetInfo.get(header.target());
        if (!targetInfo) {
            targetInfo = new WebInspector.CSSWorkspaceBinding.TargetInfo(header.target(), WebInspector.workspace, WebInspector.networkWorkspaceBinding);
            this._targetToTargetInfo.put(header.target(), targetInfo);
        }
        return targetInfo._ensureInfoForHeader(header);
    }, _mainFrameCreatedOrNavigated: function (event) {
        var target = (event.target).target();
        this._targetToTargetInfo.get(target)._reset();
    }, updateLocations: function (header) {
        var info = this._headerInfo(header);
        if (info)
            info._updateLocations();
    }, createLiveLocation: function (rawLocation, updateDelegate) {
        var header = rawLocation.styleSheetId ? rawLocation.target().cssModel.styleSheetHeaderForId(rawLocation.styleSheetId) : null;
        return new WebInspector.CSSWorkspaceBinding.LiveLocation(rawLocation.target().cssModel, header, rawLocation, updateDelegate);
    }, _addLiveLocation: function (location) {
        this._ensureInfoForHeader(location._header)._addLocation(location);
    }, _removeLiveLocation: function (location) {
        var info = this._headerInfo(location._header);
        if (info)
            info._removeLocation(location);
    }, propertyUILocation: function (cssProperty, forName) {
        var style = cssProperty.ownerStyle;
        if (!style || !style.parentRule || !style.styleSheetId)
            return null;
        var range = cssProperty.range;
        if (!range)
            return null;
        var url = style.parentRule.resourceURL();
        if (!url)
            return null;
        var line = forName ? range.startLine : range.endLine;
        var column = forName ? range.startColumn : range.endColumn - (cssProperty.text && cssProperty.text.endsWith(";") ? 2 : 1);
        var rawLocation = new WebInspector.CSSLocation(style.target(), style.styleSheetId, url, line, column);
        return this.rawLocationToUILocation(rawLocation);
    }, rawLocationToUILocation: function (rawLocation) {
        if (!rawLocation)
            return null;
        var cssModel = rawLocation.target().cssModel;
        var frameIdToSheetIds = cssModel.styleSheetIdsByFrameIdForURL(rawLocation.url);
        if (!Object.values(frameIdToSheetIds).length)
            return null;
        var styleSheetIds = [];
        for (var frameId in frameIdToSheetIds)
            styleSheetIds = styleSheetIds.concat(frameIdToSheetIds[frameId]);
        var uiLocation;
        for (var i = 0; !uiLocation && i < styleSheetIds.length; ++i) {
            var header = cssModel.styleSheetHeaderForId(styleSheetIds[i]);
            if (!header)
                continue;
            var info = this._headerInfo(header);
            if (info)
                uiLocation = info._rawLocationToUILocation(rawLocation.lineNumber, rawLocation.columnNumber);
        }
        return uiLocation || null;
    }
}
WebInspector.CSSWorkspaceBinding.TargetInfo = function (target, workspace, networkWorkspaceBinding) {
    this._target = target;
    this._workspace = workspace;
    var cssModel = target.cssModel;
    this._stylesSourceMapping = new WebInspector.StylesSourceMapping(cssModel, workspace);
    this._sassSourceMapping = new WebInspector.SASSSourceMapping(cssModel, workspace, networkWorkspaceBinding);
    this._headerInfoById = new StringMap();
    cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._styleSheetAdded, this);
    cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._styleSheetRemoved, this);
}
WebInspector.CSSWorkspaceBinding.TargetInfo.prototype = {
    _styleSheetAdded: function (event) {
        var header = (event.data);
        this._stylesSourceMapping.addHeader(header);
        this._sassSourceMapping.addHeader(header);
    }, _styleSheetRemoved: function (event) {
        var header = (event.data);
        this._stylesSourceMapping.removeHeader(header);
        this._sassSourceMapping.removeHeader(header);
        this._headerInfoById.remove(header.id);
    }, _headerInfo: function (id) {
        return this._headerInfoById.get(id);
    }, _ensureInfoForHeader: function (header) {
        var info = this._headerInfoById.get(header.id);
        if (!info) {
            info = new WebInspector.CSSWorkspaceBinding.HeaderInfo(header);
            this._headerInfoById.put(header.id, info);
        }
        return info;
    }, _dispose: function () {
        this._reset();
        this._target.cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._styleSheetAdded, this);
        this._target.cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._styleSheetRemoved, this);
    }, _reset: function () {
        this._headerInfoById.clear();
    }
}
WebInspector.CSSWorkspaceBinding.HeaderInfo = function (header) {
    this._header = header;
    this._sourceMappings = [];
    this._locations = new Set();
}
WebInspector.CSSWorkspaceBinding.HeaderInfo.prototype = {
    _addLocation: function (location) {
        this._locations.add(location);
        location.update();
    }, _removeLocation: function (location) {
        this._locations.remove(location);
    }, _updateLocations: function () {
        var items = this._locations.values();
        for (var i = 0; i < items.length; ++i)
            items[i].update();
    }, _rawLocationToUILocation: function (lineNumber, columnNumber) {
        var uiLocation = null;
        var rawLocation = new WebInspector.CSSLocation(this._header.target(), this._header.id, this._header.resourceURL(), lineNumber, columnNumber);
        for (var i = this._sourceMappings.length - 1; !uiLocation && i >= 0; --i)
            uiLocation = this._sourceMappings[i].rawLocationToUILocation(rawLocation);
        return uiLocation;
    }, _pushSourceMapping: function (sourceMapping) {
        this._sourceMappings.push(sourceMapping);
        this._updateLocations();
    }
}
WebInspector.CSSWorkspaceBinding.LiveLocation = function (cssModel, header, rawLocation, updateDelegate) {
    WebInspector.LiveLocation.call(this, updateDelegate);
    this._cssModel = cssModel;
    this._rawLocation = rawLocation;
    if (!header)
        this._clearStyleSheet(); else
        this._setStyleSheet(header);
}
WebInspector.CSSWorkspaceBinding.LiveLocation.prototype = {
    _styleSheetAdded: function (event) {
        console.assert(!this._header);
        var header = (event.data);
        if (header.sourceURL && header.sourceURL === this._rawLocation.url)
            this._setStyleSheet(header);
    }, _styleSheetRemoved: function (event) {
        console.assert(this._header);
        var header = (event.data);
        if (this._header !== header)
            return;
        WebInspector.cssWorkspaceBinding._removeLiveLocation(this);
        this._clearStyleSheet();
    }, _setStyleSheet: function (header) {
        this._header = header;
        WebInspector.cssWorkspaceBinding._addLiveLocation(this);
        this._cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._styleSheetAdded, this);
        this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._styleSheetRemoved, this);
    }, _clearStyleSheet: function () {
        delete this._header;
        this._cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._styleSheetRemoved, this);
        this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._styleSheetAdded, this);
    }, uiLocation: function () {
        var cssLocation = this._rawLocation;
        if (this._header) {
            var headerInfo = WebInspector.cssWorkspaceBinding._headerInfo(this._header);
            return headerInfo._rawLocationToUILocation(cssLocation.lineNumber, cssLocation.columnNumber);
        }
        var uiSourceCode = WebInspector.workspace.uiSourceCodeForURL(cssLocation.url);
        if (!uiSourceCode)
            return null;
        return uiSourceCode.uiLocation(cssLocation.lineNumber, cssLocation.columnNumber);
    }, dispose: function () {
        WebInspector.LiveLocation.prototype.dispose.call(this);
        if (this._header)
            WebInspector.cssWorkspaceBinding._removeLiveLocation(this);
        this._cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._styleSheetAdded, this);
        this._cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._styleSheetRemoved, this);
    }, __proto__: WebInspector.LiveLocation.prototype
}
WebInspector.CSSSourceMapping = function () {
}
WebInspector.CSSSourceMapping.prototype = {
    rawLocationToUILocation: function (rawLocation) {
    }, uiLocationToRawLocation: function (uiSourceCode, lineNumber, columnNumber) {
    }, isIdentity: function () {
    }, uiLineHasMapping: function (uiSourceCode, lineNumber) {
    }
}
WebInspector.cssWorkspaceBinding;
WebInspector.CSSParser = function () {
    this._worker = Runtime.startWorker("script_formatter_worker");
    this._worker.onmessage = this._onRuleChunk.bind(this);
    this._rules = [];
}
WebInspector.CSSParser.Events = {RulesParsed: "RulesParsed"}
WebInspector.CSSParser.prototype = {
    fetchAndParse: function (styleSheetHeader, callback) {
        this._lock();
        this._finishedCallback = callback;
        styleSheetHeader.requestContent(this._innerParse.bind(this));
    }, parse: function (text, callback) {
        this._lock();
        this._finishedCallback = callback;
        this._innerParse(text);
    }, dispose: function () {
        if (this._worker) {
            this._worker.terminate();
            delete this._worker;
        }
    }, rules: function () {
        return this._rules;
    }, _lock: function () {
        console.assert(!this._parsingStyleSheet, "Received request to parse stylesheet before previous was completed.");
        this._parsingStyleSheet = true;
    }, _unlock: function () {
        delete this._parsingStyleSheet;
    }, _innerParse: function (text) {
        this._rules = [];
        this._worker.postMessage({method: "parseCSS", params: {content: text}});
    }, _onRuleChunk: function (event) {
        var data = (event.data);
        var chunk = data.chunk;
        for (var i = 0; i < chunk.length; ++i)
            this._rules.push(chunk[i]);
        if (data.isLastChunk)
            this._onFinishedParsing();
        this.dispatchEventToListeners(WebInspector.CSSParser.Events.RulesParsed);
    }, _onFinishedParsing: function () {
        this._unlock();
        if (this._finishedCallback)
            this._finishedCallback(this._rules);
    }, __proto__: WebInspector.Object.prototype,
}
WebInspector.CSSParser.DataChunk;
WebInspector.CSSParser.StyleRule;
WebInspector.CSSParser.AtRule;
WebInspector.CSSParser.Rule;
WebInspector.CSSParser.Property;
WebInspector.NetworkManager = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.NetworkManager, target);
    this._dispatcher = new WebInspector.NetworkDispatcher(this);
    this._target = target;
    this._networkAgent = target.networkAgent();
    target.registerNetworkDispatcher(this._dispatcher);
    if (WebInspector.settings.cacheDisabled.get())
        this._networkAgent.setCacheDisabled(true);
    this._networkAgent.enable();
    WebInspector.settings.cacheDisabled.addChangeListener(this._cacheDisabledSettingChanged, this);
}
WebInspector.NetworkManager.EventTypes = {RequestStarted: "RequestStarted", RequestUpdated: "RequestUpdated", RequestFinished: "RequestFinished", RequestUpdateDropped: "RequestUpdateDropped"}
WebInspector.NetworkManager._MIMETypes = {
    "text/html": {"document": true},
    "text/xml": {"document": true},
    "text/plain": {"document": true},
    "application/xhtml+xml": {"document": true},
    "text/css": {"stylesheet": true},
    "text/xsl": {"stylesheet": true},
    "image/jpg": {"image": true},
    "image/jpeg": {"image": true},
    "image/pjpeg": {"image": true},
    "image/png": {"image": true},
    "image/gif": {"image": true},
    "image/bmp": {"image": true},
    "image/svg+xml": {"image": true, "font": true, "document": true},
    "image/vnd.microsoft.icon": {"image": true},
    "image/webp": {"image": true},
    "image/x-icon": {"image": true},
    "image/x-xbitmap": {"image": true},
    "font/ttf": {"font": true},
    "font/otf": {"font": true},
    "font/woff": {"font": true},
    "font/woff2": {"font": true},
    "font/truetype": {"font": true},
    "font/opentype": {"font": true},
    "application/octet-stream": {"font": true, "image": true},
    "application/font-woff": {"font": true},
    "application/font-woff2": {"font": true},
    "application/x-font-woff": {"font": true},
    "application/x-font-type1": {"font": true},
    "application/x-font-ttf": {"font": true},
    "application/x-truetype-font": {"font": true},
    "text/javascript": {"script": true},
    "text/ecmascript": {"script": true},
    "application/javascript": {"script": true},
    "application/ecmascript": {"script": true},
    "application/x-javascript": {"script": true},
    "application/json": {"script": true},
    "text/javascript1.1": {"script": true},
    "text/javascript1.2": {"script": true},
    "text/javascript1.3": {"script": true},
    "text/jscript": {"script": true},
    "text/livescript": {"script": true},
    "text/vtt": {"texttrack": true},
}
WebInspector.NetworkManager._devToolsRequestHeader = "X-DevTools-Request-Initiator";
WebInspector.NetworkManager.hasDevToolsRequestHeader = function (request) {
    return !!request && !!request.requestHeaderValue(WebInspector.NetworkManager._devToolsRequestHeader);
}
WebInspector.NetworkManager.prototype = {
    inflightRequestForURL: function (url) {
        return this._dispatcher._inflightRequestsByURL[url];
    }, _cacheDisabledSettingChanged: function (event) {
        var enabled = (event.data);
        this._networkAgent.setCacheDisabled(enabled);
    }, dispose: function () {
        WebInspector.settings.cacheDisabled.removeChangeListener(this._cacheDisabledSettingChanged, this)
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.NetworkDispatcher = function (manager) {
    this._manager = manager;
    this._inflightRequestsById = {};
    this._inflightRequestsByURL = {};
}
WebInspector.NetworkDispatcher.prototype = {
    _headersMapToHeadersArray: function (headersMap) {
        var result = [];
        for (var name in headersMap) {
            var values = headersMap[name].split("\n");
            for (var i = 0; i < values.length; ++i)
                result.push({name: name, value: values[i]});
        }
        return result;
    }, _updateNetworkRequestWithRequest: function (networkRequest, request) {
        networkRequest.requestMethod = request.method;
        networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));
        networkRequest.requestFormData = request.postData;
    }, _updateNetworkRequestWithResponse: function (networkRequest, response) {
        if (response.url && networkRequest.url !== response.url)
            networkRequest.url = response.url;
        networkRequest.mimeType = response.mimeType;
        networkRequest.statusCode = response.status;
        networkRequest.statusText = response.statusText;
        networkRequest.responseHeaders = this._headersMapToHeadersArray(response.headers);
        if (response.encodedDataLength >= 0)
            networkRequest.setTransferSize(response.encodedDataLength);
        if (response.headersText)
            networkRequest.responseHeadersText = response.headersText;
        if (response.requestHeaders) {
            networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));
            networkRequest.setRequestHeadersText(response.requestHeadersText || "");
        }
        networkRequest.connectionReused = response.connectionReused;
        networkRequest.connectionId = response.connectionId;
        if (response.remoteIPAddress)
            networkRequest.setRemoteAddress(response.remoteIPAddress, response.remotePort || -1);
        if (response.fromDiskCache)
            networkRequest.cached = true; else
            networkRequest.timing = response.timing;
        if (!this._mimeTypeIsConsistentWithType(networkRequest)) {
            var consoleModel = this._manager._target.consoleModel;
            consoleModel.addMessage(new WebInspector.ConsoleMessage(consoleModel.target(), WebInspector.ConsoleMessage.MessageSource.Network, WebInspector.ConsoleMessage.MessageLevel.Log, WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s: \"%s\".", networkRequest.type.title(), networkRequest.mimeType, networkRequest.url), WebInspector.ConsoleMessage.MessageType.Log, "", 0, 0, networkRequest.requestId));
        }
    }, _mimeTypeIsConsistentWithType: function (networkRequest) {
        if (networkRequest.hasErrorStatusCode() || networkRequest.statusCode === 304 || networkRequest.statusCode === 204)
            return true;
        if (typeof networkRequest.type === "undefined" || networkRequest.type === WebInspector.resourceTypes.Other || networkRequest.type === WebInspector.resourceTypes.Media || networkRequest.type === WebInspector.resourceTypes.XHR || networkRequest.type === WebInspector.resourceTypes.WebSocket)
            return true;
        if (!networkRequest.mimeType)
            return true;
        if (networkRequest.mimeType in WebInspector.NetworkManager._MIMETypes)
            return networkRequest.type.name()in WebInspector.NetworkManager._MIMETypes[networkRequest.mimeType];
        return false;
    }, requestWillBeSent: function (requestId, frameId, loaderId, documentURL, request, time, initiator, redirectResponse) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (networkRequest) {
            if (!redirectResponse)
                return;
            this.responseReceived(requestId, frameId, loaderId, time, PageAgent.ResourceType.Other, redirectResponse);
            networkRequest = this._appendRedirect(requestId, time, request.url);
        } else
            networkRequest = this._createNetworkRequest(requestId, frameId, loaderId, request.url, documentURL, initiator);
        networkRequest.hasNetworkData = true;
        this._updateNetworkRequestWithRequest(networkRequest, request);
        networkRequest.startTime = time;
        this._startNetworkRequest(networkRequest);
    }, requestServedFromCache: function (requestId) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        networkRequest.cached = true;
    }, responseReceived: function (requestId, frameId, loaderId, time, resourceType, response) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest) {
            var eventData = {};
            eventData.url = response.url;
            eventData.frameId = frameId;
            eventData.loaderId = loaderId;
            eventData.resourceType = resourceType;
            eventData.mimeType = response.mimeType;
            this._manager.dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestUpdateDropped, eventData);
            return;
        }
        networkRequest.responseReceivedTime = time;
        networkRequest.type = WebInspector.resourceTypes[resourceType];
        this._updateNetworkRequestWithResponse(networkRequest, response);
        this._updateNetworkRequest(networkRequest);
    }, dataReceived: function (requestId, time, dataLength, encodedDataLength) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        networkRequest.resourceSize += dataLength;
        if (encodedDataLength != -1)
            networkRequest.increaseTransferSize(encodedDataLength);
        networkRequest.endTime = time;
        this._updateNetworkRequest(networkRequest);
    }, loadingFinished: function (requestId, finishTime, encodedDataLength) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        this._finishNetworkRequest(networkRequest, finishTime, encodedDataLength);
    }, loadingFailed: function (requestId, time, resourceType, localizedDescription, canceled) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        networkRequest.failed = true;
        networkRequest.type = WebInspector.resourceTypes[resourceType];
        networkRequest.canceled = canceled;
        networkRequest.localizedFailDescription = localizedDescription;
        this._finishNetworkRequest(networkRequest, time, -1);
    }, webSocketCreated: function (requestId, requestURL) {
        var networkRequest = new WebInspector.NetworkRequest(this._manager._target, requestId, requestURL, "", "", "");
        networkRequest.type = WebInspector.resourceTypes.WebSocket;
        this._startNetworkRequest(networkRequest);
    }, webSocketWillSendHandshakeRequest: function (requestId, time, request) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        networkRequest.requestMethod = "GET";
        networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers));
        networkRequest.startTime = time;
        this._updateNetworkRequest(networkRequest);
    }, webSocketHandshakeResponseReceived: function (requestId, time, response) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        networkRequest.statusCode = response.status;
        networkRequest.statusText = response.statusText;
        networkRequest.responseHeaders = this._headersMapToHeadersArray(response.headers);
        networkRequest.responseHeadersText = response.headersText;
        if (response.requestHeaders)
            networkRequest.setRequestHeaders(this._headersMapToHeadersArray(response.requestHeaders));
        if (response.requestHeadersText)
            networkRequest.setRequestHeadersText(response.requestHeadersText);
        networkRequest.responseReceivedTime = time;
        this._updateNetworkRequest(networkRequest);
    }, webSocketFrameReceived: function (requestId, time, response) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        networkRequest.addFrame(response, time);
        networkRequest.responseReceivedTime = time;
        this._updateNetworkRequest(networkRequest);
    }, webSocketFrameSent: function (requestId, time, response) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        networkRequest.addFrame(response, time, true);
        networkRequest.responseReceivedTime = time;
        this._updateNetworkRequest(networkRequest);
    }, webSocketFrameError: function (requestId, time, errorMessage) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        networkRequest.addFrameError(errorMessage, time);
        networkRequest.responseReceivedTime = time;
        this._updateNetworkRequest(networkRequest);
    }, webSocketClosed: function (requestId, time) {
        var networkRequest = this._inflightRequestsById[requestId];
        if (!networkRequest)
            return;
        this._finishNetworkRequest(networkRequest, time, -1);
    }, _appendRedirect: function (requestId, time, redirectURL) {
        var originalNetworkRequest = this._inflightRequestsById[requestId];
        var previousRedirects = originalNetworkRequest.redirects || [];
        originalNetworkRequest.requestId = requestId + ":redirected." + previousRedirects.length;
        delete originalNetworkRequest.redirects;
        if (previousRedirects.length > 0)
            originalNetworkRequest.redirectSource = previousRedirects[previousRedirects.length - 1];
        this._finishNetworkRequest(originalNetworkRequest, time, -1);
        var newNetworkRequest = this._createNetworkRequest(requestId, originalNetworkRequest.frameId, originalNetworkRequest.loaderId, redirectURL, originalNetworkRequest.documentURL, originalNetworkRequest.initiator);
        newNetworkRequest.redirects = previousRedirects.concat(originalNetworkRequest);
        return newNetworkRequest;
    }, _startNetworkRequest: function (networkRequest) {
        this._inflightRequestsById[networkRequest.requestId] = networkRequest;
        this._inflightRequestsByURL[networkRequest.url] = networkRequest;
        this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestStarted, networkRequest);
    }, _updateNetworkRequest: function (networkRequest) {
        this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestUpdated, networkRequest);
    }, _finishNetworkRequest: function (networkRequest, finishTime, encodedDataLength) {
        networkRequest.endTime = finishTime;
        networkRequest.finished = true;
        if (encodedDataLength >= 0)
            networkRequest.setTransferSize(encodedDataLength);
        this._dispatchEventToListeners(WebInspector.NetworkManager.EventTypes.RequestFinished, networkRequest);
        delete this._inflightRequestsById[networkRequest.requestId];
        delete this._inflightRequestsByURL[networkRequest.url];
    }, _dispatchEventToListeners: function (eventType, networkRequest) {
        this._manager.dispatchEventToListeners(eventType, networkRequest);
    }, _createNetworkRequest: function (requestId, frameId, loaderId, url, documentURL, initiator) {
        var networkRequest = new WebInspector.NetworkRequest(this._manager._target, requestId, url, documentURL, frameId, loaderId);
        networkRequest.initiator = initiator;
        return networkRequest;
    }
}
WebInspector.NetworkLog = function (target) {
    WebInspector.SDKObject.call(this, target);
    this._requests = [];
    this._requestForId = {};
    target.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestStarted, this._onRequestStarted, this);
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._onMainFrameNavigated, this);
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.Load, this._onLoad, this);
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.DOMContentLoaded, this._onDOMContentLoaded, this);
}
WebInspector.NetworkLog.prototype = {
    get requests() {
        return this._requests;
    }, requestForURL: function (url) {
        for (var i = 0; i < this._requests.length; ++i) {
            if (this._requests[i].url === url)
                return this._requests[i];
        }
        return null;
    }, pageLoadForRequest: function (request) {
        return request.__page;
    }, _onMainFrameNavigated: function (event) {
        var mainFrame = event.data;
        this._currentPageLoad = null;
        var oldRequests = this._requests.splice(0, this._requests.length);
        this._requestForId = {};
        for (var i = 0; i < oldRequests.length; ++i) {
            var request = oldRequests[i];
            if (request.loaderId === mainFrame.loaderId) {
                if (!this._currentPageLoad)
                    this._currentPageLoad = new WebInspector.PageLoad(request);
                this._requests.push(request);
                this._requestForId[request.requestId] = request;
                request.__page = this._currentPageLoad;
            }
        }
    }, _onRequestStarted: function (event) {
        var request = (event.data);
        this._requests.push(request);
        this._requestForId[request.requestId] = request;
        request.__page = this._currentPageLoad;
    }, _onDOMContentLoaded: function (event) {
        if (this._currentPageLoad)
            this._currentPageLoad.contentLoadTime = event.data;
    }, _onLoad: function (event) {
        if (this._currentPageLoad)
            this._currentPageLoad.loadTime = event.data;
    }, requestForId: function (requestId) {
        return this._requestForId[requestId];
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.networkLog;
WebInspector.PageLoad = function (mainRequest) {
    this.id = ++WebInspector.PageLoad._lastIdentifier;
    this.url = mainRequest.url;
    this.startTime = mainRequest.startTime;
}
WebInspector.PageLoad._lastIdentifier = 0;
WebInspector.ResourceTreeModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.ResourceTreeModel, target);
    target.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestFinished, this._onRequestFinished, this);
    target.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestUpdateDropped, this._onRequestUpdateDropped, this);
    target.consoleModel.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, this._consoleMessageAdded, this);
    target.consoleModel.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this);
    this._agent = target.pageAgent();
    this._agent.enable();
    this._fetchResourceTree();
    target.registerPageDispatcher(new WebInspector.PageDispatcher(this));
    this._pendingConsoleMessages = {};
    this._securityOriginFrameCount = {};
    this._inspectedPageURL = "";
}
WebInspector.ResourceTreeModel.EventTypes = {
    FrameAdded: "FrameAdded",
    FrameNavigated: "FrameNavigated",
    FrameDetached: "FrameDetached",
    FrameResized: "FrameResized",
    MainFrameNavigated: "MainFrameNavigated",
    ResourceAdded: "ResourceAdded",
    WillLoadCachedResources: "WillLoadCachedResources",
    CachedResourcesLoaded: "CachedResourcesLoaded",
    DOMContentLoaded: "DOMContentLoaded",
    Load: "Load",
    WillReloadPage: "WillReloadPage",
    InspectedURLChanged: "InspectedURLChanged",
    SecurityOriginAdded: "SecurityOriginAdded",
    SecurityOriginRemoved: "SecurityOriginRemoved",
    ScreencastFrame: "ScreencastFrame",
    ScreencastVisibilityChanged: "ScreencastVisibilityChanged",
    ViewportChanged: "ViewportChanged"
}
WebInspector.ResourceTreeModel.prototype = {
    _fetchResourceTree: function () {
        this._frames = {};
        delete this._cachedResourcesProcessed;
        this._agent.getResourceTree(this._processCachedResources.bind(this));
    }, _processCachedResources: function (error, mainFramePayload) {
        if (error) {
            if (!this.target().isWorkerTarget())
                console.error(JSON.stringify(error));
            return;
        }
        this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.WillLoadCachedResources);
        this._inspectedPageURL = mainFramePayload.frame.url;
        this._addFramesRecursively(null, mainFramePayload);
        this._dispatchInspectedURLChanged();
        this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded);
        this._cachedResourcesProcessed = true;
    }, inspectedPageURL: function () {
        return this._inspectedPageURL;
    }, inspectedPageDomain: function () {
        var parsedURL = this._inspectedPageURL ? this._inspectedPageURL.asParsedURL() : null;
        return parsedURL ? parsedURL.host : "";
    }, cachedResourcesLoaded: function () {
        return this._cachedResourcesProcessed;
    }, _dispatchInspectedURLChanged: function () {
        InspectorFrontendHost.inspectedURLChanged(this._inspectedPageURL);
        this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._inspectedPageURL);
    }, _addFrame: function (frame, aboutToNavigate) {
        this._frames[frame.id] = frame;
        if (frame.isMainFrame())
            this.mainFrame = frame;
        this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, frame);
        if (!aboutToNavigate)
            this._addSecurityOrigin(frame.securityOrigin);
    }, _addSecurityOrigin: function (securityOrigin) {
        if (!this._securityOriginFrameCount[securityOrigin]) {
            this._securityOriginFrameCount[securityOrigin] = 1;
            this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginAdded, securityOrigin);
            return;
        }
        this._securityOriginFrameCount[securityOrigin] += 1;
    }, _removeSecurityOrigin: function (securityOrigin) {
        if (typeof securityOrigin === "undefined")
            return;
        if (this._securityOriginFrameCount[securityOrigin] === 1) {
            delete this._securityOriginFrameCount[securityOrigin];
            this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginRemoved, securityOrigin);
            return;
        }
        this._securityOriginFrameCount[securityOrigin] -= 1;
    }, securityOrigins: function () {
        return Object.keys(this._securityOriginFrameCount);
    }, _handleMainFrameDetached: function (mainFrame) {
        function removeOriginForFrame(frame) {
            for (var i = 0; i < frame.childFrames.length; ++i)
                removeOriginForFrame.call(this, frame.childFrames[i]);
            if (!frame.isMainFrame())
                this._removeSecurityOrigin(frame.securityOrigin);
        }

        removeOriginForFrame.call(this, WebInspector.resourceTreeModel.mainFrame);
    }, _frameAttached: function (frameId, parentFrameId) {
        if (!this._cachedResourcesProcessed)
            return null;
        if (this._frames[frameId])
            return null;
        var parentFrame = parentFrameId ? this._frames[parentFrameId] : null;
        var frame = new WebInspector.ResourceTreeFrame(this, parentFrame, frameId);
        if (frame.isMainFrame() && this.mainFrame) {
            this._handleMainFrameDetached(this.mainFrame);
            this._frameDetached(this.mainFrame.id);
        }
        this._addFrame(frame, true);
        return frame;
    }, _frameNavigated: function (framePayload) {
        if (!this._cachedResourcesProcessed)
            return;
        var frame = this._frames[framePayload.id];
        if (!frame) {
            console.assert(!framePayload.parentId, "Main frame shouldn't have parent frame id.");
            frame = this._frameAttached(framePayload.id, framePayload.parentId || "");
            console.assert(frame);
        }
        this._removeSecurityOrigin(frame.securityOrigin);
        frame._navigate(framePayload);
        var addedOrigin = frame.securityOrigin;
        if (frame.isMainFrame())
            this._inspectedPageURL = frame.url;
        this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, frame);
        if (frame.isMainFrame())
            this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, frame);
        if (addedOrigin)
            this._addSecurityOrigin(addedOrigin);
        var resources = frame.resources();
        for (var i = 0; i < resources.length; ++i)
            this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, resources[i]);
        if (frame.isMainFrame())
            this._dispatchInspectedURLChanged();
    }, _frameDetached: function (frameId) {
        if (!this._cachedResourcesProcessed)
            return;
        var frame = this._frames[frameId];
        if (!frame)
            return;
        this._removeSecurityOrigin(frame.securityOrigin);
        if (frame.parentFrame)
            frame.parentFrame._removeChildFrame(frame); else
            frame._remove();
    }, _onRequestFinished: function (event) {
        if (!this._cachedResourcesProcessed)
            return;
        var request = (event.data);
        if (request.failed || request.type === WebInspector.resourceTypes.XHR)
            return;
        var frame = this._frames[request.frameId];
        if (frame) {
            var resource = frame._addRequest(request);
            this._addPendingConsoleMessagesToResource(resource);
        }
    }, _onRequestUpdateDropped: function (event) {
        if (!this._cachedResourcesProcessed)
            return;
        var frameId = event.data.frameId;
        var frame = this._frames[frameId];
        if (!frame)
            return;
        var url = event.data.url;
        if (frame._resourcesMap[url])
            return;
        var resource = new WebInspector.Resource(this.target(), null, url, frame.url, frameId, event.data.loaderId, WebInspector.resourceTypes[event.data.resourceType], event.data.mimeType);
        frame.addResource(resource);
    }, frameForId: function (frameId) {
        return this._frames[frameId];
    }, forAllResources: function (callback) {
        if (this.mainFrame)
            return this.mainFrame._callForFrameResources(callback);
        return false;
    }, frames: function () {
        return Object.values(this._frames);
    }, _consoleMessageAdded: function (event) {
        var msg = (event.data);
        var resource = msg.url ? this.resourceForURL(msg.url) : null;
        if (resource)
            this._addConsoleMessageToResource(msg, resource); else
            this._addPendingConsoleMessage(msg);
    }, _addPendingConsoleMessage: function (msg) {
        if (!msg.url)
            return;
        if (!this._pendingConsoleMessages[msg.url])
            this._pendingConsoleMessages[msg.url] = [];
        this._pendingConsoleMessages[msg.url].push(msg);
    }, _addPendingConsoleMessagesToResource: function (resource) {
        var messages = this._pendingConsoleMessages[resource.url];
        if (messages) {
            for (var i = 0; i < messages.length; i++)
                this._addConsoleMessageToResource(messages[i], resource);
            delete this._pendingConsoleMessages[resource.url];
        }
    }, _addConsoleMessageToResource: function (msg, resource) {
        switch (msg.level) {
            case WebInspector.ConsoleMessage.MessageLevel.Warning:
                resource.warnings++;
                break;
            case WebInspector.ConsoleMessage.MessageLevel.Error:
                resource.errors++;
                break;
        }
        resource.addMessage(msg);
    }, _consoleCleared: function () {
        function callback(resource) {
            resource.clearErrorsAndWarnings();
        }

        this._pendingConsoleMessages = {};
        this.forAllResources(callback);
    }, resourceForURL: function (url) {
        return this.mainFrame ? this.mainFrame.resourceForURL(url) : null;
    }, _addFramesRecursively: function (parentFrame, frameTreePayload) {
        var framePayload = frameTreePayload.frame;
        var frame = new WebInspector.ResourceTreeFrame(this, parentFrame, framePayload.id, framePayload);
        this._addFrame(frame);
        var frameResource = this._createResourceFromFramePayload(framePayload, framePayload.url, WebInspector.resourceTypes.Document, framePayload.mimeType);
        if (frame.isMainFrame())
            this._inspectedPageURL = frameResource.url;
        frame.addResource(frameResource);
        for (var i = 0; frameTreePayload.childFrames && i < frameTreePayload.childFrames.length; ++i)
            this._addFramesRecursively(frame, frameTreePayload.childFrames[i]);
        for (var i = 0; i < frameTreePayload.resources.length; ++i) {
            var subresource = frameTreePayload.resources[i];
            var resource = this._createResourceFromFramePayload(framePayload, subresource.url, WebInspector.resourceTypes[subresource.type], subresource.mimeType);
            frame.addResource(resource);
        }
    }, _createResourceFromFramePayload: function (frame, url, type, mimeType) {
        return new WebInspector.Resource(this.target(), null, url, frame.url, frame.id, frame.loaderId, type, mimeType);
    }, reloadPage: function (ignoreCache, scriptToEvaluateOnLoad, scriptPreprocessor) {
        this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.WillReloadPage);
        this._agent.reload(ignoreCache, scriptToEvaluateOnLoad, scriptPreprocessor);
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.ResourceTreeFrame = function (model, parentFrame, frameId, payload) {
    this._model = model;
    this._parentFrame = parentFrame;
    this._id = frameId;
    this._url = "";
    if (payload) {
        this._loaderId = payload.loaderId;
        this._name = payload.name;
        this._url = payload.url;
        this._securityOrigin = payload.securityOrigin;
        this._mimeType = payload.mimeType;
    }
    this._childFrames = [];
    this._resourcesMap = {};
    if (this._parentFrame)
        this._parentFrame._childFrames.push(this);
}
WebInspector.ResourceTreeFrame.prototype = {
    target: function () {
        return this._model.target();
    }, get id() {
        return this._id;
    }, get name() {
        return this._name || "";
    }, get url() {
        return this._url;
    }, get securityOrigin() {
        return this._securityOrigin;
    }, get loaderId() {
        return this._loaderId;
    }, get parentFrame() {
        return this._parentFrame;
    }, get childFrames() {
        return this._childFrames;
    }, isMainFrame: function () {
        return !this._parentFrame;
    }, _navigate: function (framePayload) {
        this._loaderId = framePayload.loaderId;
        this._name = framePayload.name;
        this._url = framePayload.url;
        this._securityOrigin = framePayload.securityOrigin;
        this._mimeType = framePayload.mimeType;
        var mainResource = this._resourcesMap[this._url];
        this._resourcesMap = {};
        this._removeChildFrames();
        if (mainResource && mainResource.loaderId === this._loaderId)
            this.addResource(mainResource);
    }, get mainResource() {
        return this._resourcesMap[this._url];
    }, _removeChildFrame: function (frame) {
        this._childFrames.remove(frame);
        frame._remove();
    }, _removeChildFrames: function () {
        var frames = this._childFrames;
        this._childFrames = [];
        for (var i = 0; i < frames.length; ++i)
            frames[i]._remove();
    }, _remove: function () {
        this._removeChildFrames();
        delete this._model._frames[this.id];
        this._model.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this);
    }, addResource: function (resource) {
        if (this._resourcesMap[resource.url] === resource) {
            return;
        }
        this._resourcesMap[resource.url] = resource;
        this._model.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, resource);
    }, _addRequest: function (request) {
        var resource = this._resourcesMap[request.url];
        if (resource && resource.request === request) {
            return resource;
        }
        resource = new WebInspector.Resource(this.target(), request, request.url, request.documentURL, request.frameId, request.loaderId, request.type, request.mimeType);
        this._resourcesMap[resource.url] = resource;
        this._model.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, resource);
        return resource;
    }, resources: function () {
        var result = [];
        for (var url in this._resourcesMap)
            result.push(this._resourcesMap[url]);
        return result;
    }, resourceForURL: function (url) {
        var result;

        function filter(resource) {
            if (resource.url === url) {
                result = resource;
                return true;
            }
        }

        this._callForFrameResources(filter);
        return result || null;
    }, _callForFrameResources: function (callback) {
        for (var url in this._resourcesMap) {
            if (callback(this._resourcesMap[url]))
                return true;
        }
        for (var i = 0; i < this._childFrames.length; ++i) {
            if (this._childFrames[i]._callForFrameResources(callback))
                return true;
        }
        return false;
    }, displayName: function () {
        if (!this._parentFrame)
            return WebInspector.UIString("<top frame>");
        var subtitle = new WebInspector.ParsedURL(this._url).displayName;
        if (subtitle) {
            if (!this._name)
                return subtitle;
            return this._name + "( " + subtitle + " )";
        }
        return WebInspector.UIString("<iframe>");
    }
}
WebInspector.PageDispatcher = function (resourceTreeModel) {
    this._resourceTreeModel = resourceTreeModel;
}
WebInspector.PageDispatcher.prototype = {
    domContentEventFired: function (time) {
        this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.DOMContentLoaded, time);
    }, loadEventFired: function (time) {
        this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.Load, time);
    }, frameAttached: function (frameId, parentFrameId) {
        this._resourceTreeModel._frameAttached(frameId, parentFrameId);
    }, frameNavigated: function (frame) {
        this._resourceTreeModel._frameNavigated(frame);
    }, frameDetached: function (frameId) {
        this._resourceTreeModel._frameDetached(frameId);
    }, frameStartedLoading: function (frameId) {
    }, frameStoppedLoading: function (frameId) {
    }, frameScheduledNavigation: function (frameId, delay) {
    }, frameClearedScheduledNavigation: function (frameId) {
    }, frameResized: function () {
        this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.FrameResized, null);
    }, javascriptDialogOpening: function (message) {
    }, javascriptDialogClosed: function () {
    }, scriptsEnabled: function (isEnabled) {
        WebInspector.settings.javaScriptDisabled.set(!isEnabled);
    }, screencastFrame: function (data, metadata) {
        this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ScreencastFrame, {data: data, metadata: metadata});
    }, screencastVisibilityChanged: function (visible) {
        this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ScreencastVisibilityChanged, {visible: visible});
    }, viewportChanged: function (viewport) {
        this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ViewportChanged, viewport);
    }
}
WebInspector.resourceTreeModel;
WebInspector.resourceForURL = function (url) {
    return WebInspector.resourceTreeModel.resourceForURL(url);
}
WebInspector.forAllResources = function (callback) {
    WebInspector.resourceTreeModel.forAllResources(callback);
}
WebInspector.displayNameForURL = function (url) {
    if (!url)
        return "";
    var resource = WebInspector.resourceForURL(url);
    if (resource)
        return resource.displayName;
    var uiSourceCode = WebInspector.workspace.uiSourceCodeForURL(url);
    if (uiSourceCode)
        return uiSourceCode.displayName();
    if (!WebInspector.resourceTreeModel.inspectedPageURL())
        return url.trimURL("");
    var parsedURL = WebInspector.resourceTreeModel.inspectedPageURL().asParsedURL();
    var lastPathComponent = parsedURL ? parsedURL.lastPathComponent : parsedURL;
    var index = WebInspector.resourceTreeModel.inspectedPageURL().indexOf(lastPathComponent);
    if (index !== -1 && index + lastPathComponent.length === WebInspector.resourceTreeModel.inspectedPageURL().length) {
        var baseURL = WebInspector.resourceTreeModel.inspectedPageURL().substring(0, index);
        if (url.startsWith(baseURL))
            return url.substring(index);
    }
    if (!parsedURL)
        return url;
    var displayName = url.trimURL(parsedURL.host);
    return displayName === "/" ? parsedURL.host + "/" : displayName;
}
WebInspector.linkifyStringAsFragmentWithCustomLinkifier = function (string, linkifier) {
    var container = document.createDocumentFragment();
    var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|data:|www\.)[\w$\-_+*'=\|\/\\(){}[\]^%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({^%@&#~]/;
    var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
    while (string) {
        var linkString = linkStringRegEx.exec(string);
        if (!linkString)
            break;
        linkString = linkString[0];
        var linkIndex = string.indexOf(linkString);
        var nonLink = string.substring(0, linkIndex);
        container.appendChild(document.createTextNode(nonLink));
        var title = linkString;
        var realURL = (linkString.startsWith("www.") ? "http://" + linkString : linkString);
        var lineColumnMatch = lineColumnRegEx.exec(realURL);
        var lineNumber;
        var columnNumber;
        if (lineColumnMatch) {
            realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
            lineNumber = parseInt(lineColumnMatch[1], 10);
            lineNumber = isNaN(lineNumber) ? undefined : lineNumber - 1;
            if (typeof(lineColumnMatch[3]) === "string") {
                columnNumber = parseInt(lineColumnMatch[3], 10);
                columnNumber = isNaN(columnNumber) ? undefined : columnNumber - 1;
            }
        }
        var linkNode = linkifier(title, realURL, lineNumber, columnNumber);
        container.appendChild(linkNode);
        string = string.substring(linkIndex + linkString.length, string.length);
    }
    if (string)
        container.appendChild(document.createTextNode(string));
    return container;
}
WebInspector.linkifyStringAsFragment = function (string) {
    function linkifier(title, url, lineNumber, columnNumber) {
        var isExternal = !WebInspector.resourceForURL(url) && !WebInspector.workspace.uiSourceCodeForURL(url);
        var urlNode = WebInspector.linkifyURLAsNode(url, title, undefined, isExternal);
        if (typeof lineNumber !== "undefined") {
            urlNode.lineNumber = lineNumber;
            if (typeof columnNumber !== "undefined")
                urlNode.columnNumber = columnNumber;
        }
        return urlNode;
    }

    return WebInspector.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier);
}
WebInspector.linkifyURLAsNode = function (url, linkText, classes, isExternal, tooltipText) {
    if (!linkText)
        linkText = url;
    classes = (classes ? classes + " " : "");
    classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link";
    var a = document.createElement("a");
    var href = sanitizeHref(url);
    if (href !== null)
        a.href = href;
    a.className = classes;
    if (typeof tooltipText === "undefined")
        a.title = url; else if (typeof tooltipText !== "string" || tooltipText.length)
        a.title = tooltipText;
    a.textContent = linkText.trimMiddle(WebInspector.Linkifier.MaxLengthForDisplayedURLs);
    if (isExternal)
        a.setAttribute("target", "_blank");
    return a;
}
WebInspector.formatLinkText = function (url, lineNumber) {
    var text = url ? WebInspector.displayNameForURL(url) : WebInspector.UIString("(program)");
    if (typeof lineNumber === "number")
        text += ":" + (lineNumber + 1);
    return text;
}
WebInspector.linkifyResourceAsNode = function (url, lineNumber, classes, tooltipText) {
    var linkText = WebInspector.formatLinkText(url, lineNumber);
    var anchor = WebInspector.linkifyURLAsNode(url, linkText, classes, false, tooltipText);
    anchor.lineNumber = lineNumber;
    return anchor;
}
WebInspector.linkifyRequestAsNode = function (request) {
    var anchor = WebInspector.linkifyURLAsNode(request.url);
    anchor.requestId = request.requestId;
    return anchor;
}
WebInspector.ResourceType = function (name, title, categoryTitle, color, isTextType) {
    this._name = name;
    this._title = title;
    this._categoryTitle = categoryTitle;
    this._color = color;
    this._isTextType = isTextType;
}
WebInspector.ResourceType.prototype = {
    name: function () {
        return this._name;
    }, title: function () {
        return this._title;
    }, categoryTitle: function () {
        return this._categoryTitle;
    }, color: function () {
        return this._color;
    }, isTextType: function () {
        return this._isTextType;
    }, toString: function () {
        return this._name;
    }, canonicalMimeType: function () {
        if (this === WebInspector.resourceTypes.Document)
            return "text/html";
        if (this === WebInspector.resourceTypes.Script)
            return "text/javascript";
        if (this === WebInspector.resourceTypes.Stylesheet)
            return "text/css";
        return "";
    }
}
WebInspector.resourceTypes = {
    Document: new WebInspector.ResourceType("document", "Document", "Documents", "rgb(47,102,236)", true),
    Stylesheet: new WebInspector.ResourceType("stylesheet", "Stylesheet", "Stylesheets", "rgb(157,231,119)", true),
    Image: new WebInspector.ResourceType("image", "Image", "Images", "rgb(164,60,255)", false),
    Media: new WebInspector.ResourceType("media", "Media", "Media", "rgb(164,60,255)", false),
    Script: new WebInspector.ResourceType("script", "Script", "Scripts", "rgb(255,121,0)", true),
    XHR: new WebInspector.ResourceType("xhr", "XHR", "XHR", "rgb(231,231,10)", true),
    Font: new WebInspector.ResourceType("font", "Font", "Fonts", "rgb(255,82,62)", false),
    TextTrack: new WebInspector.ResourceType("texttrack", "TextTrack", "TextTracks", "rgb(164,60,255)", true),
    WebSocket: new WebInspector.ResourceType("websocket", "WebSocket", "WebSockets", "rgb(186,186,186)", false),
    Other: new WebInspector.ResourceType("other", "Other", "Other", "rgb(186,186,186)", false)
}
WebInspector.ResourceType.mimeTypesForExtensions = {
    "js": "text/javascript",
    "css": "text/css",
    "html": "text/html",
    "htm": "text/html",
    "xml": "application/xml",
    "xsl": "application/xml",
    "asp": "application/x-aspx",
    "aspx": "application/x-aspx",
    "jsp": "application/x-jsp",
    "c": "text/x-c++src",
    "cc": "text/x-c++src",
    "cpp": "text/x-c++src",
    "h": "text/x-c++src",
    "m": "text/x-c++src",
    "mm": "text/x-c++src",
    "coffee": "text/x-coffeescript",
    "dart": "text/javascript",
    "ts": "text/typescript",
    "json": "application/json",
    "gyp": "application/json",
    "gypi": "application/json",
    "cs": "text/x-csharp",
    "java": "text/x-java",
    "php": "text/x-php",
    "phtml": "application/x-httpd-php",
    "py": "text/x-python",
    "sh": "text/x-sh",
    "scss": "text/x-scss",
    "vtt": "text/vtt"
}
WebInspector.TimelineManager = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.TimelineManager, target);
    this._dispatcher = new WebInspector.TimelineDispatcher(this);
    this._enablementCount = 0;
    this._jsProfilerStarted = false;
    target.timelineAgent().enable();
}
WebInspector.TimelineManager.EventTypes = {TimelineStarted: "TimelineStarted", TimelineStopped: "TimelineStopped", TimelineEventRecorded: "TimelineEventRecorded", TimelineProgress: "TimelineProgress"}
WebInspector.TimelineManager.prototype = {
    isStarted: function () {
        return this._dispatcher.isStarted();
    }, start: function (maxCallStackDepth, liveEvents, includeCounters, includeGPUEvents, callback) {
        this._enablementCount++;
        WebInspector.profilingLock().acquire();
        if (WebInspector.experimentsSettings.timelineJSCPUProfile.isEnabled() && maxCallStackDepth) {
            this._configureCpuProfilerSamplingInterval();
            this._jsProfilerStarted = true;
            this.target().profilerAgent().start();
        }
        if (this._enablementCount === 1)
            this.target().timelineAgent().start(maxCallStackDepth, true, liveEvents, includeCounters, includeGPUEvents, callback); else if (callback)
            callback(null);
    }, stop: function (callback) {
        this._enablementCount--;
        if (this._enablementCount < 0) {
            console.error("WebInspector.TimelineManager start/stop calls are unbalanced " + new Error().stack);
            return;
        }
        var masterError = null;
        var masterProfile = null;
        var callbackBarrier = new CallbackBarrier();
        if (this._jsProfilerStarted) {
            this.target().profilerAgent().stop(callbackBarrier.createCallback(profilerCallback));
            this._jsProfilerStarted = false;
        }
        if (!this._enablementCount)
            this.target().timelineAgent().stop(callbackBarrier.createCallback(timelineCallback));
        callbackBarrier.callWhenDone(allDoneCallback);
        function timelineCallback(error) {
            masterError = masterError || error;
        }

        function profilerCallback(error, profile) {
            masterError = masterError || error;
            masterProfile = profile;
        }

        function allDoneCallback() {
            WebInspector.profilingLock().release();
            callback(masterError, masterProfile);
        }
    }, _stopped: function (consoleTimeline, events) {
        var data = {consoleTimeline: consoleTimeline, events: events || []};
        this.dispatchEventToListeners(WebInspector.TimelineManager.EventTypes.TimelineStopped, data);
    }, _configureCpuProfilerSamplingInterval: function () {
        var intervalUs = WebInspector.settings.highResolutionCpuProfiling.get() ? 100 : 1000;
        this.target().profilerAgent().setSamplingInterval(intervalUs, didChangeInterval);
        function didChangeInterval(error) {
            if (error)
                WebInspector.console.error(error);
        }
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.TimelineDispatcher = function (manager) {
    this._manager = manager;
    this._manager.target().registerTimelineDispatcher(this);
}
WebInspector.TimelineDispatcher.prototype = {
    eventRecorded: function (record) {
        this._manager.dispatchEventToListeners(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded, record);
    }, isStarted: function () {
        return !!this._started;
    }, started: function (consoleTimeline) {
        if (consoleTimeline) {
            self.runtime.loadModule("timeline");
        }
        this._started = true;
        this._manager.dispatchEventToListeners(WebInspector.TimelineManager.EventTypes.TimelineStarted, consoleTimeline);
    }, stopped: function (consoleTimeline, events) {
        this._started = false;
        this._manager._stopped(consoleTimeline, events);
    }, progress: function (count) {
        this._manager.dispatchEventToListeners(WebInspector.TimelineManager.EventTypes.TimelineProgress, count);
    }
}
WebInspector.TracingModel = function (target) {
    WebInspector.SDKObject.call(this, target);
    this.reset();
    this._active = false;
    InspectorBackend.registerTracingDispatcher(new WebInspector.TracingDispatcher(this));
}
WebInspector.TracingModel.Events = {"BufferUsage": "BufferUsage", "TracingStarted": "TracingStarted", "TracingStopped": "TracingStopped", "TracingComplete": "TracingComplete"}
WebInspector.TracingModel.EventPayload;
WebInspector.TracingModel.Phase = {
    Begin: "B",
    End: "E",
    Complete: "X",
    Instant: "i",
    AsyncBegin: "S",
    AsyncStepInto: "T",
    AsyncStepPast: "p",
    AsyncEnd: "F",
    FlowBegin: "s",
    FlowStep: "t",
    FlowEnd: "f",
    Metadata: "M",
    Counter: "C",
    Sample: "P",
    CreateObject: "N",
    SnapshotObject: "O",
    DeleteObject: "D"
};
WebInspector.TracingModel.MetadataEvent = {ProcessSortIndex: "process_sort_index", ProcessName: "process_name", ThreadSortIndex: "thread_sort_index", ThreadName: "thread_name"}
WebInspector.TracingModel.DevToolsMetadataEventCategory = "disabled-by-default-devtools.timeline";
WebInspector.TracingModel.FrameLifecycleEventCategory = "cc,devtools";
WebInspector.TracingModel.DevToolsMetadataEvent = {TracingStartedInPage: "TracingStartedInPage", TracingStartedInWorker: "TracingStartedInWorker",};
WebInspector.TracingModel.prototype = {
    devtoolsPageMetadataEvents: function () {
        return this._devtoolsPageMetadataEvents;
    }, devtoolsWorkerMetadataEvents: function () {
        return this._devtoolsWorkerMetadataEvents;
    }, start: function (categoryFilter, options, callback) {
        WebInspector.profilingLock().acquire();
        this.reset();
        var bufferUsageReportingIntervalMs = 500;
        TracingAgent.start(categoryFilter, options, bufferUsageReportingIntervalMs, callback);
        this._active = true;
    }, stop: function () {
        if (!this._active)
            return;
        TracingAgent.end(this._onStop.bind(this));
        WebInspector.profilingLock().release();
    }, sessionId: function () {
        return this._sessionId;
    }, setEventsForTest: function (sessionId, events) {
        this.reset();
        this._sessionId = sessionId;
        this._eventsCollected(events);
    }, _bufferUsage: function (usage) {
        this.dispatchEventToListeners(WebInspector.TracingModel.Events.BufferUsage, usage);
    }, _eventsCollected: function (events) {
        for (var i = 0; i < events.length; ++i) {
            this._addEvent(events[i]);
            this._rawEvents.push(events[i]);
        }
    }, _tracingComplete: function () {
        this._active = false;
        this.dispatchEventToListeners(WebInspector.TracingModel.Events.TracingComplete);
    }, _tracingStarted: function (sessionId) {
        this.reset();
        this._active = true;
        this._sessionId = sessionId;
        this.dispatchEventToListeners(WebInspector.TracingModel.Events.TracingStarted);
    }, _onStop: function () {
        this.dispatchEventToListeners(WebInspector.TracingModel.Events.TracingStopped);
        this._active = false;
    }, reset: function () {
        this._processById = {};
        this._minimumRecordTime = 0;
        this._maximumRecordTime = 0;
        this._sessionId = null;
        this._devtoolsPageMetadataEvents = [];
        this._devtoolsWorkerMetadataEvents = [];
        this._rawEvents = [];
    }, rawEvents: function () {
        return this._rawEvents;
    }, _addEvent: function (payload) {
        var process = this._processById[payload.pid];
        if (!process) {
            process = new WebInspector.TracingModel.Process(payload.pid);
            this._processById[payload.pid] = process;
        }
        var thread = process.threadById(payload.tid);
        if (payload.ph !== WebInspector.TracingModel.Phase.Metadata) {
            var timestamp = payload.ts / 1000;
            if (timestamp && (!this._minimumRecordTime || timestamp < this._minimumRecordTime))
                this._minimumRecordTime = timestamp;
            if (!this._maximumRecordTime || timestamp > this._maximumRecordTime)
                this._maximumRecordTime = timestamp;
            var event = thread.addEvent(payload);
            if (payload.ph === WebInspector.TracingModel.Phase.SnapshotObject)
                process.addObject(event);
            if (event && event.name === WebInspector.TracingModel.DevToolsMetadataEvent.TracingStartedInPage && event.category === WebInspector.TracingModel.DevToolsMetadataEventCategory && event.args["sessionId"] === this._sessionId)
                this._devtoolsPageMetadataEvents.push(event);
            if (event && event.name === WebInspector.TracingModel.DevToolsMetadataEvent.TracingStartedInWorker && event.category === WebInspector.TracingModel.DevToolsMetadataEventCategory && event.args["sessionId"] === this._sessionId)
                this._devtoolsWorkerMetadataEvents.push(event);
            return;
        }
        switch (payload.name) {
            case WebInspector.TracingModel.MetadataEvent.ProcessSortIndex:
                process._setSortIndex(payload.args["sort_index"]);
                break;
            case WebInspector.TracingModel.MetadataEvent.ProcessName:
                process._setName(payload.args["name"]);
                break;
            case WebInspector.TracingModel.MetadataEvent.ThreadSortIndex:
                thread._setSortIndex(payload.args["sort_index"]);
                break;
            case WebInspector.TracingModel.MetadataEvent.ThreadName:
                thread._setName(payload.args["name"]);
                break;
        }
    }, minimumRecordTime: function () {
        return this._minimumRecordTime;
    }, maximumRecordTime: function () {
        return this._maximumRecordTime;
    }, sortedProcesses: function () {
        return WebInspector.TracingModel.NamedObject._sort(Object.values(this._processById));
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.TracingModel.Loader = function (tracingModel) {
    this._tracingModel = tracingModel;
    this._events = [];
    this._sessionIdFound = false;
}
WebInspector.TracingModel.Loader.prototype = {
    loadNextChunk: function (events) {
        if (this._sessionIdFound) {
            this._tracingModel._eventsCollected(events);
            return;
        }
        var sessionId = null;
        for (var i = 0, length = events.length; i < length; i++) {
            var event = events[i];
            this._events.push(event);
            if (event.name === WebInspector.TracingModel.DevToolsMetadataEvent.TracingStartedInPage && event.cat.indexOf(WebInspector.TracingModel.DevToolsMetadataEventCategory) !== -1 && !this._sessionIdFound) {
                sessionId = event.args["sessionId"];
                this._sessionIdFound = true;
            }
        }
        if (this._sessionIdFound) {
            this._tracingModel._tracingStarted(sessionId);
            this._tracingModel._eventsCollected(this._events);
        }
    }, finish: function () {
        if (this._sessionIdFound)
            this._tracingModel._tracingComplete(); else
            WebInspector.console.error(WebInspector.UIString("Trace event %s not found while loading tracing model.", WebInspector.TracingModel.DevToolsMetadataEvent.TracingStartedInPage));
    }
}
WebInspector.TracingModel.Event = function (payload, level, thread) {
    this.name = payload.name;
    this.category = payload.cat;
    this.startTime = payload.ts / 1000;
    if (payload.args) {
        this.args = {};
        for (var name in payload.args)
            this.args[name] = payload.args[name];
    }
    this.phase = payload.ph;
    this.level = level;
    if (typeof payload.dur === "number")
        this._setEndTime((payload.ts + payload.dur) / 1000);
    if (payload.id)
        this.id = payload.id;
    this.thread = thread;
    this.warning = null;
    this.initiator = null;
    this.stackTrace = null;
    this.previewElement = null;
    this.imageURL = null;
    this.backendNodeId = 0;
    this.selfTime = 0;
}
WebInspector.TracingModel.Event.prototype = {
    _setEndTime: function (endTime) {
        if (endTime < this.startTime) {
            console.assert(false, "Event out of order: " + this.name);
            return;
        }
        this.endTime = endTime;
        this.duration = endTime - this.startTime;
    }, _complete: function (payload) {
        if (this.name !== payload.name) {
            console.assert(false, "Open/close event mismatch: " + this.name + " vs. " + payload.name + " at " + (payload.ts / 1000));
            return;
        }
        if (payload.args) {
            for (var name in payload.args) {
                if (name in this.args)
                    console.error("Same argument name (" + name + ") is used for begin and end phases of " + this.name);
                this.args[name] = payload.args[name];
            }
        }
        this._setEndTime(payload.ts / 1000);
    }
}
WebInspector.TracingModel.Event.compareStartTime = function (a, b) {
    return a.startTime - b.startTime;
}
WebInspector.TracingModel.Event.orderedCompareStartTime = function (a, b) {
    return a.startTime - b.startTime || -1;
}
WebInspector.TracingModel.NamedObject = function () {
}
WebInspector.TracingModel.NamedObject.prototype = {
    _setName: function (name) {
        this._name = name;
    }, name: function () {
        return this._name;
    }, _setSortIndex: function (sortIndex) {
        this._sortIndex = sortIndex;
    },
}
WebInspector.TracingModel.NamedObject._sort = function (array) {
    function comparator(a, b) {
        return a._sortIndex !== b._sortIndex ? a._sortIndex - b._sortIndex : a.name().localeCompare(b.name());
    }

    return array.sort(comparator);
}
WebInspector.TracingModel.Process = function (id) {
    WebInspector.TracingModel.NamedObject.call(this);
    this._setName("Process " + id);
    this._threads = {};
    this._objects = {};
}
WebInspector.TracingModel.Process.prototype = {
    threadById: function (id) {
        var thread = this._threads[id];
        if (!thread) {
            thread = new WebInspector.TracingModel.Thread(this, id);
            this._threads[id] = thread;
        }
        return thread;
    }, addObject: function (event) {
        this.objectsByName(event.name).push(event);
    }, objectsByName: function (name) {
        var objects = this._objects[name];
        if (!objects) {
            objects = [];
            this._objects[name] = objects;
        }
        return objects;
    }, sortedObjectNames: function () {
        return Object.keys(this._objects).sort();
    }, sortedThreads: function () {
        return WebInspector.TracingModel.NamedObject._sort(Object.values(this._threads));
    }, __proto__: WebInspector.TracingModel.NamedObject.prototype
}
WebInspector.TracingModel.Thread = function (process, id) {
    WebInspector.TracingModel.NamedObject.call(this);
    this._process = process;
    this._setName("Thread " + id);
    this._events = [];
    this._stack = [];
    this._maxStackDepth = 0;
}
WebInspector.TracingModel.Thread.prototype = {
    target: function () {
        return WebInspector.targetManager.targets()[0];
    }, addEvent: function (payload) {
        var timestamp = payload.ts / 1000;
        for (var top = this._stack.peekLast(); top;) {
            if (payload.ph === WebInspector.TracingModel.Phase.End) {
                if (payload.name === top.name) {
                    top._complete(payload);
                    this._stack.pop();
                    return null;
                }
            } else if (top.phase === WebInspector.TracingModel.Phase.Begin || (top.endTime && (top.endTime > timestamp))) {
                break;
            }
            this._stack.pop();
            top = this._stack.peekLast();
        }
        if (payload.ph === WebInspector.TracingModel.Phase.End)
            return null;
        var event = new WebInspector.TracingModel.Event(payload, this._stack.length, this);
        if (payload.ph === WebInspector.TracingModel.Phase.Begin || payload.ph === WebInspector.TracingModel.Phase.Complete) {
            this._stack.push(event);
            if (this._maxStackDepth < this._stack.length)
                this._maxStackDepth = this._stack.length;
        }
        if (this._events.length && this._events.peekLast().startTime > event.startTime)
            console.assert(false, "Event is our of order: " + event.name);
        this._events.push(event);
        return event;
    }, process: function () {
        return this._process;
    }, events: function () {
        return this._events;
    }, maxStackDepth: function () {
        return this._maxStackDepth + 1;
    }, __proto__: WebInspector.TracingModel.NamedObject.prototype
}
WebInspector.TracingDispatcher = function (tracingModel) {
    this._tracingModel = tracingModel;
}
WebInspector.TracingDispatcher.prototype = {
    bufferUsage: function (usage) {
        this._tracingModel._bufferUsage(usage);
    }, dataCollected: function (data) {
        this._tracingModel._eventsCollected(data);
    }, tracingComplete: function () {
        this._tracingModel._tracingComplete();
    }, started: function (consoleTimeline, sessionId) {
        this._tracingModel._tracingStarted(sessionId);
    }, stopped: function () {
        this._tracingModel._onStop();
    }
}
WebInspector.PowerProfiler = function () {
    WebInspector.Object.call(this);
    this._dispatcher = new WebInspector.PowerDispatcher(this);
    PowerAgent.getAccuracyLevel(this._onAccuracyLevel.bind(this));
}
WebInspector.PowerProfiler.EventTypes = {PowerEventRecorded: "PowerEventRecorded"}
WebInspector.PowerProfiler.prototype = {
    startProfile: function () {
        PowerAgent.start();
    }, stopProfile: function () {
        PowerAgent.end();
    }, getAccuracyLevel: function () {
        return this._accuracyLevel;
    }, _onAccuracyLevel: function (error, result) {
        this._accuracyLevel = "";
        if (error) {
            console.log("Unable to retrieve PowerProfiler accuracy level: " + error);
            return;
        }
        this._accuracyLevel = result;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.PowerDispatcher = function (profiler) {
    this._profiler = profiler;
    InspectorBackend.registerPowerDispatcher(this);
}
WebInspector.PowerDispatcher.prototype = {
    dataAvailable: function (events) {
        for (var i = 0; i < events.length; ++i)
            this._profiler.dispatchEventToListeners(WebInspector.PowerProfiler.EventTypes.PowerEventRecorded, events[i]);
    }
}
WebInspector.powerProfiler;
WebInspector.OverridesSupport = function (responsiveDesignAvailable) {
    this._touchEmulationSuspended = false;
    this._emulateMobileEnabled = false;
    this._userAgent = "";
    this._pageResizer = null;
    this._deviceScale = 1;
    this._fixedDeviceScale = false;
    this._initialized = false;
    this._deviceMetricsThrottler = new WebInspector.Throttler(0);
    this._responsiveDesignAvailable = responsiveDesignAvailable;
    this.settings = {};
    this.settings._emulationEnabled = WebInspector.settings.createSetting("emulationEnabled", false);
    this.settings.userAgent = WebInspector.settings.createSetting("userAgent", "");
    this.settings.emulateResolution = WebInspector.settings.createSetting("emulateResolution", true);
    this.settings.deviceWidth = WebInspector.settings.createSetting("deviceWidth", 360);
    this.settings.deviceHeight = WebInspector.settings.createSetting("deviceHeight", 640);
    this.settings.deviceScaleFactor = WebInspector.settings.createSetting("deviceScaleFactor", 0);
    this.settings.deviceFitWindow = WebInspector.settings.createSetting("deviceFitWindow", true);
    this.settings.emulateMobile = WebInspector.settings.createSetting("emulateMobile", false);
    this.settings.customDevicePresets = WebInspector.settings.createSetting("customDevicePresets", []);
    this.settings.emulateTouch = WebInspector.settings.createSetting("emulateTouch", false);
    this.settings.overrideGeolocation = WebInspector.settings.createSetting("overrideGeolocation", false);
    this.settings.geolocationOverride = WebInspector.settings.createSetting("geolocationOverride", "");
    this.settings.overrideDeviceOrientation = WebInspector.settings.createSetting("overrideDeviceOrientation", false);
    this.settings.deviceOrientationOverride = WebInspector.settings.createSetting("deviceOrientationOverride", "");
    this.settings.overrideCSSMedia = WebInspector.settings.createSetting("overrideCSSMedia", false);
    this.settings.emulatedCSSMedia = WebInspector.settings.createSetting("emulatedCSSMedia", "print");
    this.settings.networkConditions = WebInspector.settings.createSetting("networkConditions", {throughput: WebInspector.OverridesSupport.NetworkThroughputUnlimitedValue, latency: 0});
    WebInspector.targetManager.observeTargets(this);
}
WebInspector.OverridesSupport.Events = {OverridesWarningUpdated: "OverridesWarningUpdated", EmulationStateChanged: "EmulationStateChanged"}
WebInspector.OverridesSupport.MaxDeviceSize = 3000;
WebInspector.OverridesSupport.PageResizer = function () {
};
WebInspector.OverridesSupport.PageResizer.Events = {AvailableSizeChanged: "AvailableSizeChanged", ResizeRequested: "ResizeRequested", FixedScaleRequested: "FixedScaleRequested"};
WebInspector.OverridesSupport.PageResizer.prototype = {
    update: function (dipWidth, dipHeight, scale) {
    }
};
WebInspector.OverridesSupport.Device = {};
WebInspector.OverridesSupport.GeolocationPosition = function (latitude, longitude, error) {
    this.latitude = latitude;
    this.longitude = longitude;
    this.error = error;
}
WebInspector.OverridesSupport.GeolocationPosition.prototype = {
    toSetting: function () {
        return (typeof this.latitude === "number" && typeof this.longitude === "number" && typeof this.error === "string") ? this.latitude + "@" + this.longitude + ":" + this.error : "";
    }
}
WebInspector.OverridesSupport.GeolocationPosition.parseSetting = function (value) {
    if (value) {
        var splitError = value.split(":");
        if (splitError.length === 2) {
            var splitPosition = splitError[0].split("@")
            if (splitPosition.length === 2)
                return new WebInspector.OverridesSupport.GeolocationPosition(parseFloat(splitPosition[0]), parseFloat(splitPosition[1]), splitError[1]);
        }
    }
    return new WebInspector.OverridesSupport.GeolocationPosition(0, 0, "");
}
WebInspector.OverridesSupport.GeolocationPosition.parseUserInput = function (latitudeString, longitudeString, errorStatus) {
    function isUserInputValid(value) {
        if (!value)
            return true;
        return /^[-]?[0-9]*[.]?[0-9]*$/.test(value);
    }

    if (!latitudeString ^ !latitudeString)
        return null;
    var isLatitudeValid = isUserInputValid(latitudeString);
    var isLongitudeValid = isUserInputValid(longitudeString);
    if (!isLatitudeValid && !isLongitudeValid)
        return null;
    var latitude = isLatitudeValid ? parseFloat(latitudeString) : -1;
    var longitude = isLongitudeValid ? parseFloat(longitudeString) : -1;
    return new WebInspector.OverridesSupport.GeolocationPosition(latitude, longitude, errorStatus ? "PositionUnavailable" : "");
}
WebInspector.OverridesSupport.GeolocationPosition.clearGeolocationOverride = function () {
    GeolocationAgent.clearGeolocationOverride();
}
WebInspector.OverridesSupport.DeviceOrientation = function (alpha, beta, gamma) {
    this.alpha = alpha;
    this.beta = beta;
    this.gamma = gamma;
}
WebInspector.OverridesSupport.DeviceOrientation.prototype = {
    toSetting: function () {
        return JSON.stringify(this);
    }
}
WebInspector.OverridesSupport.DeviceOrientation.parseSetting = function (value) {
    if (value) {
        var jsonObject = JSON.parse(value);
        return new WebInspector.OverridesSupport.DeviceOrientation(jsonObject.alpha, jsonObject.beta, jsonObject.gamma);
    }
    return new WebInspector.OverridesSupport.DeviceOrientation(0, 0, 0);
}
WebInspector.OverridesSupport.DeviceOrientation.parseUserInput = function (alphaString, betaString, gammaString) {
    function isUserInputValid(value) {
        if (!value)
            return true;
        return /^[-]?[0-9]*[.]?[0-9]*$/.test(value);
    }

    if (!alphaString ^ !betaString ^ !gammaString)
        return null;
    var isAlphaValid = isUserInputValid(alphaString);
    var isBetaValid = isUserInputValid(betaString);
    var isGammaValid = isUserInputValid(gammaString);
    if (!isAlphaValid && !isBetaValid && !isGammaValid)
        return null;
    var alpha = isAlphaValid ? parseFloat(alphaString) : -1;
    var beta = isBetaValid ? parseFloat(betaString) : -1;
    var gamma = isGammaValid ? parseFloat(gammaString) : -1;
    return new WebInspector.OverridesSupport.DeviceOrientation(alpha, beta, gamma);
}
WebInspector.OverridesSupport.DeviceOrientation.clearDeviceOrientationOverride = function () {
    PageAgent.clearDeviceOrientationOverride();
}
WebInspector.OverridesSupport.deviceSizeValidator = function (value) {
    if (!value || (/^[\d]+$/.test(value) && value >= 0 && value <= WebInspector.OverridesSupport.MaxDeviceSize))
        return "";
    return WebInspector.UIString("Value must be non-negative integer");
}
WebInspector.OverridesSupport.deviceScaleFactorValidator = function (value) {
    if (!value || (/^[\d]+(\.\d+)?|\.\d+$/.test(value) && value >= 0 && value <= 10))
        return "";
    return WebInspector.UIString("Value must be non-negative float");
}
WebInspector.OverridesSupport.NetworkThroughputUnlimitedValue = -1;
WebInspector.OverridesSupport.NetworkConditionsPreset;
WebInspector.OverridesSupport.prototype = {
    canEmulate: function () {
        return !!this._target && !this._target.isMobile();
    }, emulationEnabled: function () {
        return this.canEmulate() && this.settings._emulationEnabled.get();
    }, setEmulationEnabled: function (enabled) {
        if (this.canEmulate()) {
            this.settings._emulationEnabled.set(enabled);
            this.dispatchEventToListeners(WebInspector.OverridesSupport.Events.EmulationStateChanged);
            if (enabled && this.settings.emulateResolution.get())
                this._target.pageAgent().resetScrollAndPageScaleFactor();
        }
    }, responsiveDesignAvailable: function () {
        return this._responsiveDesignAvailable;
    }, setPageResizer: function (pageResizer, availableSize) {
        if (pageResizer === this._pageResizer)
            return;
        if (this._pageResizer) {
            this._pageResizer.removeEventListener(WebInspector.OverridesSupport.PageResizer.Events.AvailableSizeChanged, this._onPageResizerAvailableSizeChanged, this);
            this._pageResizer.removeEventListener(WebInspector.OverridesSupport.PageResizer.Events.ResizeRequested, this._onPageResizerResizeRequested, this);
            this._pageResizer.removeEventListener(WebInspector.OverridesSupport.PageResizer.Events.FixedScaleRequested, this._onPageResizerFixedScaleRequested, this);
        }
        this._pageResizer = pageResizer;
        this._pageResizerAvailableSize = availableSize;
        if (this._pageResizer) {
            this._pageResizer.addEventListener(WebInspector.OverridesSupport.PageResizer.Events.AvailableSizeChanged, this._onPageResizerAvailableSizeChanged, this);
            this._pageResizer.addEventListener(WebInspector.OverridesSupport.PageResizer.Events.ResizeRequested, this._onPageResizerResizeRequested, this);
            this._pageResizer.addEventListener(WebInspector.OverridesSupport.PageResizer.Events.FixedScaleRequested, this._onPageResizerFixedScaleRequested, this);
        }
        if (this._initialized)
            this._deviceMetricsChanged();
    }, emulateDevice: function (device) {
        this._deviceMetricsChangedListenerMuted = true;
        this._userAgentChangedListenerMuted = true;
        this.settings.userAgent.set(device.userAgent);
        this.settings.emulateResolution.set(true);
        this.settings.deviceWidth.set(device.width);
        this.settings.deviceHeight.set(device.height);
        this.settings.deviceScaleFactor.set(device.deviceScaleFactor);
        this.settings.emulateTouch.set(device.touch);
        this.settings.emulateMobile.set(device.mobile);
        delete this._deviceMetricsChangedListenerMuted;
        delete this._userAgentChangedListenerMuted;
        if (this._initialized) {
            this._deviceMetricsChanged();
            this._userAgentChanged();
            this._target.pageAgent().resetScrollAndPageScaleFactor();
        }
    }, reset: function () {
        this._deviceMetricsChangedListenerMuted = true;
        this._userAgentChangedListenerMuted = true;
        this.settings.userAgent.set("");
        this.settings.emulateResolution.set(false);
        this.settings.deviceScaleFactor.set(0);
        this.settings.emulateTouch.set(false);
        this.settings.emulateMobile.set(false);
        this.settings.overrideDeviceOrientation.set(false);
        this.settings.overrideGeolocation.set(false);
        this.settings.overrideCSSMedia.set(false);
        this.settings.networkConditions.set({throughput: WebInspector.OverridesSupport.NetworkThroughputUnlimitedValue, latency: 0});
        delete this._deviceMetricsChangedListenerMuted;
        delete this._userAgentChangedListenerMuted;
        if (this._initialized) {
            this._deviceMetricsChanged();
            this._userAgentChanged();
        }
    }, isEmulatingDevice: function (device) {
        var sameResolution = this.settings.emulateResolution.get() ? (this.settings.deviceWidth.get() === device.width && this.settings.deviceHeight.get() === device.height && this.settings.deviceScaleFactor.get() === device.deviceScaleFactor) : (!device.width && !device.height && !device.deviceScaleFactor);
        return this.settings.userAgent.get() === device.userAgent && this.settings.emulateTouch.get() === device.touch && this.settings.emulateMobile.get() === device.mobile && sameResolution;
    }, deviceFromCurrentSettings: function () {
        var device = {};
        if (this.settings.emulateResolution.get()) {
            device.width = this.settings.deviceWidth.get();
            device.height = this.settings.deviceHeight.get();
        } else {
            device.width = 0;
            device.height = 0;
        }
        device.deviceScaleFactor = this.settings.deviceScaleFactor.get();
        device.touch = this.settings.emulateTouch.get();
        device.mobile = this.settings.emulateMobile.get();
        device.userAgent = this.settings.userAgent.get();
        device.title = "";
        return device;
    }, setTouchEmulationSuspended: function (suspended) {
        this._touchEmulationSuspended = suspended;
        if (this._initialized)
            this._emulateTouchEventsChanged();
    }, applyInitialOverrides: function () {
        if (!this._target) {
            this._applyInitialOverridesOnTargetAdded = true;
            return;
        }
        this._initialized = true;
        this.settings._emulationEnabled.addChangeListener(this._userAgentChanged, this);
        this.settings.userAgent.addChangeListener(this._userAgentChanged, this);
        this.settings._emulationEnabled.addChangeListener(this._deviceMetricsChanged, this);
        this.settings.emulateResolution.addChangeListener(this._deviceMetricsChanged, this);
        this.settings.deviceWidth.addChangeListener(this._deviceMetricsChanged, this);
        this.settings.deviceHeight.addChangeListener(this._deviceMetricsChanged, this);
        this.settings.deviceScaleFactor.addChangeListener(this._deviceMetricsChanged, this);
        this.settings.emulateMobile.addChangeListener(this._deviceMetricsChanged, this);
        this.settings.deviceFitWindow.addChangeListener(this._deviceMetricsChanged, this);
        this.settings._emulationEnabled.addChangeListener(this._geolocationPositionChanged, this);
        this.settings.overrideGeolocation.addChangeListener(this._geolocationPositionChanged, this);
        this.settings.geolocationOverride.addChangeListener(this._geolocationPositionChanged, this);
        this.settings._emulationEnabled.addChangeListener(this._deviceOrientationChanged, this);
        this.settings.overrideDeviceOrientation.addChangeListener(this._deviceOrientationChanged, this);
        this.settings.deviceOrientationOverride.addChangeListener(this._deviceOrientationChanged, this);
        this.settings._emulationEnabled.addChangeListener(this._emulateTouchEventsChanged, this);
        this.settings.emulateTouch.addChangeListener(this._emulateTouchEventsChanged, this);
        this.settings._emulationEnabled.addChangeListener(this._cssMediaChanged, this);
        this.settings.overrideCSSMedia.addChangeListener(this._cssMediaChanged, this);
        this.settings.emulatedCSSMedia.addChangeListener(this._cssMediaChanged, this);
        this.settings._emulationEnabled.addChangeListener(this._networkConditionsChanged, this);
        this.settings.networkConditions.addChangeListener(this._networkConditionsChanged, this);
        this.settings._emulationEnabled.addChangeListener(this._showRulersChanged, this);
        WebInspector.settings.showMetricsRulers.addChangeListener(this._showRulersChanged, this);
        this._showRulersChanged();
        WebInspector.settings.disableOverridesWarning.addChangeListener(this._dispatchWarningChanged, this);
        if (!this.emulationEnabled())
            return;
        if (this.settings.overrideDeviceOrientation.get())
            this._deviceOrientationChanged();
        if (this.settings.overrideGeolocation.get())
            this._geolocationPositionChanged();
        if (this.settings.emulateTouch.get())
            this._emulateTouchEventsChanged();
        if (this.settings.overrideCSSMedia.get())
            this._cssMediaChanged();
        this._deviceMetricsChanged();
        if (this.settings.emulateResolution.get())
            this._target.pageAgent().resetScrollAndPageScaleFactor();
        this._userAgentChanged();
        if (this.networkThroughputIsLimited())
            this._networkConditionsChanged();
    }, _userAgentChanged: function () {
        if (this._userAgentChangedListenerMuted)
            return;
        var userAgent = this.emulationEnabled() ? this.settings.userAgent.get() : "";
        NetworkAgent.setUserAgentOverride(userAgent);
        if (this._userAgent !== userAgent)
            this._updateUserAgentWarningMessage(WebInspector.UIString("You might need to reload the page for proper user agent spoofing and viewport rendering."));
        this._userAgent = userAgent;
    }, _onPageResizerAvailableSizeChanged: function (event) {
        this._pageResizerAvailableSize = (event.data);
        if (this._initialized)
            this._deviceMetricsChanged();
    }, _onPageResizerResizeRequested: function (event) {
        if (typeof event.data.width !== "undefined") {
            var width = (event.data.width);
            if (width !== this.settings.deviceWidth.get())
                this.settings.deviceWidth.set(width);
        }
        if (typeof event.data.height !== "undefined") {
            var height = (event.data.height);
            if (height !== this.settings.deviceHeight.get())
                this.settings.deviceHeight.set(height);
        }
    }, _onPageResizerFixedScaleRequested: function (event) {
        this._fixedDeviceScale = (event.data);
        if (this._initialized)
            this._deviceMetricsChanged();
    }, _deviceMetricsChanged: function () {
        this._showRulersChanged();
        if (this._deviceMetricsChangedListenerMuted)
            return;
        if (!this.emulationEnabled()) {
            this._deviceMetricsThrottler.schedule(clearDeviceMetricsOverride.bind(this));
            if (this._pageResizer)
                this._pageResizer.update(0, 0, 1);
            return;
        }
        var dipWidth = this.settings.emulateResolution.get() ? this.settings.deviceWidth.get() : 0;
        var dipHeight = this.settings.emulateResolution.get() ? this.settings.deviceHeight.get() : 0;
        var overrideWidth = dipWidth;
        var overrideHeight = dipHeight;
        var scale = 1;
        if (this._pageResizer) {
            var available = this._pageResizerAvailableSize;
            if (this.settings.deviceFitWindow.get()) {
                if (this._fixedDeviceScale) {
                    scale = this._deviceScale;
                } else {
                    scale = 1;
                    while (available.width < dipWidth * scale || available.height < dipHeight * scale)
                        scale *= 0.8;
                }
            }
            this._pageResizer.update(Math.min(dipWidth * scale, available.width), Math.min(dipHeight * scale, available.height), scale);
            if (scale === 1 && available.width >= dipWidth && available.height >= dipHeight) {
                overrideWidth = 0;
                overrideHeight = 0;
            }
            if (dipWidth === 0 && dipHeight !== 0)
                overrideWidth = Math.round(available.width / scale);
            if (dipHeight === 0 && dipWidth !== 0)
                overrideHeight = Math.round(available.height / scale);
        }
        this._deviceScale = scale;
        this._deviceMetricsThrottler.schedule(setDeviceMetricsOverride.bind(this));
        function setDeviceMetricsOverride(finishCallback) {
            this._target.pageAgent().setDeviceMetricsOverride(overrideWidth, overrideHeight, this.settings.emulateResolution.get() ? this.settings.deviceScaleFactor.get() : 0, this.settings.emulateMobile.get(), this._pageResizer ? false : this.settings.deviceFitWindow.get(), scale, 0, 0, apiCallback.bind(this, finishCallback));
        }

        function clearDeviceMetricsOverride(finishCallback) {
            this._target.pageAgent().clearDeviceMetricsOverride(apiCallback.bind(this, finishCallback));
        }

        function apiCallback(finishCallback, error) {
            if (error) {
                this._updateDeviceMetricsWarningMessage(WebInspector.UIString("Screen emulation is not available on this page."));
                this._deviceMetricsOverrideAppliedForTest();
                finishCallback();
                return;
            }
            var mobileEnabled = this.emulationEnabled() && this.settings.emulateMobile.get();
            if (this._emulateMobileEnabled !== mobileEnabled)
                this._updateDeviceMetricsWarningMessage(WebInspector.UIString("You might need to reload the page for proper user agent spoofing and viewport rendering."));
            this._emulateMobileEnabled = mobileEnabled;
            this._deviceMetricsOverrideAppliedForTest();
            finishCallback();
        }
    }, _deviceMetricsOverrideAppliedForTest: function () {
    }, _geolocationPositionChanged: function () {
        if (!this.emulationEnabled() || !this.settings.overrideGeolocation.get()) {
            GeolocationAgent.clearGeolocationOverride();
            return;
        }
        var geolocation = WebInspector.OverridesSupport.GeolocationPosition.parseSetting(this.settings.geolocationOverride.get());
        if (geolocation.error)
            GeolocationAgent.setGeolocationOverride(); else
            GeolocationAgent.setGeolocationOverride(geolocation.latitude, geolocation.longitude, 150);
    }, _deviceOrientationChanged: function () {
        if (!this.emulationEnabled() || !this.settings.overrideDeviceOrientation.get()) {
            PageAgent.clearDeviceOrientationOverride();
            return;
        }
        var deviceOrientation = WebInspector.OverridesSupport.DeviceOrientation.parseSetting(this.settings.deviceOrientationOverride.get());
        PageAgent.setDeviceOrientationOverride(deviceOrientation.alpha, deviceOrientation.beta, deviceOrientation.gamma);
    }, _emulateTouchEventsChanged: function () {
        var emulateTouch = this.emulationEnabled() && this.settings.emulateTouch.get() && !this._touchEmulationSuspended;
        var targets = WebInspector.targetManager.targets();
        for (var i = 0; i < targets.length; ++i)
            targets[i].domModel.emulateTouchEventObjects(emulateTouch);
    }, _cssMediaChanged: function () {
        var enabled = this.emulationEnabled() && this.settings.overrideCSSMedia.get();
        PageAgent.setEmulatedMedia(enabled ? this.settings.emulatedCSSMedia.get() : "");
        var targets = WebInspector.targetManager.targets();
        for (var i = 0; i < targets.length; ++i)
            targets[i].cssModel.mediaQueryResultChanged();
    }, _networkConditionsChanged: function () {
        if (!this.emulationEnabled() || !this.networkThroughputIsLimited()) {
            NetworkAgent.emulateNetworkConditions(false, 0, 0, 0);
        } else {
            var conditions = this.settings.networkConditions.get();
            var throughput = conditions.throughput;
            var latency = conditions.latency;
            var offline = !throughput && !latency;
            NetworkAgent.emulateNetworkConditions(offline, latency, throughput, throughput);
        }
    }, _pageResizerActive: function () {
        return this._pageResizer && this.emulationEnabled();
    }, showMetricsRulers: function () {
        return WebInspector.settings.showMetricsRulers.get() && !this._pageResizerActive();
    }, showExtensionLines: function () {
        return WebInspector.settings.showMetricsRulers.get();
    }, _showRulersChanged: function () {
        PageAgent.setShowViewportSizeOnResize(!this._pageResizerActive(), WebInspector.settings.showMetricsRulers.get());
    }, _onMainFrameNavigated: function () {
        if (this._initialized)
            this._deviceMetricsChanged();
        this._updateUserAgentWarningMessage("");
        this._updateDeviceMetricsWarningMessage("");
    }, _dispatchWarningChanged: function () {
        this.dispatchEventToListeners(WebInspector.OverridesSupport.Events.OverridesWarningUpdated);
    }, _updateDeviceMetricsWarningMessage: function (warningMessage) {
        this._deviceMetricsWarningMessage = warningMessage;
        this._dispatchWarningChanged();
    }, _updateUserAgentWarningMessage: function (warningMessage) {
        this._userAgentWarningMessage = warningMessage;
        this._dispatchWarningChanged();
    }, warningMessage: function () {
        return WebInspector.settings.disableOverridesWarning.get() ? "" : (this._deviceMetricsWarningMessage || this._userAgentWarningMessage || "");
    }, clearWarningMessage: function () {
        this._deviceMetricsWarningMessage = "";
        this._userAgentWarningMessage = "";
        this._dispatchWarningChanged();
    }, targetAdded: function (target) {
        if (this._target)
            return;
        this._target = target;
        target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._onMainFrameNavigated, this);
        if (this._applyInitialOverridesOnTargetAdded) {
            delete this._applyInitialOverridesOnTargetAdded;
            this.applyInitialOverrides();
        }
        this.dispatchEventToListeners(WebInspector.OverridesSupport.Events.EmulationStateChanged);
    }, swapDimensions: function () {
        var width = WebInspector.overridesSupport.settings.deviceWidth.get();
        var height = WebInspector.overridesSupport.settings.deviceHeight.get();
        WebInspector.overridesSupport.settings.deviceWidth.set(height);
        WebInspector.overridesSupport.settings.deviceHeight.set(width);
    }, targetRemoved: function (target) {
        if (target === this._target) {
            target.resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._onMainFrameNavigated, this);
            delete this._target;
            this.dispatchEventToListeners(WebInspector.OverridesSupport.Events.EmulationStateChanged);
        }
    }, networkThroughputIsLimited: function () {
        var conditions = this.settings.networkConditions.get();
        return conditions.throughput !== WebInspector.OverridesSupport.NetworkThroughputUnlimitedValue;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.overridesSupport;
WebInspector.Database = function (model, id, domain, name, version) {
    this._model = model;
    this._id = id;
    this._domain = domain;
    this._name = name;
    this._version = version;
}
WebInspector.Database.prototype = {
    get id() {
        return this._id;
    }, get name() {
        return this._name;
    }, set name(x) {
        this._name = x;
    }, get version() {
        return this._version;
    }, set version(x) {
        this._version = x;
    }, get domain() {
        return this._domain;
    }, set domain(x) {
        this._domain = x;
    }, getTableNames: function (callback) {
        function sortingCallback(error, names) {
            if (!error)
                callback(names.sort());
        }

        this._model._agent.getDatabaseTableNames(this._id, sortingCallback);
    }, executeSql: function (query, onSuccess, onError) {
        function callback(error, columnNames, values, errorObj) {
            if (error) {
                onError(error);
                return;
            }
            if (errorObj) {
                var message;
                if (errorObj.message)
                    message = errorObj.message; else if (errorObj.code == 2)
                    message = WebInspector.UIString("Database no longer has expected version."); else
                    message = WebInspector.UIString("An unexpected error %s occurred.", errorObj.code);
                onError(message);
                return;
            }
            onSuccess(columnNames, values);
        }

        this._model._agent.executeSQL(this._id, query, callback);
    }
}
WebInspector.DatabaseModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.DatabaseModel, target);
    this._databases = [];
    target.registerDatabaseDispatcher(new WebInspector.DatabaseDispatcher(this));
    this._agent = target.databaseAgent();
    this._agent.enable();
}
WebInspector.DatabaseModel.Events = {DatabaseAdded: "DatabaseAdded"}
WebInspector.DatabaseModel.prototype = {
    databases: function () {
        var result = [];
        for (var databaseId in this._databases)
            result.push(this._databases[databaseId]);
        return result;
    }, databaseForId: function (databaseId) {
        return this._databases[databaseId];
    }, _addDatabase: function (database) {
        this._databases.push(database);
        this.dispatchEventToListeners(WebInspector.DatabaseModel.Events.DatabaseAdded, database);
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.DatabaseDispatcher = function (model) {
    this._model = model;
}
WebInspector.DatabaseDispatcher.prototype = {
    addDatabase: function (payload) {
        this._model._addDatabase(new WebInspector.Database(this._model, payload.id, payload.domain, payload.name, payload.version));
    }
}
WebInspector.databaseModel;
WebInspector.DOMStorage = function (model, securityOrigin, isLocalStorage) {
    this._model = model;
    this._securityOrigin = securityOrigin;
    this._isLocalStorage = isLocalStorage;
}
WebInspector.DOMStorage.storageId = function (securityOrigin, isLocalStorage) {
    return {securityOrigin: securityOrigin, isLocalStorage: isLocalStorage};
}
WebInspector.DOMStorage.Events = {DOMStorageItemsCleared: "DOMStorageItemsCleared", DOMStorageItemRemoved: "DOMStorageItemRemoved", DOMStorageItemAdded: "DOMStorageItemAdded", DOMStorageItemUpdated: "DOMStorageItemUpdated"}
WebInspector.DOMStorage.prototype = {
    get id() {
        return WebInspector.DOMStorage.storageId(this._securityOrigin, this._isLocalStorage);
    }, get securityOrigin() {
        return this._securityOrigin;
    }, get isLocalStorage() {
        return this._isLocalStorage;
    }, getItems: function (callback) {
        this._model._agent.getDOMStorageItems(this.id, callback);
    }, setItem: function (key, value) {
        this._model._agent.setDOMStorageItem(this.id, key, value);
    }, removeItem: function (key) {
        this._model._agent.removeDOMStorageItem(this.id, key);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.DOMStorageModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.DOMStorageModel, target);
    this._storages = {};
    target.registerDOMStorageDispatcher(new WebInspector.DOMStorageDispatcher(this));
    this._agent = target.domstorageAgent();
    this._agent.enable();
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginAdded, this._securityOriginAdded, this);
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginRemoved, this._securityOriginRemoved, this);
}
WebInspector.DOMStorageModel.Events = {DOMStorageAdded: "DOMStorageAdded", DOMStorageRemoved: "DOMStorageRemoved"}
WebInspector.DOMStorageModel.prototype = {
    _securityOriginAdded: function (event) {
        var securityOrigin = (event.data);
        var localStorageKey = this._storageKey(securityOrigin, true);
        console.assert(!this._storages[localStorageKey]);
        var localStorage = new WebInspector.DOMStorage(this, securityOrigin, true);
        this._storages[localStorageKey] = localStorage;
        this.dispatchEventToListeners(WebInspector.DOMStorageModel.Events.DOMStorageAdded, localStorage);
        var sessionStorageKey = this._storageKey(securityOrigin, false);
        console.assert(!this._storages[sessionStorageKey]);
        var sessionStorage = new WebInspector.DOMStorage(this, securityOrigin, false);
        this._storages[sessionStorageKey] = sessionStorage;
        this.dispatchEventToListeners(WebInspector.DOMStorageModel.Events.DOMStorageAdded, sessionStorage);
    }, _securityOriginRemoved: function (event) {
        var securityOrigin = (event.data);
        var localStorageKey = this._storageKey(securityOrigin, true);
        var localStorage = this._storages[localStorageKey];
        console.assert(localStorage);
        delete this._storages[localStorageKey];
        this.dispatchEventToListeners(WebInspector.DOMStorageModel.Events.DOMStorageRemoved, localStorage);
        var sessionStorageKey = this._storageKey(securityOrigin, false);
        var sessionStorage = this._storages[sessionStorageKey];
        console.assert(sessionStorage);
        delete this._storages[sessionStorageKey];
        this.dispatchEventToListeners(WebInspector.DOMStorageModel.Events.DOMStorageRemoved, sessionStorage);
    }, _storageKey: function (securityOrigin, isLocalStorage) {
        return JSON.stringify(WebInspector.DOMStorage.storageId(securityOrigin, isLocalStorage));
    }, _domStorageItemsCleared: function (storageId) {
        var domStorage = this.storageForId(storageId);
        if (!domStorage)
            return;
        var eventData = {};
        domStorage.dispatchEventToListeners(WebInspector.DOMStorage.Events.DOMStorageItemsCleared, eventData);
    }, _domStorageItemRemoved: function (storageId, key) {
        var domStorage = this.storageForId(storageId);
        if (!domStorage)
            return;
        var eventData = {key: key};
        domStorage.dispatchEventToListeners(WebInspector.DOMStorage.Events.DOMStorageItemRemoved, eventData);
    }, _domStorageItemAdded: function (storageId, key, value) {
        var domStorage = this.storageForId(storageId);
        if (!domStorage)
            return;
        var eventData = {key: key, value: value};
        domStorage.dispatchEventToListeners(WebInspector.DOMStorage.Events.DOMStorageItemAdded, eventData);
    }, _domStorageItemUpdated: function (storageId, key, oldValue, value) {
        var domStorage = this.storageForId(storageId);
        if (!domStorage)
            return;
        var eventData = {key: key, oldValue: oldValue, value: value};
        domStorage.dispatchEventToListeners(WebInspector.DOMStorage.Events.DOMStorageItemUpdated, eventData);
    }, storageForId: function (storageId) {
        return this._storages[JSON.stringify(storageId)];
    }, storages: function () {
        var result = [];
        for (var id in this._storages)
            result.push(this._storages[id]);
        return result;
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.DOMStorageDispatcher = function (model) {
    this._model = model;
}
WebInspector.DOMStorageDispatcher.prototype = {
    domStorageItemsCleared: function (storageId) {
        this._model._domStorageItemsCleared(storageId);
    }, domStorageItemRemoved: function (storageId, key) {
        this._model._domStorageItemRemoved(storageId, key);
    }, domStorageItemAdded: function (storageId, key, value) {
        this._model._domStorageItemAdded(storageId, key, value);
    }, domStorageItemUpdated: function (storageId, key, oldValue, value) {
        this._model._domStorageItemUpdated(storageId, key, oldValue, value);
    },
}
WebInspector.domStorageModel;
WebInspector.HeapProfilerModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.HeapProfilerModel, target);
    target.registerHeapProfilerDispatcher(new WebInspector.HeapProfilerDispatcher(this));
    this._enabled = false;
    this._heapProfilerAgent = target.heapProfilerAgent();
}
WebInspector.HeapProfilerModel.Events = {
    HeapStatsUpdate: "HeapStatsUpdate",
    LastSeenObjectId: "LastSeenObjectId",
    AddHeapSnapshotChunk: "AddHeapSnapshotChunk",
    ReportHeapSnapshotProgress: "ReportHeapSnapshotProgress",
    ResetProfiles: "ResetProfiles"
}
WebInspector.HeapProfilerModel.prototype = {
    enable: function () {
        if (this._enabled)
            return;
        this._enabled = true;
        this._heapProfilerAgent.enable();
    }, heapStatsUpdate: function (samples) {
        this.dispatchEventToListeners(WebInspector.HeapProfilerModel.Events.HeapStatsUpdate, samples);
    }, lastSeenObjectId: function (lastSeenObjectId, timestamp) {
        this.dispatchEventToListeners(WebInspector.HeapProfilerModel.Events.LastSeenObjectId, {lastSeenObjectId: lastSeenObjectId, timestamp: timestamp});
    }, addHeapSnapshotChunk: function (chunk) {
        this.dispatchEventToListeners(WebInspector.HeapProfilerModel.Events.AddHeapSnapshotChunk, chunk);
    }, reportHeapSnapshotProgress: function (done, total, finished) {
        this.dispatchEventToListeners(WebInspector.HeapProfilerModel.Events.ReportHeapSnapshotProgress, {done: done, total: total, finished: finished});
    }, resetProfiles: function () {
        this.dispatchEventToListeners(WebInspector.HeapProfilerModel.Events.ResetProfiles);
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.HeapProfilerDispatcher = function (model) {
    this._heapProfilerModel = model;
}
WebInspector.HeapProfilerDispatcher.prototype = {
    heapStatsUpdate: function (samples) {
        this._heapProfilerModel.heapStatsUpdate(samples);
    }, lastSeenObjectId: function (lastSeenObjectId, timestamp) {
        this._heapProfilerModel.lastSeenObjectId(lastSeenObjectId, timestamp);
    }, addHeapSnapshotChunk: function (chunk) {
        this._heapProfilerModel.addHeapSnapshotChunk(chunk);
    }, reportHeapSnapshotProgress: function (done, total, finished) {
        this._heapProfilerModel.reportHeapSnapshotProgress(done, total, finished);
    }, resetProfiles: function () {
        this._heapProfilerModel.resetProfiles();
    }
}
WebInspector.DataGrid = function (columnsArray, editCallback, deleteCallback, refreshCallback, contextMenuCallback) {
    WebInspector.View.call(this);
    this.registerRequiredCSS("dataGrid.css");
    this.element.className = "data-grid";
    this.element.tabIndex = 0;
    this.element.addEventListener("keydown", this._keyDown.bind(this), false);
    var headerContainer = document.createElementWithClass("div", "header-container");
    this._headerTable = headerContainer.createChild("table", "header");
    this._headerTableHeaders = {};
    this._scrollContainer = document.createElementWithClass("div", "data-container");
    this._dataTable = this._scrollContainer.createChild("table", "data");
    this._dataTable.addEventListener("mousedown", this._mouseDownInDataTable.bind(this), true);
    this._dataTable.addEventListener("click", this._clickInDataTable.bind(this), true);
    this._dataTable.addEventListener("contextmenu", this._contextMenuInDataTable.bind(this), true);
    if (editCallback)
        this._dataTable.addEventListener("dblclick", this._ondblclick.bind(this), false);
    this._editCallback = editCallback;
    this._deleteCallback = deleteCallback;
    this._refreshCallback = refreshCallback;
    this._contextMenuCallback = contextMenuCallback;
    this.element.appendChild(headerContainer);
    this.element.appendChild(this._scrollContainer);
    this._headerRow = document.createElement("tr");
    this._headerTableColumnGroup = document.createElement("colgroup");
    this._dataTableColumnGroup = document.createElement("colgroup");
    this._topFillerRow = document.createElementWithClass("tr", "revealed");
    this._bottomFillerRow = document.createElementWithClass("tr", "revealed");
    this.setVerticalPadding(0, 0);
    this._columnsArray = columnsArray;
    this._visibleColumnsArray = columnsArray;
    this._columns = {};
    this._cellClass = null;
    for (var i = 0; i < columnsArray.length; ++i) {
        var column = columnsArray[i];
        var columnIdentifier = column.identifier = column.id || i;
        this._columns[columnIdentifier] = column;
        if (column.disclosure)
            this.disclosureColumnIdentifier = columnIdentifier;
        var cell = document.createElement("th");
        cell.className = columnIdentifier + "-column";
        cell.columnIdentifier = columnIdentifier;
        this._headerTableHeaders[columnIdentifier] = cell;
        var div = document.createElement("div");
        if (column.titleDOMFragment)
            div.appendChild(column.titleDOMFragment); else
            div.textContent = column.title;
        cell.appendChild(div);
        if (column.sort) {
            cell.classList.add(column.sort);
            this._sortColumnCell = cell;
        }
        if (column.sortable) {
            cell.addEventListener("click", this._clickInHeaderCell.bind(this), false);
            cell.classList.add("sortable");
        }
    }
    this._headerTable.appendChild(this._headerTableColumnGroup);
    this.headerTableBody.appendChild(this._headerRow);
    this._dataTable.appendChild(this._dataTableColumnGroup);
    this.dataTableBody.appendChild(this._topFillerRow);
    this.dataTableBody.appendChild(this._bottomFillerRow);
    this._refreshHeader();
    this._editing = false;
    this.selectedNode = null;
    this.expandNodesWhenArrowing = false;
    this.setRootNode(new WebInspector.DataGridNode());
    this.indentWidth = 15;
    this._resizers = [];
    this._columnWidthsInitialized = false;
    this._cornerWidth = WebInspector.DataGrid.CornerWidth;
    this._resizeMethod = WebInspector.DataGrid.ResizeMethod.Nearest;
}
WebInspector.DataGrid.CornerWidth = 14;
WebInspector.DataGrid.ColumnDescriptor;
WebInspector.DataGrid.Events = {SelectedNode: "SelectedNode", DeselectedNode: "DeselectedNode", SortingChanged: "SortingChanged", ColumnsResized: "ColumnsResized"}
WebInspector.DataGrid.Order = {Ascending: "sort-ascending", Descending: "sort-descending"}
WebInspector.DataGrid.Align = {Center: "center", Right: "right"}
WebInspector.DataGrid.prototype = {
    setCellClass: function (cellClass) {
        this._cellClass = cellClass;
    }, _refreshHeader: function () {
        this._headerTableColumnGroup.removeChildren();
        this._dataTableColumnGroup.removeChildren();
        this._headerRow.removeChildren();
        this._topFillerRow.removeChildren();
        this._bottomFillerRow.removeChildren();
        for (var i = 0; i < this._visibleColumnsArray.length; ++i) {
            var column = this._visibleColumnsArray[i];
            var columnIdentifier = column.identifier;
            var headerColumn = this._headerTableColumnGroup.createChild("col");
            var dataColumn = this._dataTableColumnGroup.createChild("col");
            if (column.width) {
                headerColumn.style.width = column.width;
                dataColumn.style.width = column.width;
            }
            this._headerRow.appendChild(this._headerTableHeaders[columnIdentifier]);
            this._topFillerRow.createChild("td", "top-filler-td");
            this._bottomFillerRow.createChild("td", "bottom-filler-td");
        }
        this._headerRow.createChild("th", "corner");
        this._topFillerRow.createChild("td", "corner").classList.add("top-filler-td");
        this._bottomFillerRow.createChild("td", "corner").classList.add("bottom-filler-td");
        this._headerTableColumnGroup.createChild("col", "corner");
        this._dataTableColumnGroup.createChild("col", "corner");
    }, setVerticalPadding: function (top, bottom) {
        this._topFillerRow.style.height = top + "px";
        if (top || bottom)
            this._bottomFillerRow.style.height = bottom + "px"; else
            this._bottomFillerRow.style.height = "auto";
    }, setRootNode: function (rootNode) {
        if (this._rootNode) {
            this._rootNode.removeChildren();
            this._rootNode.dataGrid = null;
            this._rootNode._isRoot = false;
        }
        this._rootNode = rootNode;
        rootNode._isRoot = true;
        rootNode.hasChildren = false;
        rootNode._expanded = true;
        rootNode._revealed = true;
        rootNode.dataGrid = this;
    }, rootNode: function () {
        return this._rootNode;
    }, _ondblclick: function (event) {
        if (this._editing || this._editingNode)
            return;
        var columnIdentifier = this.columnIdentifierFromNode(event.target);
        if (!columnIdentifier || !this._columns[columnIdentifier].editable)
            return;
        this._startEditing(event.target);
    }, _startEditingColumnOfDataGridNode: function (node, cellIndex) {
        this._editing = true;
        this._editingNode = node;
        this._editingNode.select();
        var element = this._editingNode._element.children[cellIndex];
        WebInspector.InplaceEditor.startEditing(element, this._startEditingConfig(element));
        window.getSelection().setBaseAndExtent(element, 0, element, 1);
    }, _startEditing: function (target) {
        var element = target.enclosingNodeOrSelfWithNodeName("td");
        if (!element)
            return;
        this._editingNode = this.dataGridNodeFromNode(target);
        if (!this._editingNode) {
            if (!this.creationNode)
                return;
            this._editingNode = this.creationNode;
        }
        if (this._editingNode.isCreationNode)
            return this._startEditingColumnOfDataGridNode(this._editingNode, this._nextEditableColumn(-1));
        this._editing = true;
        WebInspector.InplaceEditor.startEditing(element, this._startEditingConfig(element));
        window.getSelection().setBaseAndExtent(element, 0, element, 1);
    }, renderInline: function () {
        this.element.classList.add("inline");
        this._cornerWidth = 0;
        this.updateWidths();
    }, _startEditingConfig: function (element) {
        return new WebInspector.InplaceEditor.Config(this._editingCommitted.bind(this), this._editingCancelled.bind(this), element.textContent);
    }, _editingCommitted: function (element, newText, oldText, context, moveDirection) {
        var columnIdentifier = this.columnIdentifierFromNode(element);
        if (!columnIdentifier) {
            this._editingCancelled(element);
            return;
        }
        var column = this._columns[columnIdentifier];
        var cellIndex = this._visibleColumnsArray.indexOf(column);
        var textBeforeEditing = this._editingNode.data[columnIdentifier];
        var currentEditingNode = this._editingNode;

        function moveToNextIfNeeded(wasChange) {
            if (!moveDirection)
                return;
            if (moveDirection === "forward") {
                var firstEditableColumn = this._nextEditableColumn(-1);
                if (currentEditingNode.isCreationNode && cellIndex === firstEditableColumn && !wasChange)
                    return;
                var nextEditableColumn = this._nextEditableColumn(cellIndex);
                if (nextEditableColumn !== -1)
                    return this._startEditingColumnOfDataGridNode(currentEditingNode, nextEditableColumn);
                var nextDataGridNode = currentEditingNode.traverseNextNode(true, null, true);
                if (nextDataGridNode)
                    return this._startEditingColumnOfDataGridNode(nextDataGridNode, firstEditableColumn);
                if (currentEditingNode.isCreationNode && wasChange) {
                    this.addCreationNode(false);
                    return this._startEditingColumnOfDataGridNode(this.creationNode, firstEditableColumn);
                }
                return;
            }
            if (moveDirection === "backward") {
                var prevEditableColumn = this._nextEditableColumn(cellIndex, true);
                if (prevEditableColumn !== -1)
                    return this._startEditingColumnOfDataGridNode(currentEditingNode, prevEditableColumn);
                var lastEditableColumn = this._nextEditableColumn(this._visibleColumnsArray.length, true);
                var nextDataGridNode = currentEditingNode.traversePreviousNode(true, true);
                if (nextDataGridNode)
                    return this._startEditingColumnOfDataGridNode(nextDataGridNode, lastEditableColumn);
                return;
            }
        }

        if (textBeforeEditing == newText) {
            this._editingCancelled(element);
            moveToNextIfNeeded.call(this, false);
            return;
        }
        this._editingNode.data[columnIdentifier] = newText;
        this._editCallback(this._editingNode, columnIdentifier, textBeforeEditing, newText);
        if (this._editingNode.isCreationNode)
            this.addCreationNode(false);
        this._editingCancelled(element);
        moveToNextIfNeeded.call(this, true);
    }, _editingCancelled: function (element) {
        this._editing = false;
        this._editingNode = null;
    }, _nextEditableColumn: function (cellIndex, moveBackward) {
        var increment = moveBackward ? -1 : 1;
        var columns = this._visibleColumnsArray;
        for (var i = cellIndex + increment; (i >= 0) && (i < columns.length); i += increment) {
            if (columns[i].editable)
                return i;
        }
        return -1;
    }, sortColumnIdentifier: function () {
        if (!this._sortColumnCell)
            return null;
        return this._sortColumnCell.columnIdentifier;
    }, sortOrder: function () {
        if (!this._sortColumnCell || this._sortColumnCell.classList.contains(WebInspector.DataGrid.Order.Ascending))
            return WebInspector.DataGrid.Order.Ascending;
        if (this._sortColumnCell.classList.contains(WebInspector.DataGrid.Order.Descending))
            return WebInspector.DataGrid.Order.Descending;
        return null;
    }, isSortOrderAscending: function () {
        return !this._sortColumnCell || this._sortColumnCell.classList.contains(WebInspector.DataGrid.Order.Ascending);
    }, get headerTableBody() {
        if ("_headerTableBody"in this)
            return this._headerTableBody;
        this._headerTableBody = this._headerTable.getElementsByTagName("tbody")[0];
        if (!this._headerTableBody) {
            this._headerTableBody = this.element.ownerDocument.createElement("tbody");
            this._headerTable.insertBefore(this._headerTableBody, this._headerTable.tFoot);
        }
        return this._headerTableBody;
    }, get dataTableBody() {
        if ("_dataTableBody"in this)
            return this._dataTableBody;
        this._dataTableBody = this._dataTable.getElementsByTagName("tbody")[0];
        if (!this._dataTableBody) {
            this._dataTableBody = this.element.ownerDocument.createElement("tbody");
            this._dataTable.insertBefore(this._dataTableBody, this._dataTable.tFoot);
        }
        return this._dataTableBody;
    }, _autoSizeWidths: function (widths, minPercent, maxPercent) {
        if (minPercent)
            minPercent = Math.min(minPercent, Math.floor(100 / widths.length));
        var totalWidth = 0;
        for (var i = 0; i < widths.length; ++i)
            totalWidth += widths[i];
        var totalPercentWidth = 0;
        for (var i = 0; i < widths.length; ++i) {
            var width = Math.round(100 * widths[i] / totalWidth);
            if (minPercent && width < minPercent)
                width = minPercent; else if (maxPercent && width > maxPercent)
                width = maxPercent;
            totalPercentWidth += width;
            widths[i] = width;
        }
        var recoupPercent = totalPercentWidth - 100;
        while (minPercent && recoupPercent > 0) {
            for (var i = 0; i < widths.length; ++i) {
                if (widths[i] > minPercent) {
                    --widths[i];
                    --recoupPercent;
                    if (!recoupPercent)
                        break;
                }
            }
        }
        while (maxPercent && recoupPercent < 0) {
            for (var i = 0; i < widths.length; ++i) {
                if (widths[i] < maxPercent) {
                    ++widths[i];
                    ++recoupPercent;
                    if (!recoupPercent)
                        break;
                }
            }
        }
        return widths;
    }, autoSizeColumns: function (minPercent, maxPercent, maxDescentLevel) {
        var widths = [];
        for (var i = 0; i < this._columnsArray.length; ++i)
            widths.push((this._columnsArray[i].title || "").length);
        maxDescentLevel = maxDescentLevel || 0;
        var children = this._enumerateChildren(this._rootNode, [], maxDescentLevel + 1);
        for (var i = 0; i < children.length; ++i) {
            var node = children[i];
            for (var j = 0; j < this._columnsArray.length; ++j) {
                var text = node.data[this._columnsArray[j].identifier] || "";
                if (text.length > widths[j])
                    widths[j] = text.length;
            }
        }
        widths = this._autoSizeWidths(widths, minPercent, maxPercent);
        for (var i = 0; i < this._columnsArray.length; ++i)
            this._columnsArray[i].weight = widths[i];
        this._columnWidthsInitialized = false;
        this.updateWidths();
    }, _enumerateChildren: function (rootNode, result, maxLevel) {
        if (!rootNode._isRoot)
            result.push(rootNode);
        if (!maxLevel)
            return;
        for (var i = 0; i < rootNode.children.length; ++i)
            this._enumerateChildren(rootNode.children[i], result, maxLevel - 1);
        return result;
    }, onResize: function () {
        this.updateWidths();
    }, updateWidths: function () {
        var headerTableColumns = this._headerTableColumnGroup.children;
        var tableWidth = this.element.offsetWidth - this._cornerWidth;
        var numColumns = headerTableColumns.length - 1;
        if (!this._columnWidthsInitialized && this.element.offsetWidth) {
            for (var i = 0; i < numColumns; i++) {
                var columnWidth = this.headerTableBody.rows[0].cells[i].offsetWidth;
                var column = this._visibleColumnsArray[i];
                if (!column.weight)
                    column.weight = 100 * columnWidth / tableWidth;
            }
            this._columnWidthsInitialized = true;
        }
        this._applyColumnWeights();
    }, setName: function (name) {
        this._columnWeightsSetting = WebInspector.settings.createSetting("dataGrid-" + name + "-columnWeights", {});
        this._loadColumnWeights();
    }, _loadColumnWeights: function () {
        if (!this._columnWeightsSetting)
            return;
        var weights = this._columnWeightsSetting.get();
        for (var i = 0; i < this._columnsArray.length; ++i) {
            var column = this._columnsArray[i];
            var weight = weights[column.identifier];
            if (weight)
                column.weight = weight;
        }
        this._applyColumnWeights();
    }, _saveColumnWeights: function () {
        if (!this._columnWeightsSetting)
            return;
        var weights = {};
        for (var i = 0; i < this._columnsArray.length; ++i) {
            var column = this._columnsArray[i];
            weights[column.identifier] = column.weight;
        }
        this._columnWeightsSetting.set(weights);
    }, wasShown: function () {
        this._loadColumnWeights();
    }, _applyColumnWeights: function () {
        var tableWidth = this.element.offsetWidth - this._cornerWidth;
        if (tableWidth <= 0)
            return;
        var sumOfWeights = 0.0;
        for (var i = 0; i < this._visibleColumnsArray.length; ++i)
            sumOfWeights += this._visibleColumnsArray[i].weight;
        var sum = 0;
        var lastOffset = 0;
        for (var i = 0; i < this._visibleColumnsArray.length; ++i) {
            sum += this._visibleColumnsArray[i].weight;
            var offset = (sum * tableWidth / sumOfWeights) | 0;
            var width = (offset - lastOffset) + "px";
            this._headerTableColumnGroup.children[i].style.width = width;
            this._dataTableColumnGroup.children[i].style.width = width;
            lastOffset = offset;
        }
        this._positionResizers();
        this.dispatchEventToListeners(WebInspector.DataGrid.Events.ColumnsResized);
    }, setColumnsVisiblity: function (columnsVisibility) {
        this._visibleColumnsArray = [];
        for (var i = 0; i < this._columnsArray.length; ++i) {
            var column = this._columnsArray[i];
            if (columnsVisibility[column.identifier])
                this._visibleColumnsArray.push(column);
        }
        this._refreshHeader();
        this._applyColumnWeights();
        var nodes = this._enumerateChildren(this.rootNode(), [], -1);
        for (var i = 0; i < nodes.length; ++i)
            nodes[i].refresh();
    }, get scrollContainer() {
        return this._scrollContainer;
    }, isScrolledToLastRow: function () {
        return this._scrollContainer.isScrolledToBottom();
    }, scrollToLastRow: function () {
        this._scrollContainer.scrollTop = this._scrollContainer.scrollHeight - this._scrollContainer.offsetHeight;
    }, _positionResizers: function () {
        var headerTableColumns = this._headerTableColumnGroup.children;
        var numColumns = headerTableColumns.length - 1;
        var left = [];
        var resizers = this._resizers;
        while (resizers.length > numColumns - 1)
            resizers.pop().remove();
        for (var i = 0; i < numColumns - 1; i++) {
            left[i] = (left[i - 1] || 0) + this.headerTableBody.rows[0].cells[i].offsetWidth;
        }
        for (var i = 0; i < numColumns - 1; i++) {
            var resizer = resizers[i];
            if (!resizer) {
                resizer = document.createElement("div");
                resizer.__index = i;
                resizer.classList.add("data-grid-resizer");
                WebInspector.installDragHandle(resizer, this._startResizerDragging.bind(this), this._resizerDragging.bind(this), this._endResizerDragging.bind(this), "col-resize");
                this.element.appendChild(resizer);
                resizers.push(resizer);
            }
            if (resizer.__position !== left[i]) {
                resizer.__position = left[i];
                resizer.style.left = left[i] + "px";
            }
        }
    }, addCreationNode: function (hasChildren) {
        if (this.creationNode)
            this.creationNode.makeNormal();
        var emptyData = {};
        for (var column in this._columns)
            emptyData[column] = null;
        this.creationNode = new WebInspector.CreationDataGridNode(emptyData, hasChildren);
        this.rootNode().appendChild(this.creationNode);
    }, _keyDown: function (event) {
        if (!this.selectedNode || event.shiftKey || event.metaKey || event.ctrlKey || this._editing)
            return;
        var handled = false;
        var nextSelectedNode;
        if (event.keyIdentifier === "Up" && !event.altKey) {
            nextSelectedNode = this.selectedNode.traversePreviousNode(true);
            while (nextSelectedNode && !nextSelectedNode.selectable)
                nextSelectedNode = nextSelectedNode.traversePreviousNode(true);
            handled = nextSelectedNode ? true : false;
        } else if (event.keyIdentifier === "Down" && !event.altKey) {
            nextSelectedNode = this.selectedNode.traverseNextNode(true);
            while (nextSelectedNode && !nextSelectedNode.selectable)
                nextSelectedNode = nextSelectedNode.traverseNextNode(true);
            handled = nextSelectedNode ? true : false;
        } else if (event.keyIdentifier === "Left") {
            if (this.selectedNode.expanded) {
                if (event.altKey)
                    this.selectedNode.collapseRecursively(); else
                    this.selectedNode.collapse();
                handled = true;
            } else if (this.selectedNode.parent && !this.selectedNode.parent._isRoot) {
                handled = true;
                if (this.selectedNode.parent.selectable) {
                    nextSelectedNode = this.selectedNode.parent;
                    handled = nextSelectedNode ? true : false;
                } else if (this.selectedNode.parent)
                    this.selectedNode.parent.collapse();
            }
        } else if (event.keyIdentifier === "Right") {
            if (!this.selectedNode.revealed) {
                this.selectedNode.reveal();
                handled = true;
            } else if (this.selectedNode.hasChildren) {
                handled = true;
                if (this.selectedNode.expanded) {
                    nextSelectedNode = this.selectedNode.children[0];
                    handled = nextSelectedNode ? true : false;
                } else {
                    if (event.altKey)
                        this.selectedNode.expandRecursively(); else
                        this.selectedNode.expand();
                }
            }
        } else if (event.keyCode === 8 || event.keyCode === 46) {
            if (this._deleteCallback) {
                handled = true;
                this._deleteCallback(this.selectedNode);
                this.changeNodeAfterDeletion();
            }
        } else if (isEnterKey(event)) {
            if (this._editCallback) {
                handled = true;
                this._startEditing(this.selectedNode._element.children[this._nextEditableColumn(-1)]);
            }
        }
        if (nextSelectedNode) {
            nextSelectedNode.reveal();
            nextSelectedNode.select();
        }
        if (handled)
            event.consume(true);
    }, changeNodeAfterDeletion: function () {
        var nextSelectedNode = this.selectedNode.traverseNextNode(true);
        while (nextSelectedNode && !nextSelectedNode.selectable)
            nextSelectedNode = nextSelectedNode.traverseNextNode(true);
        if (!nextSelectedNode || nextSelectedNode.isCreationNode) {
            nextSelectedNode = this.selectedNode.traversePreviousNode(true);
            while (nextSelectedNode && !nextSelectedNode.selectable)
                nextSelectedNode = nextSelectedNode.traversePreviousNode(true);
        }
        if (nextSelectedNode) {
            nextSelectedNode.reveal();
            nextSelectedNode.select();
        }
    }, dataGridNodeFromNode: function (target) {
        var rowElement = target.enclosingNodeOrSelfWithNodeName("tr");
        return rowElement && rowElement._dataGridNode;
    }, columnIdentifierFromNode: function (target) {
        var cellElement = target.enclosingNodeOrSelfWithNodeName("td");
        return cellElement && cellElement.columnIdentifier_;
    }, _clickInHeaderCell: function (event) {
        var cell = event.target.enclosingNodeOrSelfWithNodeName("th");
        if (!cell || (cell.columnIdentifier === undefined) || !cell.classList.contains("sortable"))
            return;
        var sortOrder = WebInspector.DataGrid.Order.Ascending;
        if ((cell === this._sortColumnCell) && this.isSortOrderAscending())
            sortOrder = WebInspector.DataGrid.Order.Descending;
        if (this._sortColumnCell)
            this._sortColumnCell.classList.remove(WebInspector.DataGrid.Order.Ascending, WebInspector.DataGrid.Order.Descending);
        this._sortColumnCell = cell;
        cell.classList.add(sortOrder);
        this.dispatchEventToListeners(WebInspector.DataGrid.Events.SortingChanged);
    }, markColumnAsSortedBy: function (columnIdentifier, sortOrder) {
        if (this._sortColumnCell)
            this._sortColumnCell.classList.remove(WebInspector.DataGrid.Order.Ascending, WebInspector.DataGrid.Order.Descending);
        this._sortColumnCell = this._headerTableHeaders[columnIdentifier];
        this._sortColumnCell.classList.add(sortOrder);
    }, headerTableHeader: function (columnIdentifier) {
        return this._headerTableHeaders[columnIdentifier];
    }, _mouseDownInDataTable: function (event) {
        var gridNode = this.dataGridNodeFromNode(event.target);
        if (!gridNode || !gridNode.selectable)
            return;
        if (gridNode.isEventWithinDisclosureTriangle(event))
            return;
        if (event.metaKey) {
            if (gridNode.selected)
                gridNode.deselect(); else
                gridNode.select();
        } else
            gridNode.select();
    }, _contextMenuInDataTable: function (event) {
        var contextMenu = new WebInspector.ContextMenu(event);
        var gridNode = this.dataGridNodeFromNode(event.target);
        if (this._refreshCallback && (!gridNode || gridNode !== this.creationNode))
            contextMenu.appendItem(WebInspector.UIString("Refresh"), this._refreshCallback.bind(this));
        if (gridNode && gridNode.selectable && !gridNode.isEventWithinDisclosureTriangle(event)) {
            if (this._editCallback) {
                if (gridNode === this.creationNode)
                    contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Add new" : "Add New"), this._startEditing.bind(this, event.target)); else {
                    var columnIdentifier = this.columnIdentifierFromNode(event.target);
                    if (columnIdentifier && this._columns[columnIdentifier].editable)
                        contextMenu.appendItem(WebInspector.UIString("Edit \"%s\"", this._columns[columnIdentifier].title), this._startEditing.bind(this, event.target));
                }
            }
            if (this._deleteCallback && gridNode !== this.creationNode)
                contextMenu.appendItem(WebInspector.UIString("Delete"), this._deleteCallback.bind(this, gridNode));
            if (this._contextMenuCallback)
                this._contextMenuCallback(contextMenu, gridNode);
        }
        contextMenu.show();
    }, _clickInDataTable: function (event) {
        var gridNode = this.dataGridNodeFromNode(event.target);
        if (!gridNode || !gridNode.hasChildren)
            return;
        if (!gridNode.isEventWithinDisclosureTriangle(event))
            return;
        if (gridNode.expanded) {
            if (event.altKey)
                gridNode.collapseRecursively(); else
                gridNode.collapse();
        } else {
            if (event.altKey)
                gridNode.expandRecursively(); else
                gridNode.expand();
        }
    }, setResizeMethod: function (method) {
        this._resizeMethod = method;
    }, _startResizerDragging: function (event) {
        this._currentResizer = event.target;
        return true;
    }, _resizerDragging: function (event) {
        var resizer = this._currentResizer;
        if (!resizer)
            return;
        var tableWidth = this.element.offsetWidth;
        var dragPoint = event.clientX - this.element.totalOffsetLeft();
        var firstRowCells = this.headerTableBody.rows[0].cells;
        var leftEdgeOfPreviousColumn = 0;
        var leftCellIndex = resizer.__index;
        var rightCellIndex = leftCellIndex + 1;
        for (var i = 0; i < leftCellIndex; i++)
            leftEdgeOfPreviousColumn += firstRowCells[i].offsetWidth;
        if (this._resizeMethod === WebInspector.DataGrid.ResizeMethod.Last) {
            rightCellIndex = this._resizers.length;
        } else if (this._resizeMethod === WebInspector.DataGrid.ResizeMethod.First) {
            leftEdgeOfPreviousColumn += firstRowCells[leftCellIndex].offsetWidth - firstRowCells[0].offsetWidth;
            leftCellIndex = 0;
        }
        var rightEdgeOfNextColumn = leftEdgeOfPreviousColumn + firstRowCells[leftCellIndex].offsetWidth + firstRowCells[rightCellIndex].offsetWidth;
        var leftMinimum = leftEdgeOfPreviousColumn + this.ColumnResizePadding;
        var rightMaximum = rightEdgeOfNextColumn - this.ColumnResizePadding;
        if (leftMinimum > rightMaximum)
            return;
        dragPoint = Number.constrain(dragPoint, leftMinimum, rightMaximum);
        var position = (dragPoint - this.CenterResizerOverBorderAdjustment);
        resizer.__position = position;
        resizer.style.left = position + "px";
        var pxLeftColumn = (dragPoint - leftEdgeOfPreviousColumn) + "px";
        this._headerTableColumnGroup.children[leftCellIndex].style.width = pxLeftColumn;
        this._dataTableColumnGroup.children[leftCellIndex].style.width = pxLeftColumn;
        var pxRightColumn = (rightEdgeOfNextColumn - dragPoint) + "px";
        this._headerTableColumnGroup.children[rightCellIndex].style.width = pxRightColumn;
        this._dataTableColumnGroup.children[rightCellIndex].style.width = pxRightColumn;
        var leftColumn = this._visibleColumnsArray[leftCellIndex];
        var rightColumn = this._visibleColumnsArray[rightCellIndex];
        if (leftColumn.weight || rightColumn.weight) {
            var sumOfWeights = leftColumn.weight + rightColumn.weight;
            var delta = rightEdgeOfNextColumn - leftEdgeOfPreviousColumn;
            leftColumn.weight = (dragPoint - leftEdgeOfPreviousColumn) * sumOfWeights / delta;
            rightColumn.weight = (rightEdgeOfNextColumn - dragPoint) * sumOfWeights / delta;
        }
        this._positionResizers();
        event.preventDefault();
        this.dispatchEventToListeners(WebInspector.DataGrid.Events.ColumnsResized);
    }, columnOffset: function (columnId) {
        if (!this.element.offsetWidth)
            return 0;
        for (var i = 1; i < this._visibleColumnsArray.length; ++i) {
            if (columnId === this._visibleColumnsArray[i].identifier) {
                if (this._resizers[i - 1])
                    return this._resizers[i - 1].__position;
            }
        }
        return 0;
    }, _endResizerDragging: function (event) {
        this._currentResizer = null;
        this._saveColumnWeights();
        this.dispatchEventToListeners(WebInspector.DataGrid.Events.ColumnsResized);
    }, ColumnResizePadding: 24, CenterResizerOverBorderAdjustment: 3, __proto__: WebInspector.View.prototype
}
WebInspector.DataGrid.ResizeMethod = {Nearest: "nearest", First: "first", Last: "last"}
WebInspector.DataGridNode = function (data, hasChildren) {
    this._element = null;
    this._expanded = false;
    this._selected = false;
    this._depth;
    this._revealed;
    this._attached = false;
    this._savedPosition = null;
    this._shouldRefreshChildren = true;
    this._data = data || {};
    this.hasChildren = hasChildren || false;
    this.children = [];
    this.dataGrid = null;
    this.parent = null;
    this.previousSibling = null;
    this.nextSibling = null;
    this.disclosureToggleWidth = 10;
}
WebInspector.DataGridNode.prototype = {
    selectable: true, _isRoot: false, element: function () {
        if (!this._element) {
            this.createElement();
            this.createCells();
        }
        return (this._element);
    }, createElement: function () {
        this._element = document.createElement("tr");
        this._element._dataGridNode = this;
        if (this.hasChildren)
            this._element.classList.add("parent");
        if (this.expanded)
            this._element.classList.add("expanded");
        if (this.selected)
            this._element.classList.add("selected");
        if (this.revealed)
            this._element.classList.add("revealed");
    }, createCells: function () {
        this._element.removeChildren();
        var columnsArray = this.dataGrid._visibleColumnsArray;
        for (var i = 0; i < columnsArray.length; ++i)
            this._element.appendChild(this.createCell(columnsArray[i].identifier));
        this._element.appendChild(this._createTDWithClass("corner"));
    }, get data() {
        return this._data;
    }, set data(x) {
        this._data = x || {};
        this.refresh();
    }, get revealed() {
        if (this._revealed !== undefined)
            return this._revealed;
        var currentAncestor = this.parent;
        while (currentAncestor && !currentAncestor._isRoot) {
            if (!currentAncestor.expanded) {
                this._revealed = false;
                return false;
            }
            currentAncestor = currentAncestor.parent;
        }
        this._revealed = true;
        return true;
    }, set hasChildren(x) {
        if (this._hasChildren === x)
            return;
        this._hasChildren = x;
        if (!this._element)
            return;
        this._element.classList.toggle("parent", this._hasChildren);
        this._element.classList.toggle("expanded", this._hasChildren && this.expanded);
    }, get hasChildren() {
        return this._hasChildren;
    }, set revealed(x) {
        if (this._revealed === x)
            return;
        this._revealed = x;
        if (this._element)
            this._element.classList.toggle("revealed", this._revealed);
        for (var i = 0; i < this.children.length; ++i)
            this.children[i].revealed = x && this.expanded;
    }, get depth() {
        if (this._depth !== undefined)
            return this._depth;
        if (this.parent && !this.parent._isRoot)
            this._depth = this.parent.depth + 1; else
            this._depth = 0;
        return this._depth;
    }, get leftPadding() {
        if (typeof this._leftPadding === "number")
            return this._leftPadding;
        this._leftPadding = this.depth * this.dataGrid.indentWidth;
        return this._leftPadding;
    }, get shouldRefreshChildren() {
        return this._shouldRefreshChildren;
    }, set shouldRefreshChildren(x) {
        this._shouldRefreshChildren = x;
        if (x && this.expanded)
            this.expand();
    }, get selected() {
        return this._selected;
    }, set selected(x) {
        if (x)
            this.select(); else
            this.deselect();
    }, get expanded() {
        return this._expanded;
    }, set expanded(x) {
        if (x)
            this.expand(); else
            this.collapse();
    }, refresh: function () {
        if (!this.dataGrid)
            this._element = null;
        if (!this._element)
            return;
        this.createCells();
    }, _createTDWithClass: function (className) {
        var cell = document.createElementWithClass("td", className);
        var cellClass = this.dataGrid._cellClass;
        if (cellClass)
            cell.classList.add(cellClass);
        return cell;
    }, createTD: function (columnIdentifier) {
        var cell = this._createTDWithClass(columnIdentifier + "-column");
        cell.columnIdentifier_ = columnIdentifier;
        var alignment = this.dataGrid._columns[columnIdentifier].align;
        if (alignment)
            cell.classList.add(alignment);
        return cell;
    }, createCell: function (columnIdentifier) {
        var cell = this.createTD(columnIdentifier);
        var data = this.data[columnIdentifier];
        if (data instanceof Node) {
            cell.appendChild(data);
        } else {
            cell.textContent = data;
            if (this.dataGrid._columns[columnIdentifier].longText)
                cell.title = data;
        }
        if (columnIdentifier === this.dataGrid.disclosureColumnIdentifier) {
            cell.classList.add("disclosure");
            if (this.leftPadding)
                cell.style.setProperty("padding-left", this.leftPadding + "px");
        }
        return cell;
    }, nodeSelfHeight: function () {
        return 16;
    }, appendChild: function (child) {
        this.insertChild(child, this.children.length);
    }, insertChild: function (child, index) {
        if (!child)
            throw("insertChild: Node can't be undefined or null.");
        if (child.parent === this)
            throw("insertChild: Node is already a child of this node.");
        if (child.parent)
            child.parent.removeChild(child);
        this.children.splice(index, 0, child);
        this.hasChildren = true;
        child.parent = this;
        child.dataGrid = this.dataGrid;
        child.recalculateSiblings(index);
        child._depth = undefined;
        child._revealed = undefined;
        child._attached = false;
        child._shouldRefreshChildren = true;
        var current = child.children[0];
        while (current) {
            current.dataGrid = this.dataGrid;
            current._depth = undefined;
            current._revealed = undefined;
            current._attached = false;
            current._shouldRefreshChildren = true;
            current = current.traverseNextNode(false, child, true);
        }
        if (this.expanded)
            child._attach();
        if (!this.revealed)
            child.revealed = false;
    }, removeChild: function (child) {
        if (!child)
            throw("removeChild: Node can't be undefined or null.");
        if (child.parent !== this)
            throw("removeChild: Node is not a child of this node.");
        child.deselect();
        child._detach();
        this.children.remove(child, true);
        if (child.previousSibling)
            child.previousSibling.nextSibling = child.nextSibling;
        if (child.nextSibling)
            child.nextSibling.previousSibling = child.previousSibling;
        child.dataGrid = null;
        child.parent = null;
        child.nextSibling = null;
        child.previousSibling = null;
        if (this.children.length <= 0)
            this.hasChildren = false;
    }, removeChildren: function () {
        for (var i = 0; i < this.children.length; ++i) {
            var child = this.children[i];
            child.deselect();
            child._detach();
            child.dataGrid = null;
            child.parent = null;
            child.nextSibling = null;
            child.previousSibling = null;
        }
        this.children = [];
        this.hasChildren = false;
    }, recalculateSiblings: function (myIndex) {
        if (!this.parent)
            return;
        var previousChild = this.parent.children[myIndex - 1] || null;
        if (previousChild)
            previousChild.nextSibling = this;
        this.previousSibling = previousChild;
        var nextChild = this.parent.children[myIndex + 1] || null;
        if (nextChild)
            nextChild.previousSibling = this;
        this.nextSibling = nextChild;
    }, collapse: function () {
        if (this._isRoot)
            return;
        if (this._element)
            this._element.classList.remove("expanded");
        this._expanded = false;
        for (var i = 0; i < this.children.length; ++i)
            this.children[i].revealed = false;
    }, collapseRecursively: function () {
        var item = this;
        while (item) {
            if (item.expanded)
                item.collapse();
            item = item.traverseNextNode(false, this, true);
        }
    }, populate: function () {
    }, expand: function () {
        if (!this.hasChildren || this.expanded)
            return;
        if (this._isRoot)
            return;
        if (this.revealed && !this._shouldRefreshChildren)
            for (var i = 0; i < this.children.length; ++i)
                this.children[i].revealed = true;
        if (this._shouldRefreshChildren) {
            for (var i = 0; i < this.children.length; ++i)
                this.children[i]._detach();
            this.populate();
            if (this._attached) {
                for (var i = 0; i < this.children.length; ++i) {
                    var child = this.children[i];
                    if (this.revealed)
                        child.revealed = true;
                    child._attach();
                }
            }
            this._shouldRefreshChildren = false;
        }
        if (this._element)
            this._element.classList.add("expanded");
        this._expanded = true;
    }, expandRecursively: function () {
        var item = this;
        while (item) {
            item.expand();
            item = item.traverseNextNode(false, this);
        }
    }, reveal: function () {
        if (this._isRoot)
            return;
        var currentAncestor = this.parent;
        while (currentAncestor && !currentAncestor._isRoot) {
            if (!currentAncestor.expanded)
                currentAncestor.expand();
            currentAncestor = currentAncestor.parent;
        }
        this.element().scrollIntoViewIfNeeded(false);
    }, select: function (supressSelectedEvent) {
        if (!this.dataGrid || !this.selectable || this.selected)
            return;
        if (this.dataGrid.selectedNode)
            this.dataGrid.selectedNode.deselect();
        this._selected = true;
        this.dataGrid.selectedNode = this;
        if (this._element)
            this._element.classList.add("selected");
        if (!supressSelectedEvent)
            this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Events.SelectedNode);
    }, revealAndSelect: function () {
        if (this._isRoot)
            return;
        this.reveal();
        this.select();
    }, deselect: function (supressDeselectedEvent) {
        if (!this.dataGrid || this.dataGrid.selectedNode !== this || !this.selected)
            return;
        this._selected = false;
        this.dataGrid.selectedNode = null;
        if (this._element)
            this._element.classList.remove("selected");
        if (!supressDeselectedEvent)
            this.dataGrid.dispatchEventToListeners(WebInspector.DataGrid.Events.DeselectedNode);
    }, traverseNextNode: function (skipHidden, stayWithin, dontPopulate, info) {
        if (!dontPopulate && this.hasChildren)
            this.populate();
        if (info)
            info.depthChange = 0;
        var node = (!skipHidden || this.revealed) ? this.children[0] : null;
        if (node && (!skipHidden || this.expanded)) {
            if (info)
                info.depthChange = 1;
            return node;
        }
        if (this === stayWithin)
            return null;
        node = (!skipHidden || this.revealed) ? this.nextSibling : null;
        if (node)
            return node;
        node = this;
        while (node && !node._isRoot && !((!skipHidden || node.revealed) ? node.nextSibling : null) && node.parent !== stayWithin) {
            if (info)
                info.depthChange -= 1;
            node = node.parent;
        }
        if (!node)
            return null;
        return (!skipHidden || node.revealed) ? node.nextSibling : null;
    }, traversePreviousNode: function (skipHidden, dontPopulate) {
        var node = (!skipHidden || this.revealed) ? this.previousSibling : null;
        if (!dontPopulate && node && node.hasChildren)
            node.populate();
        while (node && ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null)) {
            if (!dontPopulate && node.hasChildren)
                node.populate();
            node = ((!skipHidden || (node.revealed && node.expanded)) ? node.children[node.children.length - 1] : null);
        }
        if (node)
            return node;
        if (!this.parent || this.parent._isRoot)
            return null;
        return this.parent;
    }, isEventWithinDisclosureTriangle: function (event) {
        if (!this.hasChildren)
            return false;
        var cell = event.target.enclosingNodeOrSelfWithNodeName("td");
        if (!cell.classList.contains("disclosure"))
            return false;
        var left = cell.totalOffsetLeft() + this.leftPadding;
        return event.pageX >= left && event.pageX <= left + this.disclosureToggleWidth;
    }, _attach: function () {
        if (!this.dataGrid || this._attached)
            return;
        this._attached = true;
        var nextNode = null;
        var previousNode = this.traversePreviousNode(true, true);
        var previousElement = previousNode ? previousNode.element() : this.dataGrid._topFillerRow;
        this.dataGrid.dataTableBody.insertBefore(this.element(), previousElement.nextSibling);
        if (this.expanded)
            for (var i = 0; i < this.children.length; ++i)
                this.children[i]._attach();
    }, _detach: function () {
        if (!this._attached)
            return;
        this._attached = false;
        if (this._element)
            this._element.remove();
        for (var i = 0; i < this.children.length; ++i)
            this.children[i]._detach();
        this.wasDetached();
    }, wasDetached: function () {
    }, savePosition: function () {
        if (this._savedPosition)
            return;
        if (!this.parent)
            throw("savePosition: Node must have a parent.");
        this._savedPosition = {parent: this.parent, index: this.parent.children.indexOf(this)};
    }, restorePosition: function () {
        if (!this._savedPosition)
            return;
        if (this.parent !== this._savedPosition.parent)
            this._savedPosition.parent.insertChild(this, this._savedPosition.index);
        this._savedPosition = null;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.CreationDataGridNode = function (data, hasChildren) {
    WebInspector.DataGridNode.call(this, data, hasChildren);
    this.isCreationNode = true;
}
WebInspector.CreationDataGridNode.prototype = {
    makeNormal: function () {
        this.isCreationNode = false;
    }, __proto__: WebInspector.DataGridNode.prototype
}
WebInspector.ShowMoreDataGridNode = function (callback, startPosition, endPosition, chunkSize) {
    WebInspector.DataGridNode.call(this, {summaryRow: true}, false);
    this._callback = callback;
    this._startPosition = startPosition;
    this._endPosition = endPosition;
    this._chunkSize = chunkSize;
    this.showNext = document.createElement("button");
    this.showNext.setAttribute("type", "button");
    this.showNext.addEventListener("click", this._showNextChunk.bind(this), false);
    this.showNext.textContent = WebInspector.UIString("Show %d before", this._chunkSize);
    this.showAll = document.createElement("button");
    this.showAll.setAttribute("type", "button");
    this.showAll.addEventListener("click", this._showAll.bind(this), false);
    this.showLast = document.createElement("button");
    this.showLast.setAttribute("type", "button");
    this.showLast.addEventListener("click", this._showLastChunk.bind(this), false);
    this.showLast.textContent = WebInspector.UIString("Show %d after", this._chunkSize);
    this._updateLabels();
    this.selectable = false;
}
WebInspector.ShowMoreDataGridNode.prototype = {
    _showNextChunk: function () {
        this._callback(this._startPosition, this._startPosition + this._chunkSize);
    }, _showAll: function () {
        this._callback(this._startPosition, this._endPosition);
    }, _showLastChunk: function () {
        this._callback(this._endPosition - this._chunkSize, this._endPosition);
    }, _updateLabels: function () {
        var totalSize = this._endPosition - this._startPosition;
        if (totalSize > this._chunkSize) {
            this.showNext.classList.remove("hidden");
            this.showLast.classList.remove("hidden");
        } else {
            this.showNext.classList.add("hidden");
            this.showLast.classList.add("hidden");
        }
        this.showAll.textContent = WebInspector.UIString("Show all %d", totalSize);
    }, createCells: function () {
        this._hasCells = false;
        WebInspector.DataGridNode.prototype.createCells.call(this);
    }, createCell: function (columnIdentifier) {
        var cell = this.createTD(columnIdentifier);
        if (!this._hasCells) {
            this._hasCells = true;
            if (this.depth)
                cell.style.setProperty("padding-left", (this.depth * this.dataGrid.indentWidth) + "px");
            cell.appendChild(this.showNext);
            cell.appendChild(this.showAll);
            cell.appendChild(this.showLast);
        }
        return cell;
    }, setStartPosition: function (from) {
        this._startPosition = from;
        this._updateLabels();
    }, setEndPosition: function (to) {
        this._endPosition = to;
        this._updateLabels();
    }, nodeSelfHeight: function () {
        return 32;
    }, dispose: function () {
    }, __proto__: WebInspector.DataGridNode.prototype
}
WebInspector.ViewportDataGrid = function (columnsArray, editCallback, deleteCallback, refreshCallback, contextMenuCallback) {
    WebInspector.DataGrid.call(this, columnsArray, editCallback, deleteCallback, refreshCallback, contextMenuCallback);
    this._scrollContainer.addEventListener("scroll", this._onScroll.bind(this), true);
    this._scrollContainer.addEventListener("mousewheel", this._onWheel.bind(this), true);
    this._visibleNodes = [];
    this._updateScheduled = false;
    this._inline = false;
    this._wheelTarget = null;
    this._hiddenWheelTarget = null;
    this.setRootNode(new WebInspector.ViewportDataGridNode());
}
WebInspector.ViewportDataGrid.prototype = {
    onResize: function () {
        this.scheduleUpdate();
    }, _onWheel: function (event) {
        this._wheelTarget = event.target ? event.target.enclosingNodeOrSelfWithNodeName("tr") : null;
    }, _onScroll: function (event) {
        this.scheduleUpdate();
    }, scheduleUpdate: function () {
        if (this._updateScheduled)
            return;
        this._updateScheduled = true;
        window.requestAnimationFrame(this._update.bind(this));
    }, renderInline: function () {
        this._inline = true;
        WebInspector.DataGrid.prototype.renderInline.call(this);
        this._update();
    }, _calculateVisibleNodes: function (scrollHeight, scrollTop) {
        var nodes = this._rootNode.children;
        if (this._inline)
            return {topPadding: 0, bottomPadding: 0, visibleNodes: nodes};
        var size = nodes.length;
        var i = 0;
        var y = 0;
        for (; i < size && y + nodes[i].nodeSelfHeight() < scrollTop; ++i)
            y += nodes[i].nodeSelfHeight();
        var start = i;
        var topPadding = y;
        for (; i < size && y < scrollTop + scrollHeight; ++i)
            y += nodes[i].nodeSelfHeight();
        var end = i;
        var bottomPadding = 0;
        for (; i < size; ++i)
            bottomPadding += nodes[i].nodeSelfHeight();
        return {topPadding: topPadding, bottomPadding: bottomPadding, visibleNodes: nodes.slice(start, end)};
    }, _update: function () {
        this._updateScheduled = false;
        var viewportState = this._calculateVisibleNodes(this._scrollContainer.offsetHeight, this._scrollContainer.scrollTop);
        var visibleNodes = viewportState.visibleNodes;
        var visibleNodesSet = Set.fromArray(visibleNodes);
        if (this._hiddenWheelTarget && this._hiddenWheelTarget !== this._wheelTarget) {
            this._hiddenWheelTarget.remove();
            this._hiddenWheelTarget = null;
        }
        for (var i = 0; i < this._visibleNodes.length; ++i) {
            var oldNode = this._visibleNodes[i];
            if (!visibleNodesSet.contains(oldNode)) {
                var element = oldNode.element();
                if (element === this._wheelTarget)
                    this._hiddenWheelTarget = oldNode.abandonElement(); else
                    element.remove();
                oldNode.wasDetached();
            }
        }
        var previousElement = this._topFillerRow;
        if (previousElement.nextSibling === this._hiddenWheelTarget)
            previousElement = this._hiddenWheelTarget;
        var tBody = this.dataTableBody;
        for (var i = 0; i < visibleNodes.length; ++i) {
            var element = visibleNodes[i].element();
            tBody.insertBefore(element, previousElement.nextSibling);
            previousElement = element;
        }
        this.setVerticalPadding(viewportState.topPadding, viewportState.bottomPadding);
        this._visibleNodes = visibleNodes;
    }, _revealViewportNode: function (node) {
        var nodes = this._rootNode.children;
        var index = nodes.indexOf(node);
        if (index === -1)
            return;
        var fromY = 0;
        for (var i = 0; i < index; ++i)
            fromY += nodes[i].nodeSelfHeight();
        var toY = fromY + node.nodeSelfHeight();
        var scrollTop = this._scrollContainer.scrollTop;
        if (scrollTop > fromY)
            scrollTop = fromY; else if (scrollTop + this._scrollContainer.offsetHeight < toY)
            scrollTop = toY - this._scrollContainer.offsetHeight;
        this._scrollContainer.scrollTop = scrollTop;
    }, __proto__: WebInspector.DataGrid.prototype
}
WebInspector.ViewportDataGridNode = function (data) {
    WebInspector.DataGridNode.call(this, data, false);
    this._stale = false;
}
WebInspector.ViewportDataGridNode.prototype = {
    element: function () {
        if (!this._element) {
            this.createElement();
            this.createCells();
            this._stale = false;
        }
        if (this._stale) {
            this.createCells();
            this._stale = false;
        }
        return (this._element);
    }, insertChild: function (child, index) {
        child.parent = this;
        child.dataGrid = this.dataGrid;
        this.children.splice(index, 0, child);
        child.recalculateSiblings(index);
        this.dataGrid.scheduleUpdate();
    }, removeChild: function (child) {
        child.deselect();
        this.children.remove(child, true);
        if (child.previousSibling)
            child.previousSibling.nextSibling = child.nextSibling;
        if (child.nextSibling)
            child.nextSibling.previousSibling = child.previousSibling;
        this.dataGrid.scheduleUpdate();
    }, removeChildren: function () {
        for (var i = 0; i < this.children.length; ++i)
            this.children[i].deselect();
        this.children = [];
        this.dataGrid.scheduleUpdate();
    }, expand: function () {
    }, refresh: function () {
        if (this._element && this._element.parentElement) {
            this._stale = true;
            this.dataGrid.scheduleUpdate();
        } else {
            this._element = null;
        }
    }, abandonElement: function () {
        var result = this._element;
        if (result)
            result.style.display = "none";
        this._element = null;
        return result;
    }, reveal: function () {
        this.dataGrid._revealViewportNode(this);
    }, __proto__: WebInspector.DataGridNode.prototype
}
WebInspector.SortableDataGrid = function (columnsArray, editCallback, deleteCallback, refreshCallback, contextMenuCallback) {
    WebInspector.ViewportDataGrid.call(this, columnsArray, editCallback, deleteCallback, refreshCallback, contextMenuCallback);
    this._sortingFunction = WebInspector.SortableDataGrid.TrivialComparator;
    this.setRootNode(new WebInspector.SortableDataGridNode());
}
WebInspector.SortableDataGrid.NodeComparator;
WebInspector.SortableDataGrid.TrivialComparator = function (a, b) {
    return 0;
}
WebInspector.SortableDataGrid.NumericComparator = function (columnIdentifier, a, b) {
    var aValue = a.data[columnIdentifier];
    var bValue = b.data[columnIdentifier];
    var aNumber = Number(aValue instanceof Node ? aValue.textContent : aValue);
    var bNumber = Number(bValue instanceof Node ? bValue.textContent : bValue);
    return aNumber < bNumber ? -1 : (aNumber > bNumber ? 1 : 0);
}
WebInspector.SortableDataGrid.StringComparator = function (columnIdentifier, a, b) {
    var aValue = a.data[columnIdentifier];
    var bValue = b.data[columnIdentifier];
    var aString = aValue instanceof Node ? aValue.textContent : String(aValue);
    var bString = bValue instanceof Node ? bValue.textContent : String(bValue);
    return aString < bString ? -1 : (aString > bString ? 1 : 0);
}
WebInspector.SortableDataGrid.Comparator = function (comparator, reverseMode, a, b) {
    return reverseMode ? comparator(b, a) : comparator(a, b);
}
WebInspector.SortableDataGrid.create = function (columnNames, values) {
    var numColumns = columnNames.length;
    if (!numColumns)
        return null;
    var columns = [];
    for (var i = 0; i < columnNames.length; ++i)
        columns.push({title: columnNames[i], width: columnNames[i].length, sortable: true});
    var nodes = [];
    for (var i = 0; i < values.length / numColumns; ++i) {
        var data = {};
        for (var j = 0; j < columnNames.length; ++j)
            data[j] = values[numColumns * i + j];
        var node = new WebInspector.SortableDataGridNode(data);
        node.selectable = false;
        nodes.push(node);
    }
    var dataGrid = new WebInspector.SortableDataGrid(columns);
    var length = nodes.length;
    var rootNode = dataGrid.rootNode();
    for (var i = 0; i < length; ++i)
        rootNode.appendChild(nodes[i]);
    dataGrid.addEventListener(WebInspector.DataGrid.Events.SortingChanged, sortDataGrid);
    function sortDataGrid() {
        var nodes = dataGrid.rootNode().children;
        var sortColumnIdentifier = dataGrid.sortColumnIdentifier();
        if (!sortColumnIdentifier)
            return;
        var columnIsNumeric = true;
        for (var i = 0; i < nodes.length; i++) {
            var value = nodes[i].data[sortColumnIdentifier];
            if (isNaN(value instanceof Node ? value.textContent : value)) {
                columnIsNumeric = false;
                break;
            }
        }
        var comparator = columnIsNumeric ? WebInspector.SortableDataGrid.NumericComparator : WebInspector.SortableDataGrid.StringComparator;
        dataGrid.sortNodes(comparator.bind(null, sortColumnIdentifier), !dataGrid.isSortOrderAscending());
    }

    return dataGrid;
}
WebInspector.SortableDataGrid.prototype = {
    insertChild: function (node) {
        var parentNode = this.rootNode();
        parentNode.insertChild(node, parentNode.children.upperBound(node, this._sortingFunction));
    }, sortNodes: function (comparator, reverseMode) {
        this._sortingFunction = WebInspector.SortableDataGrid.Comparator.bind(null, comparator, reverseMode);
        var children = this._rootNode.children;
        children.sort(this._sortingFunction);
        for (var i = 0; i < children.length; ++i)
            children[i].recalculateSiblings(i);
        this.scheduleUpdate();
    }, __proto__: WebInspector.ViewportDataGrid.prototype
}
WebInspector.SortableDataGridNode = function (data) {
    WebInspector.ViewportDataGridNode.call(this, data);
}
WebInspector.SortableDataGridNode.prototype = {__proto__: WebInspector.ViewportDataGridNode.prototype}
WebInspector.CookiesTable = function (expandable, refreshCallback, selectedCallback) {
    WebInspector.VBox.call(this);
    var readOnly = expandable;
    this._refreshCallback = refreshCallback;
    var columns = [{id: "name", title: WebInspector.UIString("Name"), sortable: true, disclosure: expandable, sort: WebInspector.DataGrid.Order.Ascending, longText: true, weight: 24}, {
        id: "value",
        title: WebInspector.UIString("Value"),
        sortable: true,
        longText: true,
        weight: 34
    }, {id: "domain", title: WebInspector.UIString("Domain"), sortable: true, weight: 7}, {id: "path", title: WebInspector.UIString("Path"), sortable: true, weight: 7}, {
        id: "expires",
        title: WebInspector.UIString("Expires / Max-Age"),
        sortable: true,
        weight: 7
    }, {id: "size", title: WebInspector.UIString("Size"), sortable: true, align: WebInspector.DataGrid.Align.Right, weight: 7}, {
        id: "httpOnly",
        title: WebInspector.UIString("HTTP"),
        sortable: true,
        align: WebInspector.DataGrid.Align.Center,
        weight: 7
    }, {id: "secure", title: WebInspector.UIString("Secure"), sortable: true, align: WebInspector.DataGrid.Align.Center, weight: 7}];
    if (readOnly)
        this._dataGrid = new WebInspector.DataGrid(columns); else
        this._dataGrid = new WebInspector.DataGrid(columns, undefined, this._onDeleteCookie.bind(this), refreshCallback, this._onContextMenu.bind(this));
    this._dataGrid.setName("cookiesTable");
    this._dataGrid.addEventListener(WebInspector.DataGrid.Events.SortingChanged, this._rebuildTable, this);
    if (selectedCallback)
        this._dataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode, selectedCallback, this);
    this._nextSelectedCookie = (null);
    this._dataGrid.show(this.element);
    this._data = [];
}
WebInspector.CookiesTable.prototype = {
    _clearAndRefresh: function (domain) {
        this.clear(domain);
        this._refresh();
    }, _onContextMenu: function (contextMenu, node) {
        if (node === this._dataGrid.creationNode)
            return;
        var cookie = node.cookie;
        var domain = cookie.domain();
        if (domain)
            contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Clear all from \"%s\"" : "Clear All from \"%s\"", domain), this._clearAndRefresh.bind(this, domain));
        contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Clear all" : "Clear All"), this._clearAndRefresh.bind(this, null));
    }, setCookies: function (cookies) {
        this.setCookieFolders([{cookies: cookies}]);
    }, setCookieFolders: function (cookieFolders) {
        this._data = cookieFolders;
        this._rebuildTable();
    }, selectedCookie: function () {
        var node = this._dataGrid.selectedNode;
        return node ? node.cookie : null;
    }, clear: function (domain) {
        for (var i = 0, length = this._data.length; i < length; ++i) {
            var cookies = this._data[i].cookies;
            for (var j = 0, cookieCount = cookies.length; j < cookieCount; ++j) {
                if (!domain || cookies[j].domain() === domain)
                    cookies[j].remove();
            }
        }
    }, _rebuildTable: function () {
        var selectedCookie = this._nextSelectedCookie || this.selectedCookie();
        this._nextSelectedCookie = null;
        this._dataGrid.rootNode().removeChildren();
        for (var i = 0; i < this._data.length; ++i) {
            var item = this._data[i];
            if (item.folderName) {
                var groupData = {name: item.folderName, value: "", domain: "", path: "", expires: "", size: this._totalSize(item.cookies), httpOnly: "", secure: ""};
                var groupNode = new WebInspector.DataGridNode(groupData);
                groupNode.selectable = true;
                this._dataGrid.rootNode().appendChild(groupNode);
                groupNode.element().classList.add("row-group");
                this._populateNode(groupNode, item.cookies, selectedCookie);
                groupNode.expand();
            } else
                this._populateNode(this._dataGrid.rootNode(), item.cookies, selectedCookie);
        }
    }, _populateNode: function (parentNode, cookies, selectedCookie) {
        parentNode.removeChildren();
        if (!cookies)
            return;
        this._sortCookies(cookies);
        for (var i = 0; i < cookies.length; ++i) {
            var cookie = cookies[i];
            var cookieNode = this._createGridNode(cookie);
            parentNode.appendChild(cookieNode);
            if (selectedCookie && selectedCookie.name() === cookie.name() && selectedCookie.domain() === cookie.domain() && selectedCookie.path() === cookie.path())
                cookieNode.select();
        }
    }, _totalSize: function (cookies) {
        var totalSize = 0;
        for (var i = 0; cookies && i < cookies.length; ++i)
            totalSize += cookies[i].size();
        return totalSize;
    }, _sortCookies: function (cookies) {
        var sortDirection = this._dataGrid.isSortOrderAscending() ? 1 : -1;

        function compareTo(getter, cookie1, cookie2) {
            return sortDirection * (getter.apply(cookie1) + "").compareTo(getter.apply(cookie2) + "")
        }

        function numberCompare(getter, cookie1, cookie2) {
            return sortDirection * (getter.apply(cookie1) - getter.apply(cookie2));
        }

        function expiresCompare(cookie1, cookie2) {
            if (cookie1.session() !== cookie2.session())
                return sortDirection * (cookie1.session() ? 1 : -1);
            if (cookie1.session())
                return 0;
            if (cookie1.maxAge() && cookie2.maxAge())
                return sortDirection * (cookie1.maxAge() - cookie2.maxAge());
            if (cookie1.expires() && cookie2.expires())
                return sortDirection * (cookie1.expires() - cookie2.expires());
            return sortDirection * (cookie1.expires() ? 1 : -1);
        }

        var comparator;
        switch (this._dataGrid.sortColumnIdentifier()) {
            case"name":
                comparator = compareTo.bind(null, WebInspector.Cookie.prototype.name);
                break;
            case"value":
                comparator = compareTo.bind(null, WebInspector.Cookie.prototype.value);
                break;
            case"domain":
                comparator = compareTo.bind(null, WebInspector.Cookie.prototype.domain);
                break;
            case"path":
                comparator = compareTo.bind(null, WebInspector.Cookie.prototype.path);
                break;
            case"expires":
                comparator = expiresCompare;
                break;
            case"size":
                comparator = numberCompare.bind(null, WebInspector.Cookie.prototype.size);
                break;
            case"httpOnly":
                comparator = compareTo.bind(null, WebInspector.Cookie.prototype.httpOnly);
                break;
            case"secure":
                comparator = compareTo.bind(null, WebInspector.Cookie.prototype.secure);
                break;
            default:
                compareTo.bind(null, WebInspector.Cookie.prototype.name);
        }
        cookies.sort(comparator);
    }, _createGridNode: function (cookie) {
        var data = {};
        data.name = cookie.name();
        data.value = cookie.value();
        if (cookie.type() === WebInspector.Cookie.Type.Request) {
            data.domain = WebInspector.UIString("N/A");
            data.path = WebInspector.UIString("N/A");
            data.expires = WebInspector.UIString("N/A");
        } else {
            data.domain = cookie.domain() || "";
            data.path = cookie.path() || "";
            if (cookie.maxAge())
                data.expires = Number.secondsToString(parseInt(cookie.maxAge(), 10)); else if (cookie.expires())
                data.expires = new Date(cookie.expires()).toISOString(); else
                data.expires = WebInspector.UIString("Session");
        }
        data.size = cookie.size();
        const checkmark = "\u2713";
        data.httpOnly = (cookie.httpOnly() ? checkmark : "");
        data.secure = (cookie.secure() ? checkmark : "");
        var node = new WebInspector.DataGridNode(data);
        node.cookie = cookie;
        node.selectable = true;
        return node;
    }, _onDeleteCookie: function (node) {
        var cookie = node.cookie;
        var neighbour = node.traverseNextNode() || node.traversePreviousNode();
        if (neighbour)
            this._nextSelectedCookie = neighbour.cookie;
        cookie.remove();
        this._refresh();
    }, _refresh: function () {
        if (this._refreshCallback)
            this._refreshCallback();
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.ApplicationCacheModel = function (target) {
    WebInspector.SDKObject.call(this, target);
    target.registerApplicationCacheDispatcher(new WebInspector.ApplicationCacheDispatcher(this));
    this._agent = target.applicationCacheAgent();
    this._agent.enable();
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this);
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameDetached, this);
    this._statuses = {};
    this._manifestURLsByFrame = {};
    this._mainFrameNavigated();
    this._onLine = true;
}
WebInspector.ApplicationCacheModel.EventTypes = {FrameManifestStatusUpdated: "FrameManifestStatusUpdated", FrameManifestAdded: "FrameManifestAdded", FrameManifestRemoved: "FrameManifestRemoved", NetworkStateChanged: "NetworkStateChanged"}
WebInspector.ApplicationCacheModel.prototype = {
    _frameNavigated: function (event) {
        var frame = (event.data);
        if (frame.isMainFrame()) {
            this._mainFrameNavigated();
            return;
        }
        this._agent.getManifestForFrame(frame.id, this._manifestForFrameLoaded.bind(this, frame.id));
    }, _frameDetached: function (event) {
        var frame = (event.data);
        this._frameManifestRemoved(frame.id);
    }, _mainFrameNavigated: function () {
        this._agent.getFramesWithManifests(this._framesWithManifestsLoaded.bind(this));
    }, _manifestForFrameLoaded: function (frameId, error, manifestURL) {
        if (error) {
            console.error(error);
            return;
        }
        if (!manifestURL)
            this._frameManifestRemoved(frameId);
    }, _framesWithManifestsLoaded: function (error, framesWithManifests) {
        if (error) {
            console.error(error);
            return;
        }
        for (var i = 0; i < framesWithManifests.length; ++i)
            this._frameManifestUpdated(framesWithManifests[i].frameId, framesWithManifests[i].manifestURL, framesWithManifests[i].status);
    }, _frameManifestUpdated: function (frameId, manifestURL, status) {
        if (status === applicationCache.UNCACHED) {
            this._frameManifestRemoved(frameId);
            return;
        }
        if (!manifestURL)
            return;
        if (this._manifestURLsByFrame[frameId] && manifestURL !== this._manifestURLsByFrame[frameId])
            this._frameManifestRemoved(frameId);
        var statusChanged = this._statuses[frameId] !== status;
        this._statuses[frameId] = status;
        if (!this._manifestURLsByFrame[frameId]) {
            this._manifestURLsByFrame[frameId] = manifestURL;
            this.dispatchEventToListeners(WebInspector.ApplicationCacheModel.EventTypes.FrameManifestAdded, frameId);
        }
        if (statusChanged)
            this.dispatchEventToListeners(WebInspector.ApplicationCacheModel.EventTypes.FrameManifestStatusUpdated, frameId);
    }, _frameManifestRemoved: function (frameId) {
        if (!this._manifestURLsByFrame[frameId])
            return;
        var manifestURL = this._manifestURLsByFrame[frameId];
        delete this._manifestURLsByFrame[frameId];
        delete this._statuses[frameId];
        this.dispatchEventToListeners(WebInspector.ApplicationCacheModel.EventTypes.FrameManifestRemoved, frameId);
    }, frameManifestURL: function (frameId) {
        return this._manifestURLsByFrame[frameId] || "";
    }, frameManifestStatus: function (frameId) {
        return this._statuses[frameId] || applicationCache.UNCACHED;
    }, get onLine() {
        return this._onLine;
    }, _statusUpdated: function (frameId, manifestURL, status) {
        this._frameManifestUpdated(frameId, manifestURL, status);
    }, requestApplicationCache: function (frameId, callback) {
        function callbackWrapper(error, applicationCache) {
            if (error) {
                console.error(error);
                callback(null);
                return;
            }
            callback(applicationCache);
        }

        this._agent.getApplicationCacheForFrame(frameId, callbackWrapper);
    }, _networkStateUpdated: function (isNowOnline) {
        this._onLine = isNowOnline;
        this.dispatchEventToListeners(WebInspector.ApplicationCacheModel.EventTypes.NetworkStateChanged, isNowOnline);
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.ApplicationCacheDispatcher = function (applicationCacheModel) {
    this._applicationCacheModel = applicationCacheModel;
}
WebInspector.ApplicationCacheDispatcher.prototype = {
    applicationCacheStatusUpdated: function (frameId, manifestURL, status) {
        this._applicationCacheModel._statusUpdated(frameId, manifestURL, status);
    }, networkStateUpdated: function (isNowOnline) {
        this._applicationCacheModel._networkStateUpdated(isNowOnline);
    }
}
WebInspector.IndexedDBModel = function (target) {
    WebInspector.SDKObject.call(this, target);
    this._agent = target.indexedDBAgent();
    this._agent.enable();
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginAdded, this._securityOriginAdded, this);
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginRemoved, this._securityOriginRemoved, this);
    this._databases = new Map();
    this._databaseNamesBySecurityOrigin = {};
    this._reset();
}
WebInspector.IndexedDBModel.KeyTypes = {NumberType: "number", StringType: "string", DateType: "date", ArrayType: "array"};
WebInspector.IndexedDBModel.KeyPathTypes = {NullType: "null", StringType: "string", ArrayType: "array"};
WebInspector.IndexedDBModel.keyFromIDBKey = function (idbKey) {
    if (typeof(idbKey) === "undefined" || idbKey === null)
        return null;
    var key = {};
    switch (typeof(idbKey)) {
        case"number":
            key.number = idbKey;
            key.type = WebInspector.IndexedDBModel.KeyTypes.NumberType;
            break;
        case"string":
            key.string = idbKey;
            key.type = WebInspector.IndexedDBModel.KeyTypes.StringType;
            break;
        case"object":
            if (idbKey instanceof Date) {
                key.date = idbKey.getTime();
                key.type = WebInspector.IndexedDBModel.KeyTypes.DateType;
            } else if (idbKey instanceof Array) {
                key.array = [];
                for (var i = 0; i < idbKey.length; ++i)
                    key.array.push(WebInspector.IndexedDBModel.keyFromIDBKey(idbKey[i]));
                key.type = WebInspector.IndexedDBModel.KeyTypes.ArrayType;
            }
            break;
        default:
            return null;
    }
    return key;
}
WebInspector.IndexedDBModel.keyRangeFromIDBKeyRange = function (idbKeyRange) {
    if (typeof idbKeyRange === "undefined" || idbKeyRange === null)
        return null;
    var keyRange = {};
    keyRange.lower = WebInspector.IndexedDBModel.keyFromIDBKey(idbKeyRange.lower);
    keyRange.upper = WebInspector.IndexedDBModel.keyFromIDBKey(idbKeyRange.upper);
    keyRange.lowerOpen = idbKeyRange.lowerOpen;
    keyRange.upperOpen = idbKeyRange.upperOpen;
    return keyRange;
}
WebInspector.IndexedDBModel.idbKeyPathFromKeyPath = function (keyPath) {
    var idbKeyPath;
    switch (keyPath.type) {
        case WebInspector.IndexedDBModel.KeyPathTypes.NullType:
            idbKeyPath = null;
            break;
        case WebInspector.IndexedDBModel.KeyPathTypes.StringType:
            idbKeyPath = keyPath.string;
            break;
        case WebInspector.IndexedDBModel.KeyPathTypes.ArrayType:
            idbKeyPath = keyPath.array;
            break;
    }
    return idbKeyPath;
}
WebInspector.IndexedDBModel.keyPathStringFromIDBKeyPath = function (idbKeyPath) {
    if (typeof idbKeyPath === "string")
        return "\"" + idbKeyPath + "\"";
    if (idbKeyPath instanceof Array)
        return "[\"" + idbKeyPath.join("\", \"") + "\"]";
    return null;
}
WebInspector.IndexedDBModel.EventTypes = {DatabaseAdded: "DatabaseAdded", DatabaseRemoved: "DatabaseRemoved", DatabaseLoaded: "DatabaseLoaded"}
WebInspector.IndexedDBModel.prototype = {
    _reset: function () {
        for (var securityOrigin in this._databaseNamesBySecurityOrigin)
            this._removeOrigin(securityOrigin);
        var securityOrigins = this.target().resourceTreeModel.securityOrigins();
        for (var i = 0; i < securityOrigins.length; ++i)
            this._addOrigin(securityOrigins[i]);
    }, refreshDatabaseNames: function () {
        for (var securityOrigin in this._databaseNamesBySecurityOrigin)
            this._loadDatabaseNames(securityOrigin);
    }, refreshDatabase: function (databaseId) {
        this._loadDatabase(databaseId);
    }, clearObjectStore: function (databaseId, objectStoreName, callback) {
        this._agent.clearObjectStore(databaseId.securityOrigin, databaseId.name, objectStoreName, callback);
    }, _securityOriginAdded: function (event) {
        var securityOrigin = (event.data);
        this._addOrigin(securityOrigin);
    }, _securityOriginRemoved: function (event) {
        var securityOrigin = (event.data);
        this._removeOrigin(securityOrigin);
    }, _addOrigin: function (securityOrigin) {
        console.assert(!this._databaseNamesBySecurityOrigin[securityOrigin]);
        this._databaseNamesBySecurityOrigin[securityOrigin] = [];
        this._loadDatabaseNames(securityOrigin);
    }, _removeOrigin: function (securityOrigin) {
        console.assert(this._databaseNamesBySecurityOrigin[securityOrigin]);
        for (var i = 0; i < this._databaseNamesBySecurityOrigin[securityOrigin].length; ++i)
            this._databaseRemoved(securityOrigin, this._databaseNamesBySecurityOrigin[securityOrigin][i]);
        delete this._databaseNamesBySecurityOrigin[securityOrigin];
    }, _updateOriginDatabaseNames: function (securityOrigin, databaseNames) {
        var newDatabaseNames = databaseNames.keySet();
        var oldDatabaseNames = this._databaseNamesBySecurityOrigin[securityOrigin].keySet();
        this._databaseNamesBySecurityOrigin[securityOrigin] = databaseNames;
        for (var databaseName in oldDatabaseNames) {
            if (!newDatabaseNames[databaseName])
                this._databaseRemoved(securityOrigin, databaseName);
        }
        for (var databaseName in newDatabaseNames) {
            if (!oldDatabaseNames[databaseName])
                this._databaseAdded(securityOrigin, databaseName);
        }
    }, _databaseAdded: function (securityOrigin, databaseName) {
        var databaseId = new WebInspector.IndexedDBModel.DatabaseId(securityOrigin, databaseName);
        this.dispatchEventToListeners(WebInspector.IndexedDBModel.EventTypes.DatabaseAdded, databaseId);
    }, _databaseRemoved: function (securityOrigin, databaseName) {
        var databaseId = new WebInspector.IndexedDBModel.DatabaseId(securityOrigin, databaseName);
        this.dispatchEventToListeners(WebInspector.IndexedDBModel.EventTypes.DatabaseRemoved, databaseId);
    }, _loadDatabaseNames: function (securityOrigin) {
        function callback(error, databaseNames) {
            if (error) {
                console.error("IndexedDBAgent error: " + error);
                return;
            }
            if (!this._databaseNamesBySecurityOrigin[securityOrigin])
                return;
            this._updateOriginDatabaseNames(securityOrigin, databaseNames);
        }

        this._agent.requestDatabaseNames(securityOrigin, callback.bind(this));
    }, _loadDatabase: function (databaseId) {
        function callback(error, databaseWithObjectStores) {
            if (error) {
                console.error("IndexedDBAgent error: " + error);
                return;
            }
            if (!this._databaseNamesBySecurityOrigin[databaseId.securityOrigin])
                return;
            var databaseModel = new WebInspector.IndexedDBModel.Database(databaseId, databaseWithObjectStores.version, databaseWithObjectStores.intVersion);
            this._databases.put(databaseId, databaseModel);
            for (var i = 0; i < databaseWithObjectStores.objectStores.length; ++i) {
                var objectStore = databaseWithObjectStores.objectStores[i];
                var objectStoreIDBKeyPath = WebInspector.IndexedDBModel.idbKeyPathFromKeyPath(objectStore.keyPath);
                var objectStoreModel = new WebInspector.IndexedDBModel.ObjectStore(objectStore.name, objectStoreIDBKeyPath, objectStore.autoIncrement);
                for (var j = 0; j < objectStore.indexes.length; ++j) {
                    var index = objectStore.indexes[j];
                    var indexIDBKeyPath = WebInspector.IndexedDBModel.idbKeyPathFromKeyPath(index.keyPath);
                    var indexModel = new WebInspector.IndexedDBModel.Index(index.name, indexIDBKeyPath, index.unique, index.multiEntry);
                    objectStoreModel.indexes[indexModel.name] = indexModel;
                }
                databaseModel.objectStores[objectStoreModel.name] = objectStoreModel;
            }
            this.dispatchEventToListeners(WebInspector.IndexedDBModel.EventTypes.DatabaseLoaded, databaseModel);
        }

        this._agent.requestDatabase(databaseId.securityOrigin, databaseId.name, callback.bind(this));
    }, loadObjectStoreData: function (databaseId, objectStoreName, idbKeyRange, skipCount, pageSize, callback) {
        this._requestData(databaseId, databaseId.name, objectStoreName, "", idbKeyRange, skipCount, pageSize, callback);
    }, loadIndexData: function (databaseId, objectStoreName, indexName, idbKeyRange, skipCount, pageSize, callback) {
        this._requestData(databaseId, databaseId.name, objectStoreName, indexName, idbKeyRange, skipCount, pageSize, callback);
    }, _requestData: function (databaseId, databaseName, objectStoreName, indexName, idbKeyRange, skipCount, pageSize, callback) {
        function innerCallback(error, dataEntries, hasMore) {
            if (error) {
                console.error("IndexedDBAgent error: " + error);
                return;
            }
            if (!this._databaseNamesBySecurityOrigin[databaseId.securityOrigin])
                return;
            var entries = [];
            for (var i = 0; i < dataEntries.length; ++i) {
                var key = WebInspector.RemoteObject.fromLocalObject(JSON.parse(dataEntries[i].key));
                var primaryKey = WebInspector.RemoteObject.fromLocalObject(JSON.parse(dataEntries[i].primaryKey));
                var value = WebInspector.RemoteObject.fromLocalObject(JSON.parse(dataEntries[i].value));
                entries.push(new WebInspector.IndexedDBModel.Entry(key, primaryKey, value));
            }
            callback(entries, hasMore);
        }

        var keyRange = WebInspector.IndexedDBModel.keyRangeFromIDBKeyRange(idbKeyRange);
        this._agent.requestData(databaseId.securityOrigin, databaseName, objectStoreName, indexName, skipCount, pageSize, keyRange ? keyRange : undefined, innerCallback.bind(this));
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.IndexedDBModel.Entry = function (key, primaryKey, value) {
    this.key = key;
    this.primaryKey = primaryKey;
    this.value = value;
}
WebInspector.IndexedDBModel.DatabaseId = function (securityOrigin, name) {
    this.securityOrigin = securityOrigin;
    this.name = name;
}
WebInspector.IndexedDBModel.DatabaseId.prototype = {
    equals: function (databaseId) {
        return this.name === databaseId.name && this.securityOrigin === databaseId.securityOrigin;
    },
}
WebInspector.IndexedDBModel.Database = function (databaseId, version, intVersion) {
    this.databaseId = databaseId;
    this.version = version;
    this.intVersion = intVersion;
    this.objectStores = {};
}
WebInspector.IndexedDBModel.ObjectStore = function (name, keyPath, autoIncrement) {
    this.name = name;
    this.keyPath = keyPath;
    this.autoIncrement = autoIncrement;
    this.indexes = {};
}
WebInspector.IndexedDBModel.ObjectStore.prototype = {
    get keyPathString() {
        return WebInspector.IndexedDBModel.keyPathStringFromIDBKeyPath(this.keyPath);
    }
}
WebInspector.IndexedDBModel.Index = function (name, keyPath, unique, multiEntry) {
    this.name = name;
    this.keyPath = keyPath;
    this.unique = unique;
    this.multiEntry = multiEntry;
}
WebInspector.IndexedDBModel.Index.prototype = {
    get keyPathString() {
        return WebInspector.IndexedDBModel.keyPathStringFromIDBKeyPath(this.keyPath);
    }
}
WebInspector.SidebarPane = function (title) {
    WebInspector.View.call(this);
    this.setMinimumSize(25, 0);
    this.element.className = "sidebar-pane";
    this.titleElement = document.createElementWithClass("div", "sidebar-pane-toolbar");
    // NEWTON CHANGE
    this.titleElement.setAttribute('title', title);
    // NEWTON END
    this.bodyElement = this.element.createChild("div", "body");
    this._title = title;
    this._expandCallback = null;
}
WebInspector.SidebarPane.EventTypes = {wasShown: "wasShown"}
WebInspector.SidebarPane.prototype = {
    title: function () {
        return this._title;
    }, prepareContent: function (callback) {
        if (callback)
            callback();
    }, expand: function () {
        this.prepareContent(this.onContentReady.bind(this));
    }, onContentReady: function () {
        if (this._expandCallback)
            this._expandCallback(); else
            this._expandPending = true;
    }, setExpandCallback: function (callback) {
        this._expandCallback = callback;
        if (this._expandPending) {
            delete this._expandPending;
            this._expandCallback();
        }
    }, wasShown: function () {
        WebInspector.View.prototype.wasShown.call(this);
        this.dispatchEventToListeners(WebInspector.SidebarPane.EventTypes.wasShown);
    }, __proto__: WebInspector.View.prototype
}
WebInspector.SidebarPaneTitle = function (container, pane) {
    this._pane = pane;
    this.element = container.createChild("div", "sidebar-pane-title");
    // NEWTON CHANGE
    this.element.setAttribute("title", pane.title());
    // NEWTON END
    this.element.textContent = pane.title();
    this.element.tabIndex = 0;
    this.element.addEventListener("click", this._toggleExpanded.bind(this), false);
    this.element.addEventListener("keydown", this._onTitleKeyDown.bind(this), false);
    this.element.appendChild(this._pane.titleElement);
    this._pane.setExpandCallback(this._expand.bind(this));
}
WebInspector.SidebarPaneTitle.prototype = {
    _expand: function () {
        this.element.classList.add("expanded");
        this._pane.show(this.element.parentElement, (this.element.nextSibling));
    }, _collapse: function () {
        this.element.classList.remove("expanded");
        if (this._pane.element.parentNode == this.element.parentNode)
            this._pane.detach();
    }, _toggleExpanded: function () {
        if (this.element.classList.contains("expanded"))
            this._collapse(); else
            this._pane.expand();
    }, _onTitleKeyDown: function (event) {
        if (isEnterKey(event) || event.keyCode === WebInspector.KeyboardShortcut.Keys.Space.code)
            this._toggleExpanded();
    }
}
WebInspector.SidebarPaneStack = function () {
    WebInspector.View.call(this);
    this.setMinimumSize(25, 0);
    this.element.className = "sidebar-pane-stack";
    this._titleByPane = new Map();
}
WebInspector.SidebarPaneStack.prototype = {
    addPane: function (pane) {
        // NEWTON CHANGE
        pane.element.setAttribute('title', pane._title);
        pane.titleElement.setAttribute('title', pane._title);
        // NEWTON END

        this._titleByPane.put(pane, new WebInspector.SidebarPaneTitle(this.element, pane));
    }, togglePaneHidden: function (pane, hide) {
        var title = this._titleByPane.get(pane);
        if (!title)
            return;
        title.element.classList.toggle("hidden", hide);
        pane.element.classList.toggle("hidden", hide);
    }, __proto__: WebInspector.View.prototype
}
WebInspector.SidebarTabbedPane = function () {
    WebInspector.TabbedPane.call(this);
    this.setRetainTabOrder(true);
    this.element.classList.add("sidebar-tabbed-pane");
}
WebInspector.SidebarTabbedPane.prototype = {
    addPane: function (pane) {
        var title = pane.title();
        this.appendTab(title, title, pane);
        pane.element.appendChild(pane.titleElement);
        pane.setExpandCallback(this.selectTab.bind(this, title));
    }, __proto__: WebInspector.TabbedPane.prototype
}
WebInspector.DOMPresentationUtils = {}
WebInspector.DOMPresentationUtils.decorateNodeLabel = function (node, parentElement) {
    var title = node.nodeNameInCorrectCase();
    var nameElement = document.createElement("span");
    nameElement.textContent = title;
    parentElement.appendChild(nameElement);
    var idAttribute = node.getAttribute("id");
    if (idAttribute) {
        var idElement = document.createElement("span");
        parentElement.appendChild(idElement);
        var part = "#" + idAttribute;
        title += part;
        idElement.appendChild(document.createTextNode(part));
        nameElement.className = "extra";
    }
    var classAttribute = node.getAttribute("class");
    if (classAttribute) {
        var classes = classAttribute.split(/\s+/);
        var foundClasses = {};
        if (classes.length) {
            var classesElement = document.createElement("span");
            classesElement.className = "extra";
            parentElement.appendChild(classesElement);
            for (var i = 0; i < classes.length; ++i) {
                var className = classes[i];
                if (className && !(className in foundClasses)) {
                    var part = "." + className;
                    title += part;
                    classesElement.appendChild(document.createTextNode(part));
                    foundClasses[className] = true;
                }
            }
        }
    }
    parentElement.title = title;
}
WebInspector.DOMPresentationUtils.createSpansForNodeTitle = function (container, nodeTitle) {
    var match = nodeTitle.match(/([^#.]+)(#[^.]+)?(\..*)?/);
    container.createChild("span", "webkit-html-tag-name").textContent = match[1];
    if (match[2])
        container.createChild("span", "webkit-html-attribute-value").textContent = match[2];
    if (match[3])
        container.createChild("span", "webkit-html-attribute-name").textContent = match[3];
}
WebInspector.DOMPresentationUtils.linkifyNodeReference = function (node) {
    if (!node)
        return document.createTextNode(WebInspector.UIString("<node>"));
    var link = document.createElement("span");
    link.className = "node-link";
    WebInspector.DOMPresentationUtils.decorateNodeLabel(node, link);
    link.addEventListener("click", WebInspector.Revealer.reveal.bind(WebInspector.Revealer, node, undefined), false);
    link.addEventListener("mouseover", node.highlight.bind(node, undefined, undefined), false);
    link.addEventListener("mouseout", node.domModel().hideDOMNodeHighlight.bind(node.domModel()), false);
    return link;
}
WebInspector.DOMPresentationUtils.buildImagePreviewContents = function (target, imageURL, showDimensions, userCallback, precomputedDimensions) {
    var resource = target.resourceTreeModel.resourceForURL(imageURL);
    if (!resource) {
        userCallback();
        return;
    }
    var imageElement = document.createElement("img");
    imageElement.addEventListener("load", buildContent, false);
    imageElement.addEventListener("error", errorCallback, false);
    resource.populateImageSource(imageElement);
    function errorCallback() {
        userCallback();
    }

    function buildContent() {
        var container = document.createElement("table");
        container.className = "image-preview-container";
        var naturalWidth = precomputedDimensions ? precomputedDimensions.naturalWidth : imageElement.naturalWidth;
        var naturalHeight = precomputedDimensions ? precomputedDimensions.naturalHeight : imageElement.naturalHeight;
        var offsetWidth = precomputedDimensions ? precomputedDimensions.offsetWidth : naturalWidth;
        var offsetHeight = precomputedDimensions ? precomputedDimensions.offsetHeight : naturalHeight;
        var description;
        if (showDimensions) {
            if (offsetHeight === naturalHeight && offsetWidth === naturalWidth)
                description = WebInspector.UIString("%d \xd7 %d pixels", offsetWidth, offsetHeight); else
                description = WebInspector.UIString("%d \xd7 %d pixels (Natural: %d \xd7 %d pixels)", offsetWidth, offsetHeight, naturalWidth, naturalHeight);
        }
        container.createChild("tr").createChild("td", "image-container").appendChild(imageElement);
        if (description)
            container.createChild("tr").createChild("td").createChild("span", "description").textContent = description;
        userCallback(container);
    }
}
WebInspector.DOMPresentationUtils.fullQualifiedSelector = function (node, justSelector) {
    if (node.nodeType() !== Node.ELEMENT_NODE)
        return node.localName() || node.nodeName().toLowerCase();
    return WebInspector.DOMPresentationUtils.cssPath(node, justSelector);
}
WebInspector.DOMPresentationUtils.simpleSelector = function (node) {
    var lowerCaseName = node.localName() || node.nodeName().toLowerCase();
    if (node.nodeType() !== Node.ELEMENT_NODE)
        return lowerCaseName;
    if (lowerCaseName === "input" && node.getAttribute("type") && !node.getAttribute("id") && !node.getAttribute("class"))
        return lowerCaseName + "[type=\"" + node.getAttribute("type") + "\"]";
    if (node.getAttribute("id"))
        return lowerCaseName + "#" + node.getAttribute("id");
    if (node.getAttribute("class"))
        return (lowerCaseName === "div" ? "" : lowerCaseName) + "." + node.getAttribute("class").trim().replace(/\s+/g, ".");
    return lowerCaseName;
}
WebInspector.DOMPresentationUtils.cssPath = function (node, optimized) {
    if (node.nodeType() !== Node.ELEMENT_NODE)
        return "";
    var steps = [];
    var contextNode = node;
    while (contextNode) {
        var step = WebInspector.DOMPresentationUtils._cssPathStep(contextNode, !!optimized, contextNode === node);
        if (!step)
            break;
        steps.push(step);
        if (step.optimized)
            break;
        contextNode = contextNode.parentNode;
    }
    steps.reverse();
    return steps.join(" > ");
}
WebInspector.DOMPresentationUtils._cssPathStep = function (node, optimized, isTargetNode) {
    if (node.nodeType() !== Node.ELEMENT_NODE)
        return null;
    var id = node.getAttribute("id");
    if (optimized) {
        if (id)
            return new WebInspector.DOMNodePathStep(idSelector(id), true);
        var nodeNameLower = node.nodeName().toLowerCase();
        if (nodeNameLower === "body" || nodeNameLower === "head" || nodeNameLower === "html")
            return new WebInspector.DOMNodePathStep(node.nodeNameInCorrectCase(), true);
    }
    var nodeName = node.nodeNameInCorrectCase();
    if (id)
        return new WebInspector.DOMNodePathStep(nodeName + idSelector(id), true);
    var parent = node.parentNode;
    if (!parent || parent.nodeType() === Node.DOCUMENT_NODE)
        return new WebInspector.DOMNodePathStep(nodeName, true);
    function prefixedElementClassNames(node) {
        var classAttribute = node.getAttribute("class");
        if (!classAttribute)
            return [];
        return classAttribute.split(/\s+/g).filter(Boolean).map(function (name) {
            return "$" + name;
        });
    }

    function idSelector(id) {
        return "#" + escapeIdentifierIfNeeded(id);
    }

    function escapeIdentifierIfNeeded(ident) {
        if (isCSSIdentifier(ident))
            return ident;
        var shouldEscapeFirst = /^(?:[0-9]|-[0-9-]?)/.test(ident);
        var lastIndex = ident.length - 1;
        return ident.replace(/./g, function (c, i) {
            return ((shouldEscapeFirst && i === 0) || !isCSSIdentChar(c)) ? escapeAsciiChar(c, i === lastIndex) : c;
        });
    }

    function escapeAsciiChar(c, isLast) {
        return "\\" + toHexByte(c) + (isLast ? "" : " ");
    }

    function toHexByte(c) {
        var hexByte = c.charCodeAt(0).toString(16);
        if (hexByte.length === 1)
            hexByte = "0" + hexByte;
        return hexByte;
    }

    function isCSSIdentChar(c) {
        if (/[a-zA-Z0-9_-]/.test(c))
            return true;
        return c.charCodeAt(0) >= 0xA0;
    }

    function isCSSIdentifier(value) {
        return /^-?[a-zA-Z_][a-zA-Z0-9_-]*$/.test(value);
    }

    var prefixedOwnClassNamesArray = prefixedElementClassNames(node);
    var needsClassNames = false;
    var needsNthChild = false;
    var ownIndex = -1;
    var elementIndex = -1;
    var siblings = parent.children();
    for (var i = 0; (ownIndex === -1 || !needsNthChild) && i < siblings.length; ++i) {
        var sibling = siblings[i];
        if (sibling.nodeType() !== Node.ELEMENT_NODE)
            continue;
        elementIndex += 1;
        if (sibling === node) {
            ownIndex = elementIndex;
            continue;
        }
        if (needsNthChild)
            continue;
        if (sibling.nodeNameInCorrectCase() !== nodeName)
            continue;
        needsClassNames = true;
        var ownClassNames = prefixedOwnClassNamesArray.keySet();
        var ownClassNameCount = 0;
        for (var name in ownClassNames)
            ++ownClassNameCount;
        if (ownClassNameCount === 0) {
            needsNthChild = true;
            continue;
        }
        var siblingClassNamesArray = prefixedElementClassNames(sibling);
        for (var j = 0; j < siblingClassNamesArray.length; ++j) {
            var siblingClass = siblingClassNamesArray[j];
            if (!ownClassNames.hasOwnProperty(siblingClass))
                continue;
            delete ownClassNames[siblingClass];
            if (!--ownClassNameCount) {
                needsNthChild = true;
                break;
            }
        }
    }
    var result = nodeName;
    if (isTargetNode && nodeName.toLowerCase() === "input" && node.getAttribute("type") && !node.getAttribute("id") && !node.getAttribute("class"))
        result += "[type=\"" + node.getAttribute("type") + "\"]";
    if (needsNthChild) {
        result += ":nth-child(" + (ownIndex + 1) + ")";
    } else if (needsClassNames) {
        for (var prefixedName in prefixedOwnClassNamesArray.keySet())
            result += "." + escapeIdentifierIfNeeded(prefixedName.substr(1));
    }
    return new WebInspector.DOMNodePathStep(result, false);
}
WebInspector.DOMPresentationUtils.xPath = function (node, optimized) {
    if (node.nodeType() === Node.DOCUMENT_NODE)
        return "/";
    var steps = [];
    var contextNode = node;
    while (contextNode) {
        var step = WebInspector.DOMPresentationUtils._xPathValue(contextNode, optimized);
        if (!step)
            break;
        steps.push(step);
        if (step.optimized)
            break;
        contextNode = contextNode.parentNode;
    }
    steps.reverse();
    return (steps.length && steps[0].optimized ? "" : "/") + steps.join("/");
}
WebInspector.DOMPresentationUtils._xPathValue = function (node, optimized) {
    var ownValue;
    var ownIndex = WebInspector.DOMPresentationUtils._xPathIndex(node);
    if (ownIndex === -1)
        return null;
    switch (node.nodeType()) {
        case Node.ELEMENT_NODE:
            if (optimized && node.getAttribute("id"))
                return new WebInspector.DOMNodePathStep("//*[@id=\"" + node.getAttribute("id") + "\"]", true);
            ownValue = node.localName();
            break;
        case Node.ATTRIBUTE_NODE:
            ownValue = "@" + node.nodeName();
            break;
        case Node.TEXT_NODE:
        case Node.CDATA_SECTION_NODE:
            ownValue = "text()";
            break;
        case Node.PROCESSING_INSTRUCTION_NODE:
            ownValue = "processing-instruction()";
            break;
        case Node.COMMENT_NODE:
            ownValue = "comment()";
            break;
        case Node.DOCUMENT_NODE:
            ownValue = "";
            break;
        default:
            ownValue = "";
            break;
    }
    if (ownIndex > 0)
        ownValue += "[" + ownIndex + "]";
    return new WebInspector.DOMNodePathStep(ownValue, node.nodeType() === Node.DOCUMENT_NODE);
}, WebInspector.DOMPresentationUtils._xPathIndex = function (node) {
    function areNodesSimilar(left, right) {
        if (left === right)
            return true;
        if (left.nodeType() === Node.ELEMENT_NODE && right.nodeType() === Node.ELEMENT_NODE)
            return left.localName() === right.localName();
        if (left.nodeType() === right.nodeType())
            return true;
        var leftType = left.nodeType() === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : left.nodeType();
        var rightType = right.nodeType() === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : right.nodeType();
        return leftType === rightType;
    }

    var siblings = node.parentNode ? node.parentNode.children() : null;
    if (!siblings)
        return 0;
    var hasSameNamedElements;
    for (var i = 0; i < siblings.length; ++i) {
        if (areNodesSimilar(node, siblings[i]) && siblings[i] !== node) {
            hasSameNamedElements = true;
            break;
        }
    }
    if (!hasSameNamedElements)
        return 0;
    var ownIndex = 1;
    for (var i = 0; i < siblings.length; ++i) {
        if (areNodesSimilar(node, siblings[i])) {
            if (siblings[i] === node)
                return ownIndex;
            ++ownIndex;
        }
    }
    return -1;
}
WebInspector.DOMNodePathStep = function (value, optimized) {
    this.value = value;
    this.optimized = optimized || false;
}
WebInspector.DOMNodePathStep.prototype = {
    toString: function () {
        return this.value;
    }
}
WebInspector.SidebarSectionTreeElement = function (title, representedObject, hasChildren) {
    TreeElement.call(this, title.escapeHTML(), representedObject || {}, hasChildren);
    this.expand();
}
WebInspector.SidebarSectionTreeElement.prototype = {
    selectable: false, collapse: function () {
    }, get smallChildren() {
        return this._smallChildren;
    }, set smallChildren(x) {
        if (this._smallChildren === x)
            return;
        this._smallChildren = x;
        this._childrenListNode.classList.toggle("small", this._smallChildren);
    }, onattach: function () {
        this.listItemElement.classList.add("sidebar-tree-section");
    }, onreveal: function () {
        if (this.listItemElement)
            this.listItemElement.scrollIntoViewIfNeeded(false);
    }, __proto__: TreeElement.prototype
}
WebInspector.SidebarTreeElement = function (className, title, subtitle, representedObject, hasChildren) {
    TreeElement.call(this, "", representedObject, hasChildren);
    if (hasChildren)
        this.disclosureButton = document.createElementWithClass("button", "disclosure-button");
    this.iconElement = document.createElementWithClass("div", "icon");
    this.statusElement = document.createElementWithClass("div", "status");
    this.titlesElement = document.createElementWithClass("div", "titles");
    this.titleContainer = this.titlesElement.createChild("span", "title-container");
    this.titleElement = this.titleContainer.createChild("span", "title");
    this.subtitleElement = this.titlesElement.createChild("span", "subtitle");
    this.className = className;
    this.mainTitle = title;
    this.subtitle = subtitle;
}
WebInspector.SidebarTreeElement.prototype = {
    get small() {
        return this._small;
    }, set small(x) {
        this._small = x;
        if (this.listItemElement)
            this.listItemElement.classList.toggle("small", this._small);
    }, get mainTitle() {
        return this._mainTitle;
    }, set mainTitle(x) {
        this._mainTitle = x;
        this.refreshTitles();
    }, get subtitle() {
        return this._subtitle;
    }, set subtitle(x) {
        this._subtitle = x;
        this.refreshTitles();
    }, set wait(x) {
        this.listItemElement.classList.toggle("wait", x);
    }, refreshTitles: function () {
        var mainTitle = this.mainTitle;
        if (this.titleElement.textContent !== mainTitle)
            this.titleElement.textContent = mainTitle;
        var subtitle = this.subtitle;
        if (subtitle) {
            if (this.subtitleElement.textContent !== subtitle)
                this.subtitleElement.textContent = subtitle;
            this.titlesElement.classList.remove("no-subtitle");
        } else {
            this.subtitleElement.textContent = "";
            this.titlesElement.classList.add("no-subtitle");
        }
    }, isEventWithinDisclosureTriangle: function (event) {
        return event.target === this.disclosureButton;
    }, onattach: function () {
        this.listItemElement.classList.add("sidebar-tree-item");
        if (this.className)
            this.listItemElement.classList.add(this.className);
        if (this.small)
            this.listItemElement.classList.add("small");
        if (this.hasChildren && this.disclosureButton)
            this.listItemElement.appendChild(this.disclosureButton);
        this.listItemElement.appendChildren(this.iconElement, this.statusElement, this.titlesElement);
    }, onreveal: function () {
        if (this.listItemElement)
            this.listItemElement.scrollIntoViewIfNeeded(false);
    }, __proto__: TreeElement.prototype
}
WebInspector.Section = function (title, subtitle) {
    this.element = document.createElement("div");
    this.element.className = "section";
    this.element._section = this;
    this.headerElement = document.createElement("div");
    this.headerElement.className = "header";
    this.titleElement = document.createElement("div");
    this.titleElement.className = "title";
    this.subtitleElement = document.createElement("div");
    this.subtitleElement.className = "subtitle";
    this.headerElement.appendChild(this.subtitleElement);
    this.headerElement.appendChild(this.titleElement);
    this.headerElement.addEventListener("click", this.handleClick.bind(this), false);
    this.element.appendChild(this.headerElement);
    this.title = title;
    this.subtitle = subtitle;
    this._expanded = false;
}
WebInspector.Section.prototype = {
    get title() {
        return this._title;
    }, set title(x) {
        if (this._title === x)
            return;
        this._title = x;
        if (x instanceof Node) {
            this.titleElement.removeChildren();
            this.titleElement.appendChild(x);
        } else
            this.titleElement.textContent = x;
    }, get subtitle() {
        return this._subtitle;
    }, set subtitle(x) {
        if (this._subtitle === x)
            return;
        this._subtitle = x;
        this.subtitleElement.textContent = x;
    }, get subtitleAsTextForTest() {
        var result = this.subtitleElement.textContent;
        var child = this.subtitleElement.querySelector("[data-uncopyable]");
        if (child) {
            var linkData = child.getAttribute("data-uncopyable");
            if (linkData)
                result += linkData;
        }
        return result;
    }, get expanded() {
        return this._expanded;
    }, set expanded(x) {
        if (x)
            this.expand(); else
            this.collapse();
    }, get populated() {
        return this._populated;
    }, set populated(x) {
        this._populated = x;
        if (!x && this._expanded) {
            this.onpopulate();
            this._populated = true;
        }
    }, onpopulate: function () {
    }, get firstSibling() {
        var parent = this.element.parentElement;
        if (!parent)
            return null;
        var childElement = parent.firstChild;
        while (childElement) {
            if (childElement._section)
                return childElement._section;
            childElement = childElement.nextSibling;
        }
        return null;
    }, get lastSibling() {
        var parent = this.element.parentElement;
        if (!parent)
            return null;
        var childElement = parent.lastChild;
        while (childElement) {
            if (childElement._section)
                return childElement._section;
            childElement = childElement.previousSibling;
        }
        return null;
    }, get nextSibling() {
        var curElement = this.element;
        do {
            curElement = curElement.nextSibling;
        } while (curElement && !curElement._section);
        return curElement ? curElement._section : null;
    }, get previousSibling() {
        var curElement = this.element;
        do {
            curElement = curElement.previousSibling;
        } while (curElement && !curElement._section);
        return curElement ? curElement._section : null;
    }, expand: function () {
        if (this._expanded)
            return;
        this._expanded = true;
        this.element.classList.add("expanded");
        if (!this._populated) {
            this.onpopulate();
            this._populated = true;
        }
    }, collapse: function () {
        if (!this._expanded)
            return;
        this._expanded = false;
        this.element.classList.remove("expanded");
    }, toggleExpanded: function () {
        this.expanded = !this.expanded;
    }, handleClick: function (event) {
        this.toggleExpanded();
        event.consume();
    }
}
WebInspector.PropertiesSection = function (title, subtitle) {
    WebInspector.Section.call(this, title, subtitle);
    this.headerElement.classList.add("monospace");
    this.propertiesElement = document.createElement("ol");
    this.propertiesElement.className = "properties properties-tree monospace";
    this.propertiesTreeOutline = new TreeOutline(this.propertiesElement, true);
    this.propertiesTreeOutline.setFocusable(false);
    this.propertiesTreeOutline.section = this;
    this.element.appendChild(this.propertiesElement);
}
WebInspector.PropertiesSection.prototype = {__proto__: WebInspector.Section.prototype}
WebInspector.RemoteObject = function () {
}
WebInspector.RemoteObject.prototype = {
    get type() {
        throw"Not implemented";
    }, get subtype() {
        throw"Not implemented";
    }, get description() {
        throw"Not implemented";
    }, get hasChildren() {
        throw"Not implemented";
    }, arrayLength: function () {
        throw"Not implemented";
    }, getOwnProperties: function (callback) {
        throw"Not implemented";
    }, getAllProperties: function (accessorPropertiesOnly, callback) {
        throw"Not implemented";
    }, deleteProperty: function (name, callback) {
        throw"Not implemented";
    }, callFunction: function (functionDeclaration, args, callback) {
        throw"Not implemented";
    }, callFunctionJSON: function (functionDeclaration, args, callback) {
        throw"Not implemented";
    }, target: function () {
        throw new Error("Target-less object");
    }, isNode: function () {
        return false;
    }, functionDetails: function (callback) {
        callback(null);
    }
}
WebInspector.RemoteObject.fromLocalObject = function (value) {
    return new WebInspector.LocalJSONObject(value);
}
WebInspector.RemoteObject.type = function (remoteObject) {
    if (remoteObject === null)
        return "null";
    var type = typeof remoteObject;
    if (type !== "object" && type !== "function")
        return type;
    return remoteObject.type;
}
WebInspector.RemoteObject.toCallArgument = function (object) {
    var type = typeof object;
    var value = object;
    var objectId = undefined;
    var description = String(object);
    if (type === "number" && value === 0 && 1 / value < 0)
        description = "-0";
    switch (type) {
        case"number":
        case"string":
        case"boolean":
        case"undefined":
            break;
        default:
            if (object) {
                type = object.type;
                value = object.value;
                objectId = object.objectId;
                description = object.description;
            }
            break;
    }
    if (type === "number") {
        switch (description) {
            case"NaN":
            case"Infinity":
            case"-Infinity":
            case"-0":
                value = description;
                break;
        }
    }
    return {value: value, objectId: objectId, type: (type)};
}
WebInspector.RemoteObjectImpl = function (target, objectId, type, subtype, value, description, preview) {
    WebInspector.RemoteObject.call(this);
    this._target = target;
    this._runtimeAgent = target.runtimeAgent();
    this._domModel = target.domModel;
    this._type = type;
    this._subtype = subtype;
    if (objectId) {
        this._objectId = objectId;
        this._description = description;
        this._hasChildren = (type !== "symbol");
        this._preview = preview;
    } else {
        console.assert(type !== "object" || value === null);
        this._description = description || (value + "");
        this._hasChildren = false;
        if (type === "number" && typeof value !== "number")
            this.value = Number(value); else
            this.value = value;
    }
}
WebInspector.RemoteObjectImpl.prototype = {
    get objectId() {
        return this._objectId;
    }, get type() {
        return this._type;
    }, get subtype() {
        return this._subtype;
    }, get description() {
        return this._description;
    }, get hasChildren() {
        return this._hasChildren;
    }, get preview() {
        return this._preview;
    }, getOwnProperties: function (callback) {
        this.doGetProperties(true, false, callback);
    }, getAllProperties: function (accessorPropertiesOnly, callback) {
        this.doGetProperties(false, accessorPropertiesOnly, callback);
    }, getProperty: function (propertyPath, callback) {
        function remoteFunction(arrayStr) {
            var result = this;
            var properties = JSON.parse(arrayStr);
            for (var i = 0, n = properties.length; i < n; ++i)
                result = result[properties[i]];
            return result;
        }

        var args = [{value: JSON.stringify(propertyPath)}];
        this.callFunction(remoteFunction, args, callback);
    }, doGetProperties: function (ownProperties, accessorPropertiesOnly, callback) {
        if (!this._objectId) {
            callback(null, null);
            return;
        }
        function remoteObjectBinder(error, properties, internalProperties) {
            if (error) {
                callback(null, null);
                return;
            }
            var result = [];
            for (var i = 0; properties && i < properties.length; ++i) {
                var property = properties[i];
                var propertyValue = property.value ? this._target.runtimeModel.createRemoteObject(property.value) : null;
                var propertySymbol = property.symbol ? this._target.runtimeModel.createRemoteObject(property.symbol) : null;
                var remoteProperty = new WebInspector.RemoteObjectProperty(property.name, propertyValue, !!property.enumerable, !!property.writable, !!property.isOwn, !!property.wasThrown, propertySymbol);
                if (typeof property.value === "undefined") {
                    if (property.get && property.get.type !== "undefined")
                        remoteProperty.getter = this._target.runtimeModel.createRemoteObject(property.get);
                    if (property.set && property.set.type !== "undefined")
                        remoteProperty.setter = this._target.runtimeModel.createRemoteObject(property.set);
                }
                result.push(remoteProperty);
            }
            var internalPropertiesResult = null;
            if (internalProperties) {
                internalPropertiesResult = [];
                for (var i = 0; i < internalProperties.length; i++) {
                    var property = internalProperties[i];
                    if (!property.value)
                        continue;
                    var propertyValue = this._target.runtimeModel.createRemoteObject(property.value);
                    internalPropertiesResult.push(new WebInspector.RemoteObjectProperty(property.name, propertyValue, true, false));
                }
            }
            callback(result, internalPropertiesResult);
        }

        this._runtimeAgent.getProperties(this._objectId, ownProperties, accessorPropertiesOnly, remoteObjectBinder.bind(this));
    }, setPropertyValue: function (name, value, callback) {
        if (!this._objectId) {
            callback("Can't set a property of non-object.");
            return;
        }
        this._runtimeAgent.invoke_evaluate({expression: value, doNotPauseOnExceptionsAndMuteConsole: true}, evaluatedCallback.bind(this));
        function evaluatedCallback(error, result, wasThrown) {
            if (error || wasThrown) {
                callback(error || result.description);
                return;
            }
            this.doSetObjectPropertyValue(result, name, callback);
            if (result.objectId)
                this._runtimeAgent.releaseObject(result.objectId);
        }
    }, doSetObjectPropertyValue: function (result, name, callback) {
        var setPropertyValueFunction = "function(a, b) { this[a] = b; }";
        var argv = [name, WebInspector.RemoteObject.toCallArgument(result)];
        this._runtimeAgent.callFunctionOn(this._objectId, setPropertyValueFunction, argv, true, undefined, undefined, propertySetCallback);
        function propertySetCallback(error, result, wasThrown) {
            if (error || wasThrown) {
                callback(error || result.description);
                return;
            }
            callback();
        }
    }, deleteProperty: function (name, callback) {
        if (!this._objectId) {
            callback("Can't delete a property of non-object.");
            return;
        }
        var deletePropertyFunction = "function(a) { delete this[a]; return !(a in this); }";
        this._runtimeAgent.callFunctionOn(this._objectId, deletePropertyFunction, [name], true, undefined, undefined, deletePropertyCallback);
        function deletePropertyCallback(error, result, wasThrown) {
            if (error || wasThrown) {
                callback(error || result.description);
                return;
            }
            if (!result.value)
                callback("Failed to delete property."); else
                callback();
        }
    }, pushNodeToFrontend: function (callback) {
        if (this.isNode())
            this._domModel.pushNodeToFrontend(this._objectId, callback); else
            callback(null);
    }, highlightAsDOMNode: function () {
        this._domModel.highlightDOMNode(undefined, undefined, this._objectId);
    }, hideDOMNodeHighlight: function () {
        this._domModel.hideDOMNodeHighlight();
    }, callFunction: function (functionDeclaration, args, callback) {
        function mycallback(error, result, wasThrown) {
            if (!callback)
                return;
            if (error)
                callback(null, false); else
                callback(this.target().runtimeModel.createRemoteObject(result), wasThrown);
        }

        this._runtimeAgent.callFunctionOn(this._objectId, functionDeclaration.toString(), args, true, undefined, undefined, mycallback.bind(this));
    }, callFunctionJSON: function (functionDeclaration, args, callback) {
        function mycallback(error, result, wasThrown) {
            callback((error || wasThrown) ? null : result.value);
        }

        this._runtimeAgent.callFunctionOn(this._objectId, functionDeclaration.toString(), args, true, true, false, mycallback);
    }, release: function () {
        if (!this._objectId)
            return;
        this._runtimeAgent.releaseObject(this._objectId);
    }, arrayLength: function () {
        if (this.subtype !== "array")
            return 0;
        var matches = this._description.match(/\[([0-9]+)\]/);
        if (!matches)
            return 0;
        return parseInt(matches[1], 10);
    }, target: function () {
        return this._target;
    }, isNode: function () {
        return !!this._objectId && this.type === "object" && this.subtype === "node";
    }, functionDetails: function (callback) {
        this._target.debuggerModel.functionDetails(this, callback)
    }, __proto__: WebInspector.RemoteObject.prototype
};
WebInspector.RemoteObject.loadFromObject = function (object, flattenProtoChain, callback) {
    if (flattenProtoChain)
        object.getAllProperties(false, callback); else
        WebInspector.RemoteObject.loadFromObjectPerProto(object, callback);
};
WebInspector.RemoteObject.loadFromObjectPerProto = function (object, callback) {
    var savedOwnProperties;
    var savedAccessorProperties;
    var savedInternalProperties;
    var resultCounter = 2;

    function processCallback() {
        if (--resultCounter)
            return;
        if (savedOwnProperties && savedAccessorProperties) {
            var combinedList = savedAccessorProperties.slice(0);
            for (var i = 0; i < savedOwnProperties.length; i++) {
                var property = savedOwnProperties[i];
                if (!property.isAccessorProperty())
                    combinedList.push(property);
            }
            return callback(combinedList, savedInternalProperties ? savedInternalProperties : null);
        } else {
            callback(null, null);
        }
    }

    function allAccessorPropertiesCallback(properties, internalProperties) {
        savedAccessorProperties = properties;
        processCallback();
    }

    function ownPropertiesCallback(properties, internalProperties) {
        savedOwnProperties = properties;
        savedInternalProperties = internalProperties;
        processCallback();
    }

    object.getAllProperties(true, allAccessorPropertiesCallback);
    object.getOwnProperties(ownPropertiesCallback);
};
WebInspector.ScopeRemoteObject = function (target, objectId, scopeRef, type, subtype, value, description, preview) {
    WebInspector.RemoteObjectImpl.call(this, target, objectId, type, subtype, value, description, preview);
    this._scopeRef = scopeRef;
    this._savedScopeProperties = undefined;
    this._debuggerAgent = target.debuggerAgent();
};
WebInspector.ScopeRemoteObject.prototype = {
    doGetProperties: function (ownProperties, accessorPropertiesOnly, callback) {
        if (accessorPropertiesOnly) {
            callback([], []);
            return;
        }
        if (this._savedScopeProperties) {
            callback(this._savedScopeProperties.slice(), []);
            return;
        }
        function wrappedCallback(properties, internalProperties) {
            if (this._scopeRef && properties instanceof Array)
                this._savedScopeProperties = properties.slice();
            callback(properties, internalProperties);
        }

        WebInspector.RemoteObjectImpl.prototype.doGetProperties.call(this, ownProperties, accessorPropertiesOnly, wrappedCallback.bind(this));
    }, doSetObjectPropertyValue: function (result, name, callback) {
        this._debuggerAgent.setVariableValue(this._scopeRef.number, name, WebInspector.RemoteObject.toCallArgument(result), this._scopeRef.callFrameId, this._scopeRef.functionId, setVariableValueCallback.bind(this));
        function setVariableValueCallback(error) {
            if (error) {
                callback(error);
                return;
            }
            if (this._savedScopeProperties) {
                for (var i = 0; i < this._savedScopeProperties.length; i++) {
                    if (this._savedScopeProperties[i].name === name)
                        this._savedScopeProperties[i].value = this._target.runtimeModel.createRemoteObject(result);
                }
            }
            callback();
        }
    }, __proto__: WebInspector.RemoteObjectImpl.prototype
};
WebInspector.ScopeRef = function (number, callFrameId, functionId) {
    this.number = number;
    this.callFrameId = callFrameId;
    this.functionId = functionId;
}
WebInspector.RemoteObjectProperty = function (name, value, enumerable, writable, isOwn, wasThrown, symbol) {
    this.name = name;
    if (value !== null)
        this.value = value;
    this.enumerable = typeof enumerable !== "undefined" ? enumerable : true;
    this.writable = typeof writable !== "undefined" ? writable : true;
    this.isOwn = !!isOwn;
    this.wasThrown = !!wasThrown;
    if (symbol)
        this.symbol = symbol;
}
WebInspector.RemoteObjectProperty.prototype = {
    isAccessorProperty: function () {
        return !!(this.getter || this.setter);
    }
};
WebInspector.LocalJSONObject = function (value) {
    WebInspector.RemoteObject.call(this);
    this._value = value;
}
WebInspector.LocalJSONObject.prototype = {
    get description() {
        if (this._cachedDescription)
            return this._cachedDescription;
        function formatArrayItem(property) {
            return property.value.description;
        }

        function formatObjectItem(property) {
            return property.name + ":" + property.value.description;
        }

        if (this.type === "object") {
            switch (this.subtype) {
                case"array":
                    this._cachedDescription = this._concatenate("[", "]", formatArrayItem);
                    break;
                case"date":
                    this._cachedDescription = "" + this._value;
                    break;
                case"null":
                    this._cachedDescription = "null";
                    break;
                default:
                    this._cachedDescription = this._concatenate("{", "}", formatObjectItem);
            }
        } else
            this._cachedDescription = String(this._value);
        return this._cachedDescription;
    }, _concatenate: function (prefix, suffix, formatProperty) {
        const previewChars = 100;
        var buffer = prefix;
        var children = this._children();
        for (var i = 0; i < children.length; ++i) {
            var itemDescription = formatProperty(children[i]);
            if (buffer.length + itemDescription.length > previewChars) {
                buffer += ",\u2026";
                break;
            }
            if (i)
                buffer += ", ";
            buffer += itemDescription;
        }
        buffer += suffix;
        return buffer;
    }, get type() {
        return typeof this._value;
    }, get subtype() {
        if (this._value === null)
            return "null";
        if (this._value instanceof Array)
            return "array";
        if (this._value instanceof Date)
            return "date";
        return undefined;
    }, get hasChildren() {
        if ((typeof this._value !== "object") || (this._value === null))
            return false;
        return !!Object.keys((this._value)).length;
    }, getOwnProperties: function (callback) {
        callback(this._children());
    }, getAllProperties: function (accessorPropertiesOnly, callback) {
        if (accessorPropertiesOnly)
            callback([], null); else
            callback(this._children(), null);
    }, _children: function () {
        if (!this.hasChildren)
            return [];
        var value = (this._value);

        function buildProperty(propName) {
            return new WebInspector.RemoteObjectProperty(propName, new WebInspector.LocalJSONObject(this._value[propName]));
        }

        if (!this._cachedChildren)
            this._cachedChildren = Object.keys(value).map(buildProperty.bind(this));
        return this._cachedChildren;
    }, isError: function () {
        return false;
    }, arrayLength: function () {
        return this._value instanceof Array ? this._value.length : 0;
    }, callFunction: function (functionDeclaration, args, callback) {
        var target = (this._value);
        var rawArgs = args ? args.map(function (arg) {
            return arg.value;
        }) : [];
        var result;
        var wasThrown = false;
        try {
            result = functionDeclaration.apply(target, rawArgs);
        } catch (e) {
            wasThrown = true;
        }
        if (!callback)
            return;
        callback(WebInspector.RemoteObject.fromLocalObject(result), wasThrown);
    }, callFunctionJSON: function (functionDeclaration, args, callback) {
        var target = (this._value);
        var rawArgs = args ? args.map(function (arg) {
            return arg.value;
        }) : [];
        var result;
        try {
            result = functionDeclaration.apply(target, rawArgs);
        } catch (e) {
            result = null;
        }
        callback(result);
    }, __proto__: WebInspector.RemoteObject.prototype
}
WebInspector.ObjectPropertiesSection = function (object, title, subtitle, emptyPlaceholder, ignoreHasOwnProperty, extraProperties, treeElementConstructor) {
    this.emptyPlaceholder = (emptyPlaceholder || WebInspector.UIString("No Properties"));
    this.object = object;
    this.ignoreHasOwnProperty = ignoreHasOwnProperty;
    this.extraProperties = extraProperties;
    this.treeElementConstructor = treeElementConstructor || WebInspector.ObjectPropertyTreeElement;
    this.editable = true;
    this.skipProto = false;
    WebInspector.PropertiesSection.call(this, title || "", subtitle);
}
WebInspector.ObjectPropertiesSection._arrayLoadThreshold = 100;
WebInspector.ObjectPropertiesSection.prototype = {
    enableContextMenu: function () {
        this.element.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), false);
    }, _contextMenuEventFired: function (event) {
        var contextMenu = new WebInspector.ContextMenu(event);
        contextMenu.appendApplicableItems(this.object);
        contextMenu.show();
    }, onpopulate: function () {
        this.update();
    }, update: function () {
        if (this.object.arrayLength() > WebInspector.ObjectPropertiesSection._arrayLoadThreshold) {
            this.propertiesTreeOutline.removeChildren();
            WebInspector.ArrayGroupingTreeElement._populateArray(this.propertiesTreeOutline, this.object, 0, this.object.arrayLength() - 1);
            return;
        }
        function callback(properties, internalProperties) {
            if (!properties)
                return;
            this.updateProperties(properties, internalProperties);
        }

        WebInspector.RemoteObject.loadFromObject(this.object, !!this.ignoreHasOwnProperty, callback.bind(this));
    }, updateProperties: function (properties, internalProperties, rootTreeElementConstructor, rootPropertyComparer) {
        if (!rootTreeElementConstructor)
            rootTreeElementConstructor = this.treeElementConstructor;
        if (!rootPropertyComparer)
            rootPropertyComparer = WebInspector.ObjectPropertiesSection.CompareProperties;
        if (this.extraProperties) {
            for (var i = 0; i < this.extraProperties.length; ++i)
                properties.push(this.extraProperties[i]);
        }
        this.propertiesTreeOutline.removeChildren();
        WebInspector.ObjectPropertyTreeElement.populateWithProperties(this.propertiesTreeOutline, properties, internalProperties, rootTreeElementConstructor, rootPropertyComparer, this.skipProto, this.object);
        this.propertiesForTest = properties;
        if (!this.propertiesTreeOutline.children.length) {
            var title = document.createElementWithClass("div", "info");
            title.textContent = this.emptyPlaceholder;
            var infoElement = new TreeElement(title, null, false);
            this.propertiesTreeOutline.appendChild(infoElement);
        }
    }, __proto__: WebInspector.PropertiesSection.prototype
}
WebInspector.ObjectPropertiesSection.CompareProperties = function (propertyA, propertyB) {
    var a = propertyA.name;
    var b = propertyB.name;
    if (a === "__proto__")
        return 1;
    if (b === "__proto__")
        return -1;
    if (propertyA.symbol && !propertyB.symbol)
        return 1;
    if (propertyB.symbol && !propertyA.symbol)
        return -1;
    return String.naturalOrderComparator(a, b);
}
WebInspector.ObjectPropertyTreeElement = function (property) {
    this.property = property;
    TreeElement.call(this, "", null, false);
    this.toggleOnClick = true;
    this.selectable = false;
}
WebInspector.ObjectPropertyTreeElement.prototype = {
    onpopulate: function () {
        var propertyValue = (this.property.value);
        console.assert(propertyValue);
        WebInspector.ObjectPropertyTreeElement.populate(this, propertyValue);
    }, ondblclick: function (event) {
        if (this.property.writable || this.property.setter)
            this.startEditing(event);
        return false;
    }, onattach: function () {
        this.update();
    }, update: function () {
        this.nameElement = document.createElementWithClass("span", "name");
        var name = this.property.name;
        if (/^\s|\s$|^$|\n/.test(name))
            this.nameElement.createTextChildren("\"", name.replace(/\n/g, "\u21B5"), "\""); else
            this.nameElement.textContent = name;
        if (!this.property.enumerable)
            this.nameElement.classList.add("dimmed");
        if (this.property.isAccessorProperty())
            this.nameElement.classList.add("properties-accessor-property-name");
        if (this.property.symbol)
            this.nameElement.addEventListener("contextmenu", this._contextMenuFired.bind(this, this.property.symbol), false);
        var separatorElement = document.createElementWithClass("span", "separator");
        separatorElement.textContent = ": ";
        if (this.property.value) {
            this.valueElement = document.createElementWithClass("span", "value");
            var type = this.property.value.type;
            var subtype = this.property.value.subtype;
            var description = this.property.value.description;
            var prefix;
            var valueText;
            var suffix;
            if (this.property.wasThrown) {
                prefix = "[Exception: ";
                valueText = description;
                suffix = "]";
            } else if (type === "string" && typeof description === "string") {
                prefix = "\"";
                valueText = description.replace(/\n/g, "\u21B5");
                suffix = "\"";
                this.valueElement._originalTextContent = "\"" + description + "\"";
            } else if (type === "function" && typeof description === "string") {
                valueText = /.*/.exec(description)[0].replace(/\s+$/g, "");
                this.valueElement._originalTextContent = description;
            } else if (type !== "object" || subtype !== "node") {
                valueText = description;
            }
            this.valueElement.setTextContentTruncatedIfNeeded(valueText || "");
            if (prefix)
                this.valueElement.insertBefore(document.createTextNode(prefix), this.valueElement.firstChild);
            if (suffix)
                this.valueElement.createTextChild(suffix);
            if (this.property.wasThrown)
                this.valueElement.classList.add("error");
            if (subtype || type)
                this.valueElement.classList.add("console-formatted-" + (subtype || type));
            this.valueElement.addEventListener("contextmenu", this._contextMenuFired.bind(this, this.property.value), false);
            if (type === "object" && subtype === "node" && description) {
                WebInspector.DOMPresentationUtils.createSpansForNodeTitle(this.valueElement, description);
                this.valueElement.addEventListener("mousemove", this._mouseMove.bind(this, this.property.value), false);
                this.valueElement.addEventListener("mouseout", this._mouseOut.bind(this, this.property.value), false);
            } else {
                this.valueElement.title = description || "";
            }
            this.listItemElement.removeChildren();
            this.hasChildren = this.property.value.hasChildren && !this.property.wasThrown;
        } else {
            if (this.property.getter) {
                this.valueElement = WebInspector.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(this.property.parentObject, [this.property.name], this._onInvokeGetterClick.bind(this));
            } else {
                this.valueElement = document.createElementWithClass("span", "console-formatted-undefined");
                this.valueElement.textContent = WebInspector.UIString("<unreadable>");
                this.valueElement.title = WebInspector.UIString("No property getter");
            }
        }
        this.listItemElement.appendChildren(this.nameElement, separatorElement, this.valueElement);
    }, _contextMenuFired: function (value, event) {
        var contextMenu = new WebInspector.ContextMenu(event);
        this.populateContextMenu(contextMenu);
        contextMenu.appendApplicableItems(value);
        contextMenu.show();
    }, populateContextMenu: function (contextMenu) {
    }, _mouseMove: function (event) {
        this.property.value.highlightAsDOMNode();
    }, _mouseOut: function (event) {
        this.property.value.hideDOMNodeHighlight();
    }, updateSiblings: function () {
        if (this.parent.root)
            this.treeOutline.section.update(); else
            this.parent.shouldRefreshChildren = true;
    }, renderPromptAsBlock: function () {
        return false;
    }, elementAndValueToEdit: function () {
        return {element: this.valueElement, value: (typeof this.valueElement._originalTextContent === "string") ? this.valueElement._originalTextContent : undefined};
    }, startEditing: function (event) {
        var elementAndValueToEdit = this.elementAndValueToEdit();
        var elementToEdit = elementAndValueToEdit.element;
        var valueToEdit = elementAndValueToEdit.value;
        if (WebInspector.isBeingEdited(elementToEdit) || !this.treeOutline.section.editable || this._readOnly)
            return;
        if (typeof valueToEdit !== "undefined")
            elementToEdit.setTextContentTruncatedIfNeeded(valueToEdit, WebInspector.UIString("<string is too large to edit>"));
        var context = {expanded: this.expanded, elementToEdit: elementToEdit, previousContent: elementToEdit.textContent};
        this.hasChildren = false;
        this.listItemElement.classList.add("editing-sub-part");
        this._prompt = new WebInspector.ObjectPropertyPrompt(this.renderPromptAsBlock());
        function blurListener() {
            this.editingCommitted(null, elementToEdit.textContent, context.previousContent, context);
        }

        var proxyElement = this._prompt.attachAndStartEditing(elementToEdit, blurListener.bind(this));
        window.getSelection().setBaseAndExtent(elementToEdit, 0, elementToEdit, 1);
        proxyElement.addEventListener("keydown", this._promptKeyDown.bind(this, context), false);
    }, isEditing: function () {
        return !!this._prompt;
    }, editingEnded: function (context) {
        this._prompt.detach();
        delete this._prompt;
        this.listItemElement.scrollLeft = 0;
        this.listItemElement.classList.remove("editing-sub-part");
        if (context.expanded)
            this.expand();
    }, editingCancelled: function (element, context) {
        this.editingEnded(context);
        this.update();
    }, editingCommitted: function (element, userInput, previousContent, context) {
        if (userInput === previousContent) {
            this.editingCancelled(element, context);
            return;
        }
        this.editingEnded(context);
        this.applyExpression(userInput);
    }, _promptKeyDown: function (context, event) {
        if (isEnterKey(event)) {
            event.consume(true);
            this.editingCommitted(null, context.elementToEdit.textContent, context.previousContent, context);
            return;
        }
        if (event.keyIdentifier === "U+001B") {
            event.consume();
            this.editingCancelled(null, context);
            return;
        }
    }, applyExpression: function (expression) {
        var property = WebInspector.RemoteObject.toCallArgument(this.property.symbol || this.property.name);
        expression = expression.trim();
        if (expression)
            this.property.parentObject.setPropertyValue(property, expression, callback.bind(this)); else
            this.property.parentObject.deleteProperty(property, callback.bind(this));
        function callback(error) {
            if (error) {
                this.update();
                return;
            }
            if (!expression) {
                this.parent.removeChild(this);
            } else {
                this.updateSiblings();
            }
        };
    }, propertyPath: function () {
        if ("_cachedPropertyPath"in this)
            return this._cachedPropertyPath;
        var current = this;
        var result;
        do {
            if (current.property) {
                if (result)
                    result = current.property.name + "." + result; else
                    result = current.property.name;
            }
            current = current.parent;
        } while (current && !current.root);
        this._cachedPropertyPath = result;
        return result;
    }, _onInvokeGetterClick: function (result, wasThrown) {
        if (!result)
            return;
        this.property.value = result;
        this.property.wasThrown = wasThrown;
        this.update();
        this.shouldRefreshChildren = true;
    }, __proto__: TreeElement.prototype
}
WebInspector.ObjectPropertyTreeElement.populate = function (treeElement, value) {
    if (treeElement.children.length && !treeElement.shouldRefreshChildren)
        return;
    if (value.arrayLength() > WebInspector.ObjectPropertiesSection._arrayLoadThreshold) {
        treeElement.removeChildren();
        WebInspector.ArrayGroupingTreeElement._populateArray(treeElement, value, 0, value.arrayLength() - 1);
        return;
    }
    function callback(properties, internalProperties) {
        treeElement.removeChildren();
        if (!properties)
            return;
        if (!internalProperties)
            internalProperties = [];
        WebInspector.ObjectPropertyTreeElement.populateWithProperties(treeElement, properties, internalProperties, treeElement.treeOutline.section.treeElementConstructor, WebInspector.ObjectPropertiesSection.CompareProperties, treeElement.treeOutline.section.skipProto, value);
    }

    WebInspector.RemoteObject.loadFromObjectPerProto(value, callback);
}
WebInspector.ObjectPropertyTreeElement.populateWithProperties = function (treeElement, properties, internalProperties, treeElementConstructor, comparator, skipProto, value) {
    properties.sort(comparator);
    for (var i = 0; i < properties.length; ++i) {
        var property = properties[i];
        if (skipProto && property.name === "__proto__")
            continue;
        if (property.isAccessorProperty()) {
            if (property.name !== "__proto__" && property.getter) {
                property.parentObject = value;
                treeElement.appendChild(new treeElementConstructor(property));
            }
            if (property.isOwn) {
                if (property.getter) {
                    var getterProperty = new WebInspector.RemoteObjectProperty("get " + property.name, property.getter);
                    getterProperty.parentObject = value;
                    treeElement.appendChild(new treeElementConstructor(getterProperty));
                }
                if (property.setter) {
                    var setterProperty = new WebInspector.RemoteObjectProperty("set " + property.name, property.setter);
                    setterProperty.parentObject = value;
                    treeElement.appendChild(new treeElementConstructor(setterProperty));
                }
            }
        } else {
            property.parentObject = value;
            treeElement.appendChild(new treeElementConstructor(property));
        }
    }
    if (value && value.type === "function") {
        var hasTargetFunction = false;
        if (internalProperties) {
            for (var i = 0; i < internalProperties.length; i++) {
                if (internalProperties[i].name == "[[TargetFunction]]") {
                    hasTargetFunction = true;
                    break;
                }
            }
        }
        if (!hasTargetFunction)
            treeElement.appendChild(new WebInspector.FunctionScopeMainTreeElement(value));
    }
    if (internalProperties) {
        for (var i = 0; i < internalProperties.length; i++) {
            internalProperties[i].parentObject = value;
            treeElement.appendChild(new treeElementConstructor(internalProperties[i]));
        }
    }
}
WebInspector.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan = function (object, propertyPath, callback) {
    var rootElement = document.createElement("span");
    var element = rootElement.createChild("span", "properties-calculate-value-button");
    element.textContent = WebInspector.UIString("(...)");
    element.title = WebInspector.UIString("Invoke property getter");
    element.addEventListener("click", onInvokeGetterClick, false);
    function onInvokeGetterClick(event) {
        event.consume();
        object.getProperty(propertyPath, callback);
    }

    return rootElement;
}
WebInspector.FunctionScopeMainTreeElement = function (remoteObject) {
    TreeElement.call(this, "<function scope>", null, false);
    this.toggleOnClick = true;
    this.selectable = false;
    this._remoteObject = remoteObject;
    this.hasChildren = true;
}
WebInspector.FunctionScopeMainTreeElement.prototype = {
    onpopulate: function () {
        if (this.children.length && !this.shouldRefreshChildren)
            return;
        function didGetDetails(response) {
            if (!response)
                return;
            this.removeChildren();
            var scopeChain = response.scopeChain;
            if (!scopeChain)
                return;
            for (var i = 0; i < scopeChain.length; ++i) {
                var scope = scopeChain[i];
                var title = null;
                var isTrueObject;
                switch (scope.type) {
                    case DebuggerAgent.ScopeType.Local:
                        title = WebInspector.UIString("Local");
                        isTrueObject = false;
                        break;
                    case DebuggerAgent.ScopeType.Closure:
                        title = WebInspector.UIString("Closure");
                        isTrueObject = false;
                        break;
                    case DebuggerAgent.ScopeType.Catch:
                        title = WebInspector.UIString("Catch");
                        isTrueObject = false;
                        break;
                    case DebuggerAgent.ScopeType.With:
                        title = WebInspector.UIString("With Block");
                        isTrueObject = true;
                        break;
                    case DebuggerAgent.ScopeType.Global:
                        title = WebInspector.UIString("Global");
                        isTrueObject = true;
                        break;
                    default:
                        console.error("Unknown scope type: " + scope.type);
                        continue;
                }
                var runtimeModel = this._remoteObject.target().runtimeModel;
                if (isTrueObject) {
                    var remoteObject = runtimeModel.createRemoteObject(scope.object);
                    var property = new WebInspector.RemoteObjectProperty(title, remoteObject);
                    property.writable = false;
                    property.parentObject = null;
                    this.appendChild(new this.treeOutline.section.treeElementConstructor(property));
                } else {
                    var scopeRef = new WebInspector.ScopeRef(i, undefined, this._remoteObject.objectId);
                    var remoteObject = runtimeModel.createScopeRemoteObject(scope.object, scopeRef);
                    var scopeTreeElement = new WebInspector.ScopeTreeElement(title, null, remoteObject);
                    this.appendChild(scopeTreeElement);
                }
            }
        }

        this._remoteObject.functionDetails(didGetDetails.bind(this));
    }, __proto__: TreeElement.prototype
}
WebInspector.ScopeTreeElement = function (title, subtitle, remoteObject) {
    TreeElement.call(this, title, null, false);
    this.toggleOnClick = true;
    this.selectable = false;
    this._remoteObject = remoteObject;
    this.hasChildren = true;
}
WebInspector.ScopeTreeElement.prototype = {
    onpopulate: function () {
        WebInspector.ObjectPropertyTreeElement.populate(this, this._remoteObject);
    }, __proto__: TreeElement.prototype
}
WebInspector.ArrayGroupingTreeElement = function (object, fromIndex, toIndex, propertyCount) {
    TreeElement.call(this, String.sprintf("[%d \u2026 %d]", fromIndex, toIndex), undefined, true);
    this._fromIndex = fromIndex;
    this._toIndex = toIndex;
    this._object = object;
    this._readOnly = true;
    this._propertyCount = propertyCount;
    this._populated = false;
}
WebInspector.ArrayGroupingTreeElement._bucketThreshold = 100;
WebInspector.ArrayGroupingTreeElement._sparseIterationThreshold = 250000;
WebInspector.ArrayGroupingTreeElement._populateArray = function (treeElement, object, fromIndex, toIndex) {
    WebInspector.ArrayGroupingTreeElement._populateRanges(treeElement, object, fromIndex, toIndex, true);
}
WebInspector.ArrayGroupingTreeElement._populateRanges = function (treeElement, object, fromIndex, toIndex, topLevel) {
    object.callFunctionJSON(packRanges, [{value: fromIndex}, {value: toIndex}, {value: WebInspector.ArrayGroupingTreeElement._bucketThreshold}, {value: WebInspector.ArrayGroupingTreeElement._sparseIterationThreshold}], callback);
    function packRanges(fromIndex, toIndex, bucketThreshold, sparseIterationThreshold) {
        var ownPropertyNames = null;

        function doLoop(iterationCallback) {
            if (toIndex - fromIndex < sparseIterationThreshold) {
                for (var i = fromIndex; i <= toIndex; ++i) {
                    if (i in this)
                        iterationCallback(i);
                }
            } else {
                ownPropertyNames = ownPropertyNames || Object.getOwnPropertyNames(this);
                for (var i = 0; i < ownPropertyNames.length; ++i) {
                    var name = ownPropertyNames[i];
                    var index = name >>> 0;
                    if (String(index) === name && fromIndex <= index && index <= toIndex)
                        iterationCallback(index);
                }
            }
        }

        var count = 0;

        function countIterationCallback() {
            ++count;
        }

        doLoop.call(this, countIterationCallback);
        var bucketSize = count;
        if (count <= bucketThreshold)
            bucketSize = count; else
            bucketSize = Math.pow(bucketThreshold, Math.ceil(Math.log(count) / Math.log(bucketThreshold)) - 1);
        var ranges = [];
        count = 0;
        var groupStart = -1;
        var groupEnd = 0;

        function loopIterationCallback(i) {
            if (groupStart === -1)
                groupStart = i;
            groupEnd = i;
            if (++count === bucketSize) {
                ranges.push([groupStart, groupEnd, count]);
                count = 0;
                groupStart = -1;
            }
        }

        doLoop.call(this, loopIterationCallback);
        if (count > 0)
            ranges.push([groupStart, groupEnd, count]);
        return ranges;
    }

    function callback(ranges) {
        if (ranges.length == 1)
            WebInspector.ArrayGroupingTreeElement._populateAsFragment(treeElement, object, ranges[0][0], ranges[0][1]); else {
            for (var i = 0; i < ranges.length; ++i) {
                var fromIndex = ranges[i][0];
                var toIndex = ranges[i][1];
                var count = ranges[i][2];
                if (fromIndex == toIndex)
                    WebInspector.ArrayGroupingTreeElement._populateAsFragment(treeElement, object, fromIndex, toIndex); else
                    treeElement.appendChild(new WebInspector.ArrayGroupingTreeElement(object, fromIndex, toIndex, count));
            }
        }
        if (topLevel)
            WebInspector.ArrayGroupingTreeElement._populateNonIndexProperties(treeElement, object);
    }
}
WebInspector.ArrayGroupingTreeElement._populateAsFragment = function (treeElement, object, fromIndex, toIndex) {
    object.callFunction(buildArrayFragment, [{value: fromIndex}, {value: toIndex}, {value: WebInspector.ArrayGroupingTreeElement._sparseIterationThreshold}], processArrayFragment.bind(this));
    function buildArrayFragment(fromIndex, toIndex, sparseIterationThreshold) {
        var result = Object.create(null);
        if (toIndex - fromIndex < sparseIterationThreshold) {
            for (var i = fromIndex; i <= toIndex; ++i) {
                if (i in this)
                    result[i] = this[i];
            }
        } else {
            var ownPropertyNames = Object.getOwnPropertyNames(this);
            for (var i = 0; i < ownPropertyNames.length; ++i) {
                var name = ownPropertyNames[i];
                var index = name >>> 0;
                if (String(index) === name && fromIndex <= index && index <= toIndex)
                    result[index] = this[index];
            }
        }
        return result;
    }

    function processArrayFragment(arrayFragment, wasThrown) {
        if (!arrayFragment || wasThrown)
            return;
        arrayFragment.getAllProperties(false, processProperties.bind(this));
    }

    function processProperties(properties, internalProperties) {
        if (!properties)
            return;
        properties.sort(WebInspector.ObjectPropertiesSection.CompareProperties);
        for (var i = 0; i < properties.length; ++i) {
            properties[i].parentObject = this._object;
            var childTreeElement = new treeElement.treeOutline.section.treeElementConstructor(properties[i]);
            childTreeElement._readOnly = true;
            treeElement.appendChild(childTreeElement);
        }
    }
}
WebInspector.ArrayGroupingTreeElement._populateNonIndexProperties = function (treeElement, object) {
    object.callFunction(buildObjectFragment, undefined, processObjectFragment.bind(this));
    function buildObjectFragment() {
        var result = Object.create(this.__proto__);
        var names = Object.getOwnPropertyNames(this);
        for (var i = 0; i < names.length; ++i) {
            var name = names[i];
            if (String(name >>> 0) === name && name >>> 0 !== 0xffffffff)
                continue;
            var descriptor = Object.getOwnPropertyDescriptor(this, name);
            if (descriptor)
                Object.defineProperty(result, name, descriptor);
        }
        return result;
    }

    function processObjectFragment(arrayFragment, wasThrown) {
        if (!arrayFragment || wasThrown)
            return;
        arrayFragment.getOwnProperties(processProperties.bind(this));
    }

    function processProperties(properties, internalProperties) {
        if (!properties)
            return;
        properties.sort(WebInspector.ObjectPropertiesSection.CompareProperties);
        for (var i = 0; i < properties.length; ++i) {
            properties[i].parentObject = this._object;
            var childTreeElement = new treeElement.treeOutline.section.treeElementConstructor(properties[i]);
            childTreeElement._readOnly = true;
            treeElement.appendChild(childTreeElement);
        }
    }
}
WebInspector.ArrayGroupingTreeElement.prototype = {
    onpopulate: function () {
        if (this._populated)
            return;
        this._populated = true;
        if (this._propertyCount >= WebInspector.ArrayGroupingTreeElement._bucketThreshold) {
            WebInspector.ArrayGroupingTreeElement._populateRanges(this, this._object, this._fromIndex, this._toIndex, false);
            return;
        }
        WebInspector.ArrayGroupingTreeElement._populateAsFragment(this, this._object, this._fromIndex, this._toIndex);
    }, onattach: function () {
        this.listItemElement.classList.add("name");
    }, __proto__: TreeElement.prototype
}
WebInspector.ObjectPropertyPrompt = function (renderAsBlock) {
    WebInspector.TextPrompt.call(this, WebInspector.ExecutionContextSelector.completionsForTextPromptInCurrentContext);
    this.setSuggestBoxEnabled(true);
    if (renderAsBlock)
        this.renderAsBlock();
}
WebInspector.ObjectPropertyPrompt.prototype = {__proto__: WebInspector.TextPrompt.prototype}
WebInspector.ObjectPopoverHelper = function (panelElement, getAnchor, queryObject, onHide, disableOnClick) {
    WebInspector.PopoverHelper.call(this, panelElement, getAnchor, this._showObjectPopover.bind(this), this._onHideObjectPopover.bind(this), disableOnClick);
    this._queryObject = queryObject;
    this._onHideCallback = onHide;
    this._popoverObjectGroup = "popover";
    panelElement.addEventListener("scroll", this.hidePopover.bind(this), true);
};
WebInspector.ObjectPopoverHelper.prototype = {
    setRemoteObjectFormatter: function (formatter) {
        this._remoteObjectFormatter = formatter;
    }, _showObjectPopover: function (element, popover) {
        function didGetDetails(target, anchorElement, popoverContentElement, response) {
            if (!response)
                return;
            var container = document.createElement("div");
            container.className = "inline-block";
            var title = container.createChild("div", "function-popover-title source-code");
            var functionName = title.createChild("span", "function-name");
            functionName.textContent = response.functionName || WebInspector.UIString("(anonymous function)");
            var rawLocation = response.location;
            var sourceURL = response.sourceURL;
            if (rawLocation && sourceURL) {
                this._linkifier = new WebInspector.Linkifier();
                var link = this._linkifier.linkifyRawLocation(rawLocation, sourceURL, "function-location-link");
                title.appendChild(link);
            }
            container.appendChild(popoverContentElement);
            popover.show(container, anchorElement);
        }

        function showObjectPopover(result, wasThrown, anchorOverride) {
            if (popover.disposed)
                return;
            if (wasThrown) {
                this.hidePopover();
                return;
            }
            this._objectTarget = result.target();
            var anchorElement = anchorOverride || element;
            var description = (this._remoteObjectFormatter && this._remoteObjectFormatter(result)) || result.description;
            var popoverContentElement = null;
            if (result.type !== "object") {
                popoverContentElement = document.createElement("span");
                popoverContentElement.className = "monospace console-formatted-" + result.type;
                popoverContentElement.style.whiteSpace = "pre";
                if (result.type === "string")
                    popoverContentElement.createTextChildren("\"", description, "\""); else
                    popoverContentElement.textContent = description;
                if (result.type === "function") {
                    result.functionDetails(didGetDetails.bind(this, result.target(), anchorElement, popoverContentElement));
                    return;
                }
                popover.show(popoverContentElement, anchorElement);
            } else {
                if (result.subtype === "node") {
                    result.highlightAsDOMNode();
                    this._resultHighlightedAsDOM = result;
                }
                popoverContentElement = document.createElement("div");
                this._titleElement = document.createElement("div");
                this._titleElement.className = "source-frame-popover-title monospace";
                this._titleElement.textContent = description;
                popoverContentElement.appendChild(this._titleElement);
                var section = new WebInspector.ObjectPropertiesSection(result);
                if (description.substr(0, 4) === "HTML") {
                    this._sectionUpdateProperties = section.updateProperties.bind(section);
                    section.updateProperties = this._updateHTMLId.bind(this);
                }
                section.expanded = true;
                section.element.classList.add("source-frame-popover-tree");
                section.headerElement.classList.add("hidden");
                popoverContentElement.appendChild(section.element);
                const popoverWidth = 300;
                const popoverHeight = 250;
                popover.show(popoverContentElement, anchorElement, popoverWidth, popoverHeight);
            }
        }

        this._queryObject(element, showObjectPopover.bind(this), this._popoverObjectGroup);
    }, _onHideObjectPopover: function () {
        if (this._resultHighlightedAsDOM) {
            this._resultHighlightedAsDOM.target().domModel.hideDOMNodeHighlight();
            delete this._resultHighlightedAsDOM;
        }
        if (this._linkifier) {
            this._linkifier.reset();
            delete this._linkifier;
        }
        if (this._onHideCallback)
            this._onHideCallback();
        if (this._objectTarget) {
            this._objectTarget.runtimeAgent().releaseObjectGroup(this._popoverObjectGroup);
            delete this._objectTarget;
        }
    }, _updateHTMLId: function (properties, rootTreeElementConstructor, rootPropertyComparer) {
        for (var i = 0; i < properties.length; ++i) {
            if (properties[i].name === "id") {
                if (properties[i].value.description)
                    this._titleElement.textContent += "#" + properties[i].value.description;
                break;
            }
        }
        this._sectionUpdateProperties(properties, rootTreeElementConstructor, rootPropertyComparer);
    }, __proto__: WebInspector.PopoverHelper.prototype
}
WebInspector.NativeBreakpointsSidebarPane = function (title) {
    WebInspector.SidebarPane.call(this, title);
    this.registerRequiredCSS("breakpointsList.css");
    this.listElement = document.createElement("ol");
    this.listElement.className = "breakpoint-list";
    this.emptyElement = document.createElement("div");
    this.emptyElement.className = "info";
    this.emptyElement.textContent = WebInspector.UIString("No Breakpoints");
    this.bodyElement.appendChild(this.emptyElement);
}
WebInspector.NativeBreakpointsSidebarPane.prototype = {
    addListElement: function (element, beforeElement) {
        if (beforeElement) {
            this.listElement.insertBefore(element, beforeElement);
        } else {
            if (!this.listElement.firstChild) {
                this.bodyElement.removeChild(this.emptyElement);
                this.bodyElement.appendChild(this.listElement);
            }
            this.listElement.appendChild(element);
        }
    }, removeListElement: function (element) {
        this.listElement.removeChild(element);
        if (!this.listElement.firstChild) {
            this.bodyElement.removeChild(this.listElement);
            this.bodyElement.appendChild(this.emptyElement);
        }
    }, reset: function () {
        this.listElement.removeChildren();
        if (this.listElement.parentElement) {
            this.bodyElement.removeChild(this.listElement);
            this.bodyElement.appendChild(this.emptyElement);
        }
    }, __proto__: WebInspector.SidebarPane.prototype
}
WebInspector.DOMBreakpointsSidebarPane = function () {
    WebInspector.NativeBreakpointsSidebarPane.call(this, WebInspector.UIString("DOM Breakpoints"));
    this._breakpointElements = {};
    this._breakpointTypes = {SubtreeModified: "subtree-modified", AttributeModified: "attribute-modified", NodeRemoved: "node-removed"};
    this._breakpointTypeLabels = {};
    this._breakpointTypeLabels[this._breakpointTypes.SubtreeModified] = WebInspector.UIString("Subtree Modified");
    this._breakpointTypeLabels[this._breakpointTypes.AttributeModified] = WebInspector.UIString("Attribute Modified");
    this._breakpointTypeLabels[this._breakpointTypes.NodeRemoved] = WebInspector.UIString("Node Removed");
    this._contextMenuLabels = {};
    this._contextMenuLabels[this._breakpointTypes.SubtreeModified] = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Subtree modifications" : "Subtree Modifications");
    this._contextMenuLabels[this._breakpointTypes.AttributeModified] = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Attributes modifications" : "Attributes Modifications");
    this._contextMenuLabels[this._breakpointTypes.NodeRemoved] = WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Node removal" : "Node Removal");
    WebInspector.targetManager.addModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._inspectedURLChanged, this);
    WebInspector.targetManager.addModelListener(WebInspector.DOMModel, WebInspector.DOMModel.Events.NodeRemoved, this._nodeRemoved, this);
}
WebInspector.DOMBreakpointsSidebarPane.prototype = {
    _inspectedURLChanged: function (event) {
        this._breakpointElements = {};
        this.reset();
        var url = (event.data);
        this._inspectedURL = url.removeURLFragment();
    }, populateNodeContextMenu: function (node, contextMenu) {
        if (node.pseudoType())
            return;
        var nodeBreakpoints = {};
        for (var id in this._breakpointElements) {
            var element = this._breakpointElements[id];
            if (element._node === node)
                nodeBreakpoints[element._type] = true;
        }
        function toggleBreakpoint(type) {
            if (!nodeBreakpoints[type])
                this._setBreakpoint(node, type, true); else
                this._removeBreakpoint(node, type);
            this._saveBreakpoints();
        }

        var breakPointSubMenu = contextMenu.appendSubMenuItem(WebInspector.UIString("Break on..."));
        for (var key in this._breakpointTypes) {
            var type = this._breakpointTypes[key];
            var label = this._contextMenuLabels[type];
            breakPointSubMenu.appendCheckboxItem(label, toggleBreakpoint.bind(this, type), nodeBreakpoints[type]);
        }
    }, createBreakpointHitStatusMessage: function (details, callback) {
        var auxData = (details.auxData);
        var domModel = details.target().domModel;
        if (auxData.type === this._breakpointTypes.SubtreeModified) {
            var targetNodeObject = details.target().runtimeModel.createRemoteObject(auxData["targetNode"]);
            targetNodeObject.pushNodeToFrontend(didPushNodeToFrontend.bind(this));
        } else {
            this._doCreateBreakpointHitStatusMessage(auxData, domModel.nodeForId(auxData.nodeId), null, callback);
        }
        function didPushNodeToFrontend(targetNode) {
            if (targetNode)
                targetNodeObject.release();
            this._doCreateBreakpointHitStatusMessage(auxData, domModel.nodeForId(auxData.nodeId), targetNode, callback);
        }
    }, _doCreateBreakpointHitStatusMessage: function (auxData, node, targetNode, callback) {
        var message;
        var typeLabel = this._breakpointTypeLabels[auxData.type];
        var linkifiedNode = WebInspector.DOMPresentationUtils.linkifyNodeReference(node);
        var substitutions = [typeLabel, linkifiedNode];
        var targetNodeLink = "";
        if (targetNode)
            targetNodeLink = WebInspector.DOMPresentationUtils.linkifyNodeReference(targetNode);
        if (auxData.type === this._breakpointTypes.SubtreeModified) {
            if (auxData.insertion) {
                if (targetNode !== node) {
                    message = "Paused on a \"%s\" breakpoint set on %s, because a new child was added to its descendant %s.";
                    substitutions.push(targetNodeLink);
                } else
                    message = "Paused on a \"%s\" breakpoint set on %s, because a new child was added to that node.";
            } else {
                message = "Paused on a \"%s\" breakpoint set on %s, because its descendant %s was removed.";
                substitutions.push(targetNodeLink);
            }
        } else
            message = "Paused on a \"%s\" breakpoint set on %s.";
        var element = document.createElement("span");
        var formatters = {
            s: function (substitution) {
                return substitution;
            }
        };

        function append(a, b) {
            if (typeof b === "string")
                b = document.createTextNode(b);
            element.appendChild(b);
        }

        WebInspector.formatLocalized(message, substitutions, formatters, "", append);
        callback(element);
    }, _nodeRemoved: function (event) {
        var node = event.data.node;
        this._removeBreakpointsForNode(event.data.node);
        var children = node.children();
        if (!children)
            return;
        for (var i = 0; i < children.length; ++i)
            this._removeBreakpointsForNode(children[i]);
        this._saveBreakpoints();
    }, _removeBreakpointsForNode: function (node) {
        for (var id in this._breakpointElements) {
            var element = this._breakpointElements[id];
            if (element._node === node)
                this._removeBreakpoint(element._node, element._type);
        }
    }, _setBreakpoint: function (node, type, enabled) {
        var breakpointId = this._createBreakpointId(node.id, type);
        if (breakpointId in this._breakpointElements)
            return;
        var element = document.createElement("li");
        element._node = node;
        element._type = type;
        element.addEventListener("contextmenu", this._contextMenu.bind(this, node, type), true);
        var checkboxElement = document.createElement("input");
        checkboxElement.className = "checkbox-elem";
        checkboxElement.type = "checkbox";
        checkboxElement.checked = enabled;
        checkboxElement.addEventListener("click", this._checkboxClicked.bind(this, node, type), false);
        element._checkboxElement = checkboxElement;
        element.appendChild(checkboxElement);
        var labelElement = document.createElement("span");
        element.appendChild(labelElement);
        var linkifiedNode = WebInspector.DOMPresentationUtils.linkifyNodeReference(node);
        linkifiedNode.classList.add("monospace");
        labelElement.appendChild(linkifiedNode);
        var description = document.createElement("div");
        description.className = "source-text";
        description.textContent = this._breakpointTypeLabels[type];
        labelElement.appendChild(description);
        var currentElement = this.listElement.firstChild;
        while (currentElement) {
            if (currentElement._type && currentElement._type < element._type)
                break;
            currentElement = currentElement.nextSibling;
        }
        this.addListElement(element, currentElement);
        this._breakpointElements[breakpointId] = element;
        if (enabled)
            DOMDebuggerAgent.setDOMBreakpoint(node.id, type);
    }, _removeAllBreakpoints: function () {
        for (var id in this._breakpointElements) {
            var element = this._breakpointElements[id];
            this._removeBreakpoint(element._node, element._type);
        }
        this._saveBreakpoints();
    }, _removeBreakpoint: function (node, type) {
        var breakpointId = this._createBreakpointId(node.id, type);
        var element = this._breakpointElements[breakpointId];
        if (!element)
            return;
        this.removeListElement(element);
        delete this._breakpointElements[breakpointId];
        if (element._checkboxElement.checked)
            DOMDebuggerAgent.removeDOMBreakpoint(node.id, type);
    }, _contextMenu: function (node, type, event) {
        var contextMenu = new WebInspector.ContextMenu(event);

        function removeBreakpoint() {
            this._removeBreakpoint(node, type);
            this._saveBreakpoints();
        }

        contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Remove breakpoint" : "Remove Breakpoint"), removeBreakpoint.bind(this));
        contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Remove all DOM breakpoints" : "Remove All DOM Breakpoints"), this._removeAllBreakpoints.bind(this));
        contextMenu.show();
    }, _checkboxClicked: function (node, type, event) {
        if (event.target.checked)
            DOMDebuggerAgent.setDOMBreakpoint(node.id, type); else
            DOMDebuggerAgent.removeDOMBreakpoint(node.id, type);
        this._saveBreakpoints();
    }, highlightBreakpoint: function (auxData) {
        var breakpointId = this._createBreakpointId(auxData.nodeId, auxData.type);
        var element = this._breakpointElements[breakpointId];
        if (!element)
            return;
        this.expand();
        element.classList.add("breakpoint-hit");
        this._highlightedElement = element;
    }, clearBreakpointHighlight: function () {
        if (this._highlightedElement) {
            this._highlightedElement.classList.remove("breakpoint-hit");
            delete this._highlightedElement;
        }
    }, _createBreakpointId: function (nodeId, type) {
        return nodeId + ":" + type;
    }, _saveBreakpoints: function () {
        var breakpoints = [];
        var storedBreakpoints = WebInspector.settings.domBreakpoints.get();
        for (var i = 0; i < storedBreakpoints.length; ++i) {
            var breakpoint = storedBreakpoints[i];
            if (breakpoint.url !== this._inspectedURL)
                breakpoints.push(breakpoint);
        }
        for (var id in this._breakpointElements) {
            var element = this._breakpointElements[id];
            breakpoints.push({url: this._inspectedURL, path: element._node.path(), type: element._type, enabled: element._checkboxElement.checked});
        }
        WebInspector.settings.domBreakpoints.set(breakpoints);
    }, restoreBreakpoints: function (target) {
        var pathToBreakpoints = {};

        function didPushNodeByPathToFrontend(path, nodeId) {
            var node = nodeId ? target.domModel.nodeForId(nodeId) : null;
            if (!node)
                return;
            var breakpoints = pathToBreakpoints[path];
            for (var i = 0; i < breakpoints.length; ++i)
                this._setBreakpoint(node, breakpoints[i].type, breakpoints[i].enabled);
        }

        var breakpoints = WebInspector.settings.domBreakpoints.get();
        for (var i = 0; i < breakpoints.length; ++i) {
            var breakpoint = breakpoints[i];
            if (breakpoint.url !== this._inspectedURL)
                continue;
            var path = breakpoint.path;
            if (!pathToBreakpoints[path]) {
                pathToBreakpoints[path] = [];
                target.domModel.pushNodeByPathToFrontend(path, didPushNodeByPathToFrontend.bind(this, path));
            }
            pathToBreakpoints[path].push(breakpoint);
        }
    }, createProxy: function (panel) {
        var proxy = new WebInspector.DOMBreakpointsSidebarPane.Proxy(this, panel);
        if (!this._proxies)
            this._proxies = [];
        this._proxies.push(proxy);
        return proxy;
    }, onContentReady: function () {
        for (var i = 0; i != this._proxies.length; i++)
            this._proxies[i].onContentReady();
    }, __proto__: WebInspector.NativeBreakpointsSidebarPane.prototype
}
WebInspector.DOMBreakpointsSidebarPane.Proxy = function (pane, panel) {
    WebInspector.View.__assert(!pane.titleElement.firstChild, "Cannot create proxy for a sidebar pane with a toolbar");
    WebInspector.SidebarPane.call(this, pane.title());
    this.registerRequiredCSS("breakpointsList.css");
    this._wrappedPane = pane;
    this._panel = panel;
    this.bodyElement.remove();
    this.bodyElement = this._wrappedPane.bodyElement;
}
WebInspector.DOMBreakpointsSidebarPane.Proxy.prototype = {
    expand: function () {
        this._wrappedPane.expand();
    }, onContentReady: function () {
        if (this._panel.isShowing())
            this._reattachBody();
        WebInspector.SidebarPane.prototype.onContentReady.call(this);
    }, wasShown: function () {
        WebInspector.SidebarPane.prototype.wasShown.call(this);
        this._reattachBody();
    }, _reattachBody: function () {
        if (this.bodyElement.parentNode !== this.element)
            this.element.appendChild(this.bodyElement);
    }, __proto__: WebInspector.SidebarPane.prototype
}
WebInspector.domBreakpointsSidebarPane;
WebInspector.CSSMetadata = function (properties) {
    this._values = ([]);
    this._longhands = {};
    this._shorthands = {};
    for (var i = 0; i < properties.length; ++i) {
        var property = properties[i];
        if (typeof property === "string") {
            this._values.push(property);
            continue;
        }
        var propertyName = property.name;
        this._values.push(propertyName);
        var longhands = properties[i].longhands;
        if (longhands) {
            this._longhands[propertyName] = longhands;
            for (var j = 0; j < longhands.length; ++j) {
                var longhandName = longhands[j];
                var shorthands = this._shorthands[longhandName];
                if (!shorthands) {
                    shorthands = [];
                    this._shorthands[longhandName] = shorthands;
                }
                shorthands.push(propertyName);
            }
        }
    }
    this._values.sort();
}
WebInspector.CSSMetadata.cssPropertiesMetainfo = new WebInspector.CSSMetadata([]);
WebInspector.CSSMetadata.isColorAwareProperty = function (propertyName) {
    return !!WebInspector.CSSMetadata._colorAwareProperties[propertyName.toLowerCase()];
}
WebInspector.CSSMetadata.colors = function () {
    if (!WebInspector.CSSMetadata._colorsKeySet)
        WebInspector.CSSMetadata._colorsKeySet = WebInspector.CSSMetadata._colors.keySet();
    return WebInspector.CSSMetadata._colorsKeySet;
}
WebInspector.CSSMetadata.isLengthProperty = function (propertyName) {
    if (propertyName === "line-height")
        return false;
    if (!WebInspector.CSSMetadata._distancePropertiesKeySet)
        WebInspector.CSSMetadata._distancePropertiesKeySet = WebInspector.CSSMetadata._distanceProperties.keySet();
    return WebInspector.CSSMetadata._distancePropertiesKeySet[propertyName] || propertyName.startsWith("margin") || propertyName.startsWith("padding") || propertyName.indexOf("width") !== -1 || propertyName.indexOf("height") !== -1;
}
WebInspector.CSSMetadata.InheritedProperties = ["azimuth", "border-collapse", "border-spacing", "caption-side", "color", "cursor", "direction", "elevation", "empty-cells", "font-family", "font-size", "font-style", "font-variant", "font-weight", "font", "letter-spacing", "line-height", "list-style-image", "list-style-position", "list-style-type", "list-style", "orphans", "overflow-wrap", "pitch-range", "pitch", "quotes", "resize", "richness", "speak-header", "speak-numeral", "speak-punctuation", "speak", "speech-rate", "stress", "text-align", "text-indent", "text-transform", "text-shadow", "visibility", "voice-family", "volume", "white-space", "widows", "word-spacing", "word-wrap", "zoom"].keySet();
WebInspector.CSSMetadata.NonStandardInheritedProperties = ["-webkit-font-smoothing"].keySet();
WebInspector.CSSMetadata.canonicalPropertyName = function (name) {
    if (!name || name.length < 9 || name.charAt(0) !== "-")
        return name.toLowerCase();
    var match = name.match(/(?:-webkit-)(.+)/);
    var propertiesSet = WebInspector.CSSMetadata.cssPropertiesMetainfoKeySet();
    var hasSupportedProperties = WebInspector.CSSMetadata.cssPropertiesMetainfo._values.length > 0;
    if (!match || (hasSupportedProperties && !propertiesSet.hasOwnProperty(match[1].toLowerCase())))
        return name.toLowerCase();
    return match[1].toLowerCase();
}
WebInspector.CSSMetadata.isPropertyInherited = function (propertyName) {
    return !!(WebInspector.CSSMetadata.InheritedProperties[WebInspector.CSSMetadata.canonicalPropertyName(propertyName)] || WebInspector.CSSMetadata.NonStandardInheritedProperties[propertyName.toLowerCase()]);
}
WebInspector.CSSMetadata._colors = ["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "orange", "purple", "red", "silver", "teal", "white", "yellow", "transparent", "currentcolor", "grey", "aliceblue", "antiquewhite", "aquamarine", "azure", "beige", "bisque", "blanchedalmond", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "gainsboro", "ghostwhite", "gold", "goldenrod", "greenyellow", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", "limegreen", "linen", "magenta", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "oldlace", "olivedrab", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "thistle", "tomato", "turquoise", "violet", "wheat", "whitesmoke", "yellowgreen"];
WebInspector.CSSMetadata._distanceProperties = ['background-position', 'border-spacing', 'bottom', 'font-size', 'height', 'left', 'letter-spacing', 'max-height', 'max-width', 'min-height', 'min-width', 'right', 'text-indent', 'top', 'width', 'word-spacing'];
WebInspector.CSSMetadata._colorAwareProperties = ["background", "background-color", "background-image", "border", "border-color", "border-top", "border-right", "border-bottom", "border-left", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "box-shadow", "color", "fill", "outline", "outline-color", "stroke", "text-shadow", "-webkit-box-shadow", "-webkit-column-rule-color", "-webkit-text-decoration-color", "-webkit-text-emphasis", "-webkit-text-emphasis-color"].keySet();
WebInspector.CSSMetadata._propertyDataMap = {
    "table-layout": {values: ["auto", "fixed"]},
    "visibility": {values: ["hidden", "visible", "collapse"]},
    "background-repeat": {values: ["repeat", "repeat-x", "repeat-y", "no-repeat", "space", "round"]},
    "content": {values: ["list-item", "close-quote", "no-close-quote", "no-open-quote", "open-quote"]},
    "list-style-image": {values: ["none"]},
    "clear": {values: ["none", "left", "right", "both"]},
    "overflow-x": {values: ["hidden", "auto", "visible", "overlay", "scroll"]},
    "stroke-linejoin": {values: ["round", "miter", "bevel"]},
    "baseline-shift": {values: ["baseline", "sub", "super"]},
    "border-bottom-width": {values: ["medium", "thick", "thin"]},
    "marquee-speed": {values: ["normal", "slow", "fast"]},
    "margin-top-collapse": {values: ["collapse", "separate", "discard"]},
    "max-height": {values: ["none"]},
    "box-orient": {values: ["horizontal", "vertical", "inline-axis", "block-axis"],},
    "font-stretch": {values: ["normal", "wider", "narrower", "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", "semi-expanded", "expanded", "extra-expanded", "ultra-expanded"]},
    "-webkit-background-composite": {values: ["highlight", "clear", "copy", "source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop", "xor", "plus-darker", "plus-lighter"]},
    "border-left-width": {values: ["medium", "thick", "thin"]},
    "box-shadow": {values: ["inset", "none"]},
    "-webkit-writing-mode": {values: ["lr", "rl", "tb", "lr-tb", "rl-tb", "tb-rl", "horizontal-tb", "vertical-rl", "vertical-lr", "horizontal-bt"]},
    "border-collapse": {values: ["collapse", "separate"]},
    "page-break-inside": {values: ["auto", "avoid"]},
    "border-top-width": {values: ["medium", "thick", "thin"]},
    "outline-color": {values: ["invert"]},
    "outline-style": {values: ["none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double"]},
    "cursor": {values: ["none", "copy", "auto", "crosshair", "default", "pointer", "move", "vertical-text", "cell", "context-menu", "alias", "progress", "no-drop", "not-allowed", "-webkit-zoom-in", "-webkit-zoom-out", "e-resize", "ne-resize", "nw-resize", "n-resize", "se-resize", "sw-resize", "s-resize", "w-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "col-resize", "row-resize", "text", "wait", "help", "all-scroll", "-webkit-grab", "-webkit-grabbing"]},
    "border-width": {values: ["medium", "thick", "thin"]},
    "border-style": {values: ["none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double"]},
    "size": {values: ["a3", "a4", "a5", "b4", "b5", "landscape", "ledger", "legal", "letter", "portrait"]},
    "background-size": {values: ["contain", "cover"]},
    "direction": {values: ["ltr", "rtl"]},
    "marquee-direction": {values: ["left", "right", "auto", "reverse", "forwards", "backwards", "ahead", "up", "down"]},
    "enable-background": {values: ["accumulate", "new"]},
    "float": {values: ["none", "left", "right"]},
    "overflow-y": {values: ["hidden", "auto", "visible", "overlay", "scroll"]},
    "margin-bottom-collapse": {values: ["collapse", "separate", "discard"]},
    "box-reflect": {values: ["left", "right", "above", "below"]},
    "overflow": {values: ["hidden", "auto", "visible", "overlay", "scroll"]},
    "text-rendering": {values: ["auto", "optimizeSpeed", "optimizeLegibility", "geometricPrecision"]},
    "text-align": {values: ["-webkit-auto", "start", "end", "left", "right", "center", "justify", "-webkit-left", "-webkit-right", "-webkit-center"]},
    "list-style-position": {values: ["outside", "inside", "hanging"]},
    "margin-bottom": {values: ["auto"]},
    "color-interpolation": {values: ["linearrgb"]},
    "background-origin": {values: ["border-box", "content-box", "padding-box"]},
    "word-wrap": {values: ["normal", "break-word"]},
    "font-weight": {values: ["normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900"]},
    "margin-before-collapse": {values: ["collapse", "separate", "discard"]},
    "text-transform": {values: ["none", "capitalize", "uppercase", "lowercase"]},
    "border-right-style": {values: ["none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double"]},
    "border-left-style": {values: ["none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double"]},
    "-webkit-text-emphasis": {values: ["circle", "filled", "open", "dot", "double-circle", "triangle", "sesame"]},
    "font-style": {values: ["italic", "oblique", "normal"]},
    "speak": {values: ["none", "normal", "spell-out", "digits", "literal-punctuation", "no-punctuation"]},
    "color-rendering": {values: ["auto", "optimizeSpeed", "optimizeQuality"]},
    "list-style-type": {values: ["none", "inline", "disc", "circle", "square", "decimal", "decimal-leading-zero", "arabic-indic", "binary", "bengali", "cambodian", "khmer", "devanagari", "gujarati", "gurmukhi", "kannada", "lower-hexadecimal", "lao", "malayalam", "mongolian", "myanmar", "octal", "oriya", "persian", "urdu", "telugu", "tibetan", "thai", "upper-hexadecimal", "lower-roman", "upper-roman", "lower-greek", "lower-alpha", "lower-latin", "upper-alpha", "upper-latin", "afar", "ethiopic-halehame-aa-et", "ethiopic-halehame-aa-er", "amharic", "ethiopic-halehame-am-et", "amharic-abegede", "ethiopic-abegede-am-et", "cjk-earthly-branch", "cjk-heavenly-stem", "ethiopic", "ethiopic-halehame-gez", "ethiopic-abegede", "ethiopic-abegede-gez", "hangul-consonant", "hangul", "lower-norwegian", "oromo", "ethiopic-halehame-om-et", "sidama", "ethiopic-halehame-sid-et", "somali", "ethiopic-halehame-so-et", "tigre", "ethiopic-halehame-tig", "tigrinya-er", "ethiopic-halehame-ti-er", "tigrinya-er-abegede", "ethiopic-abegede-ti-er", "tigrinya-et", "ethiopic-halehame-ti-et", "tigrinya-et-abegede", "ethiopic-abegede-ti-et", "upper-greek", "upper-norwegian", "asterisks", "footnotes", "hebrew", "armenian", "lower-armenian", "upper-armenian", "georgian", "cjk-ideographic", "hiragana", "katakana", "hiragana-iroha", "katakana-iroha"]},
    "-webkit-text-combine": {values: ["none", "horizontal"]},
    "outline": {values: ["none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double"]},
    "font": {values: ["caption", "icon", "menu", "message-box", "small-caption", "-webkit-mini-control", "-webkit-small-control", "-webkit-control", "status-bar", "italic", "oblique", "small-caps", "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900", "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "-webkit-xxx-large", "smaller", "larger", "serif", "sans-serif", "cursive", "fantasy", "monospace", "-webkit-body", "-webkit-pictograph"]},
    "dominant-baseline": {values: ["middle", "auto", "central", "text-before-edge", "text-after-edge", "ideographic", "alphabetic", "hanging", "mathematical", "use-script", "no-change", "reset-size"]},
    "display": {values: ["none", "inline", "block", "list-item", "run-in", "compact", "inline-block", "table", "inline-table", "table-row-group", "table-header-group", "table-footer-group", "table-row", "table-column-group", "table-column", "table-cell", "table-caption", "-webkit-box", "-webkit-inline-box", "flex", "inline-flex", "grid", "inline-grid"]},
    "-webkit-text-emphasis-position": {values: ["over", "under"]},
    "image-rendering": {values: ["auto", "optimizeSpeed", "optimizeQuality", "pixelated"]},
    "alignment-baseline": {values: ["baseline", "middle", "auto", "before-edge", "after-edge", "central", "text-before-edge", "text-after-edge", "ideographic", "alphabetic", "hanging", "mathematical"]},
    "outline-width": {values: ["medium", "thick", "thin"]},
    "box-align": {values: ["baseline", "center", "stretch", "start", "end"]},
    "border-right-width": {values: ["medium", "thick", "thin"]},
    "border-top-style": {values: ["none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double"]},
    "line-height": {values: ["normal"]},
    "text-overflow": {values: ["clip", "ellipsis"]},
    "overflow-wrap": {values: ["normal", "break-word"]},
    "box-direction": {values: ["normal", "reverse"]},
    "margin-after-collapse": {values: ["collapse", "separate", "discard"]},
    "page-break-before": {values: ["left", "right", "auto", "always", "avoid"]},
    "border-image": {values: ["repeat", "stretch"]},
    "text-decoration": {values: ["blink", "line-through", "overline", "underline"]},
    "position": {values: ["absolute", "fixed", "relative", "static"]},
    "font-family": {values: ["serif", "sans-serif", "cursive", "fantasy", "monospace", "-webkit-body", "-webkit-pictograph"]},
    "text-overflow-mode": {values: ["clip", "ellipsis"]},
    "border-bottom-style": {values: ["none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double"]},
    "unicode-bidi": {values: ["normal", "bidi-override", "embed", "isolate", "isolate-override", "plaintext"]},
    "clip-rule": {values: ["nonzero", "evenodd"]},
    "margin-left": {values: ["auto"]},
    "margin-top": {values: ["auto"]},
    "zoom": {values: ["normal", "document", "reset"]},
    "max-width": {values: ["none"]},
    "caption-side": {values: ["top", "bottom"]},
    "empty-cells": {values: ["hide", "show"]},
    "pointer-events": {values: ["none", "all", "auto", "visible", "visiblepainted", "visiblefill", "visiblestroke", "painted", "fill", "stroke", "bounding-box"]},
    "letter-spacing": {values: ["normal"]},
    "background-clip": {values: ["border-box", "content-box", "padding-box"]},
    "-webkit-font-smoothing": {values: ["none", "auto", "antialiased", "subpixel-antialiased"]},
    "border": {values: ["none", "hidden", "inset", "groove", "ridge", "outset", "dotted", "dashed", "solid", "double"]},
    "font-size": {values: ["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "-webkit-xxx-large", "smaller", "larger"]},
    "font-variant": {values: ["small-caps", "normal"]},
    "vertical-align": {values: ["baseline", "middle", "sub", "super", "text-top", "text-bottom", "top", "bottom", "-webkit-baseline-middle"]},
    "marquee-style": {values: ["none", "scroll", "slide", "alternate"]},
    "white-space": {values: ["normal", "nowrap", "pre", "pre-line", "pre-wrap"]},
    "box-lines": {values: ["single", "multiple"]},
    "page-break-after": {values: ["left", "right", "auto", "always", "avoid"]},
    "clip-path": {values: ["none"]},
    "margin": {values: ["auto"]},
    "marquee-repetition": {values: ["infinite"]},
    "margin-right": {values: ["auto"]},
    "word-break": {values: ["normal", "break-all", "break-word"]},
    "word-spacing": {values: ["normal"]},
    "-webkit-text-emphasis-style": {values: ["circle", "filled", "open", "dot", "double-circle", "triangle", "sesame"]},
    "transform": {values: ["scale", "scaleX", "scaleY", "scale3d", "rotate", "rotateX", "rotateY", "rotateZ", "rotate3d", "skew", "skewX", "skewY", "translate", "translateX", "translateY", "translateZ", "translate3d", "matrix", "matrix3d", "perspective"]},
    "image-resolution": {values: ["from-image", "snap"]},
    "box-sizing": {values: ["content-box", "padding-box", "border-box"]},
    "clip": {values: ["auto"]},
    "resize": {values: ["none", "both", "horizontal", "vertical"]},
    "align-content": {values: ["flex-start", "flex-end", "center", "space-between", "space-around", "stretch"]},
    "align-items": {values: ["flex-start", "flex-end", "center", "baseline", "stretch"]},
    "align-self": {values: ["auto", "flex-start", "flex-end", "center", "baseline", "stretch"]},
    "flex-direction": {values: ["row", "row-reverse", "column", "column-reverse"]},
    "justify-content": {values: ["flex-start", "flex-end", "center", "space-between", "space-around"]},
    "flex-wrap": {values: ["nowrap", "wrap", "wrap-reverse"]},
    "-webkit-animation-timing-function": {values: ["ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "steps", "cubic-bezier"]},
    "-webkit-animation-direction": {values: ["normal", "reverse", "alternate", "alternate-reverse"]},
    "-webkit-animation-play-state": {values: ["running", "paused"]},
    "-webkit-animation-fill-mode": {values: ["none", "forwards", "backwards", "both"]},
    "-webkit-backface-visibility": {values: ["visible", "hidden"]},
    "-webkit-box-decoration-break": {values: ["slice", "clone"]},
    "-webkit-column-break-after": {values: ["auto", "always", "avoid", "left", "right", "page", "column", "avoid-page", "avoid-column"]},
    "-webkit-column-break-before": {values: ["auto", "always", "avoid", "left", "right", "page", "column", "avoid-page", "avoid-column"]},
    "-webkit-column-break-inside": {values: ["auto", "avoid", "avoid-page", "avoid-column"]},
    "-webkit-column-span": {values: ["none", "all"]},
    "-webkit-column-count": {values: ["auto"]},
    "-webkit-column-gap": {values: ["normal"]},
    "-webkit-line-break": {values: ["auto", "loose", "normal", "strict"]},
    "-webkit-perspective": {values: ["none"]},
    "-webkit-perspective-origin": {values: ["left", "center", "right", "top", "bottom"]},
    "text-align-last": {values: ["auto", "start", "end", "left", "right", "center", "justify"]},
    "-webkit-text-decoration-line": {values: ["none", "underline", "overline", "line-through", "blink"]},
    "-webkit-text-decoration-style": {values: ["solid", "double", "dotted", "dashed", "wavy"]},
    "-webkit-text-decoration-skip": {values: ["none", "objects", "spaces", "ink", "edges", "box-decoration"]},
    "-webkit-transform-origin": {values: ["left", "center", "right", "top", "bottom"]},
    "-webkit-transform-style": {values: ["flat", "preserve-3d"]},
    "-webkit-transition-timing-function": {values: ["ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "steps", "cubic-bezier"]},
    "-webkit-flex": {m: "flexbox"},
    "-webkit-flex-basis": {m: "flexbox"},
    "-webkit-flex-flow": {m: "flexbox"},
    "-webkit-flex-grow": {m: "flexbox"},
    "-webkit-flex-shrink": {m: "flexbox"},
    "-webkit-animation": {m: "animations"},
    "-webkit-animation-delay": {m: "animations"},
    "-webkit-animation-duration": {m: "animations"},
    "-webkit-animation-iteration-count": {m: "animations"},
    "-webkit-animation-name": {m: "animations"},
    "-webkit-column-rule": {m: "multicol"},
    "-webkit-column-rule-color": {m: "multicol", a: "crc"},
    "-webkit-column-rule-style": {m: "multicol", a: "crs"},
    "-webkit-column-rule-width": {m: "multicol", a: "crw"},
    "-webkit-column-width": {m: "multicol", a: "cw"},
    "-webkit-columns": {m: "multicol"},
    "-webkit-order": {m: "flexbox"},
    "-webkit-text-decoration-color": {m: "text-decor"},
    "-webkit-text-emphasis-color": {m: "text-decor"},
    "-webkit-transition": {m: "transitions"},
    "-webkit-transition-delay": {m: "transitions"},
    "-webkit-transition-duration": {m: "transitions"},
    "-webkit-transition-property": {m: "transitions"},
    "background": {m: "background"},
    "background-attachment": {m: "background"},
    "background-color": {m: "background"},
    "background-image": {m: "background"},
    "background-position": {m: "background"},
    "background-position-x": {m: "background"},
    "background-position-y": {m: "background"},
    "background-repeat-x": {m: "background"},
    "background-repeat-y": {m: "background"},
    "border-top": {m: "background"},
    "border-right": {m: "background"},
    "border-bottom": {m: "background"},
    "border-left": {m: "background"},
    "border-radius": {m: "background"},
    "bottom": {m: "visuren"},
    "color": {m: "color", a: "foreground"},
    "counter-increment": {m: "generate"},
    "counter-reset": {m: "generate"},
    "grid-template-columns": {m: "grid"},
    "grid-template-rows": {m: "grid"},
    "height": {m: "box"},
    "image-orientation": {m: "images"},
    "left": {m: "visuren"},
    "list-style": {m: "lists"},
    "min-height": {m: "box"},
    "min-width": {m: "box"},
    "opacity": {m: "color", a: "transparency"},
    "orphans": {m: "page"},
    "outline-offset": {m: "ui"},
    "padding": {m: "box", a: "padding1"},
    "padding-bottom": {m: "box"},
    "padding-left": {m: "box"},
    "padding-right": {m: "box"},
    "padding-top": {m: "box"},
    "page": {m: "page"},
    "quotes": {m: "generate"},
    "right": {m: "visuren"},
    "tab-size": {m: "text"},
    "text-indent": {m: "text"},
    "text-shadow": {m: "text-decor"},
    "top": {m: "visuren"},
    "unicode-range": {m: "fonts", a: "descdef-unicode-range"},
    "widows": {m: "page"},
    "width": {m: "box"},
    "z-index": {m: "visuren"}
}
WebInspector.CSSMetadata.keywordsForProperty = function (propertyName) {
    var acceptedKeywords = ["inherit", "initial"];
    var descriptor = WebInspector.CSSMetadata.descriptor(propertyName);
    if (descriptor && descriptor.values)
        acceptedKeywords.push.apply(acceptedKeywords, descriptor.values);
    if (WebInspector.CSSMetadata.isColorAwareProperty(propertyName))
        acceptedKeywords.push.apply(acceptedKeywords, WebInspector.CSSMetadata._colors);
    return new WebInspector.CSSMetadata(acceptedKeywords);
}
WebInspector.CSSMetadata.descriptor = function (propertyName) {
    if (!propertyName)
        return null;
    var unprefixedName = propertyName.replace(/^-webkit-/, "");
    propertyName = propertyName.toLowerCase();
    var entry = WebInspector.CSSMetadata._propertyDataMap[propertyName];
    if (!entry && unprefixedName !== propertyName)
        entry = WebInspector.CSSMetadata._propertyDataMap[unprefixedName];
    return entry || null;
}
WebInspector.CSSMetadata.initializeWithSupportedProperties = function (properties) {
    WebInspector.CSSMetadata.cssPropertiesMetainfo = new WebInspector.CSSMetadata(properties);
}
WebInspector.CSSMetadata.cssPropertiesMetainfoKeySet = function () {
    if (!WebInspector.CSSMetadata._cssPropertiesMetainfoKeySet)
        WebInspector.CSSMetadata._cssPropertiesMetainfoKeySet = WebInspector.CSSMetadata.cssPropertiesMetainfo.keySet();
    return WebInspector.CSSMetadata._cssPropertiesMetainfoKeySet;
}
WebInspector.CSSMetadata.Weight = {
    "-webkit-animation": 1,
    "-webkit-animation-duration": 1,
    "-webkit-animation-iteration-count": 1,
    "-webkit-animation-name": 1,
    "-webkit-animation-timing-function": 1,
    "-webkit-appearance": 1,
    "-webkit-background-clip": 2,
    "-webkit-border-horizontal-spacing": 1,
    "-webkit-border-vertical-spacing": 1,
    "-webkit-box-shadow": 24,
    "-webkit-font-smoothing": 2,
    "-webkit-transition": 8,
    "-webkit-transition-delay": 7,
    "-webkit-transition-duration": 7,
    "-webkit-transition-property": 7,
    "-webkit-transition-timing-function": 6,
    "-webkit-user-select": 1,
    "background": 222,
    "background-attachment": 144,
    "background-clip": 143,
    "background-color": 222,
    "background-image": 201,
    "background-origin": 142,
    "background-size": 25,
    "border": 121,
    "border-bottom": 121,
    "border-bottom-color": 121,
    "border-bottom-left-radius": 50,
    "border-bottom-right-radius": 50,
    "border-bottom-style": 114,
    "border-bottom-width": 120,
    "border-collapse": 3,
    "border-left": 95,
    "border-left-color": 95,
    "border-left-style": 89,
    "border-left-width": 94,
    "border-radius": 50,
    "border-right": 93,
    "border-right-color": 93,
    "border-right-style": 88,
    "border-right-width": 93,
    "border-top": 111,
    "border-top-color": 111,
    "border-top-left-radius": 49,
    "border-top-right-radius": 49,
    "border-top-style": 104,
    "border-top-width": 109,
    "bottom": 16,
    "box-shadow": 25,
    "box-sizing": 2,
    "clear": 23,
    "color": 237,
    "cursor": 34,
    "direction": 4,
    "display": 210,
    "fill": 2,
    "filter": 1,
    "float": 105,
    "font": 174,
    "font-family": 25,
    "font-size": 174,
    "font-style": 9,
    "font-weight": 89,
    "height": 161,
    "left": 54,
    "letter-spacing": 3,
    "line-height": 75,
    "list-style": 17,
    "list-style-image": 8,
    "list-style-position": 8,
    "list-style-type": 17,
    "margin": 241,
    "margin-bottom": 226,
    "margin-left": 225,
    "margin-right": 213,
    "margin-top": 241,
    "max-height": 5,
    "max-width": 11,
    "min-height": 9,
    "min-width": 6,
    "opacity": 24,
    "outline": 10,
    "outline-color": 10,
    "outline-style": 10,
    "outline-width": 10,
    "overflow": 57,
    "overflow-x": 56,
    "overflow-y": 57,
    "padding": 216,
    "padding-bottom": 208,
    "padding-left": 216,
    "padding-right": 206,
    "padding-top": 216,
    "position": 136,
    "resize": 1,
    "right": 29,
    "stroke": 1,
    "stroke-width": 1,
    "table-layout": 1,
    "text-align": 66,
    "text-decoration": 53,
    "text-indent": 9,
    "text-overflow": 8,
    "text-shadow": 19,
    "text-transform": 5,
    "top": 71,
    "transform": 1,
    "unicode-bidi": 1,
    "vertical-align": 37,
    "visibility": 11,
    "white-space": 24,
    "width": 255,
    "word-wrap": 6,
    "z-index": 32,
    "zoom": 10
};
WebInspector.CSSMetadata.prototype = {
    startsWith: function (prefix) {
        var firstIndex = this._firstIndexOfPrefix(prefix);
        if (firstIndex === -1)
            return [];
        var results = [];
        while (firstIndex < this._values.length && this._values[firstIndex].startsWith(prefix))
            results.push(this._values[firstIndex++]);
        return results;
    }, mostUsedOf: function (properties) {
        var maxWeight = 0;
        var index = 0;
        for (var i = 0; i < properties.length; i++) {
            var weight = WebInspector.CSSMetadata.Weight[properties[i]];
            if (!weight)
                weight = WebInspector.CSSMetadata.Weight[WebInspector.CSSMetadata.canonicalPropertyName(properties[i])];
            if (weight > maxWeight) {
                maxWeight = weight;
                index = i;
            }
        }
        return index;
    }, _firstIndexOfPrefix: function (prefix) {
        if (!this._values.length)
            return -1;
        if (!prefix)
            return 0;
        var maxIndex = this._values.length - 1;
        var minIndex = 0;
        var foundIndex;
        do {
            var middleIndex = (maxIndex + minIndex) >> 1;
            if (this._values[middleIndex].startsWith(prefix)) {
                foundIndex = middleIndex;
                break;
            }
            if (this._values[middleIndex] < prefix)
                minIndex = middleIndex + 1; else
                maxIndex = middleIndex - 1;
        } while (minIndex <= maxIndex);
        if (foundIndex === undefined)
            return -1;
        while (foundIndex && this._values[foundIndex - 1].startsWith(prefix))
            foundIndex--;
        return foundIndex;
    }, keySet: function () {
        if (!this._keySet)
            this._keySet = this._values.keySet();
        return this._keySet;
    }, next: function (str, prefix) {
        return this._closest(str, prefix, 1);
    }, previous: function (str, prefix) {
        return this._closest(str, prefix, -1);
    }, _closest: function (str, prefix, shift) {
        if (!str)
            return "";
        var index = this._values.indexOf(str);
        if (index === -1)
            return "";
        if (!prefix) {
            index = (index + this._values.length + shift) % this._values.length;
            return this._values[index];
        }
        var propertiesWithPrefix = this.startsWith(prefix);
        var j = propertiesWithPrefix.indexOf(str);
        j = (j + propertiesWithPrefix.length + shift) % propertiesWithPrefix.length;
        return propertiesWithPrefix[j];
    }, longhands: function (shorthand) {
        return this._longhands[shorthand];
    }, shorthands: function (longhand) {
        return this._shorthands[longhand];
    }
}
WebInspector.CSSMetadata.initializeWithSupportedProperties([]);
WebInspector.CSSMetadata.initializeWithSupportedProperties([{"name": "color"}, {"name": "direction"}, {
    "longhands": ["font-family", "font-size", "font-style", "font-variant", "font-weight", "font-stretch", "line-height"],
    "name": "font"
}, {"name": "font-family"}, {"name": "font-kerning"}, {"name": "font-size"}, {"name": "font-stretch"}, {"name": "font-style"}, {"name": "font-variant"}, {"name": "font-variant-ligatures"}, {"name": "font-weight"}, {"name": "-webkit-font-feature-settings"}, {"name": "-webkit-font-smoothing"}, {"name": "-webkit-locale"}, {"name": "-webkit-text-orientation"}, {"name": "-webkit-writing-mode"}, {"name": "text-rendering"}, {"name": "zoom"}, {"name": "line-height"}, {"name": "align-content"}, {"name": "align-items"}, {"name": "alignment-baseline"}, {"name": "align-self"}, {"name": "backface-visibility"}, {"name": "background-attachment"}, {"name": "background-blend-mode"}, {"name": "background-clip"}, {"name": "background-color"}, {"name": "background-image"}, {"name": "background-origin"}, {"name": "background-position-x"}, {"name": "background-position-y"}, {"name": "background-repeat-x"}, {"name": "background-repeat-y"}, {"name": "background-size"}, {"name": "baseline-shift"}, {"name": "border-bottom-color"}, {"name": "border-bottom-left-radius"}, {"name": "border-bottom-right-radius"}, {"name": "border-bottom-style"}, {"name": "border-bottom-width"}, {"name": "border-collapse"}, {"name": "border-image-outset"}, {"name": "border-image-repeat"}, {"name": "border-image-slice"}, {"name": "border-image-source"}, {"name": "border-image-width"}, {"name": "border-left-color"}, {"name": "border-left-style"}, {"name": "border-left-width"}, {"name": "border-right-color"}, {"name": "border-right-style"}, {"name": "border-right-width"}, {"name": "border-top-color"}, {"name": "border-top-left-radius"}, {"name": "border-top-right-radius"}, {"name": "border-top-style"}, {"name": "border-top-width"}, {"name": "bottom"}, {"name": "box-shadow"}, {"name": "box-sizing"}, {"name": "buffered-rendering"}, {"name": "caption-side"}, {"name": "clear"}, {"name": "clip"}, {"name": "clip-path"}, {"name": "clip-rule"}, {"name": "color-interpolation"}, {"name": "color-interpolation-filters"}, {"name": "color-rendering"}, {"name": "column-fill"}, {"name": "content"}, {"name": "counter-increment"}, {"name": "counter-reset"}, {"name": "cursor"}, {"name": "display"}, {"name": "dominant-baseline"}, {"name": "empty-cells"}, {"name": "fill"}, {"name": "fill-opacity"}, {"name": "fill-rule"}, {"name": "filter"}, {"name": "flex-basis"}, {"name": "flex-direction"}, {"name": "flex-grow"}, {"name": "flex-shrink"}, {"name": "flex-wrap"}, {"name": "float"}, {"name": "flood-color"}, {"name": "flood-opacity"}, {"name": "glyph-orientation-horizontal"}, {"name": "glyph-orientation-vertical"}, {"name": "grid-auto-columns"}, {"name": "grid-auto-flow"}, {"name": "grid-auto-rows"}, {"name": "grid-column-end"}, {"name": "grid-column-start"}, {"name": "grid-row-end"}, {"name": "grid-row-start"}, {"name": "grid-template-areas"}, {"name": "grid-template-columns"}, {"name": "grid-template-rows"}, {"name": "height"}, {"name": "image-rendering"}, {"name": "isolation"}, {"name": "justify-content"}, {"name": "justify-items"}, {"name": "justify-self"}, {"name": "left"}, {"name": "letter-spacing"}, {"name": "lighting-color"}, {"name": "list-style-image"}, {"name": "list-style-position"}, {"name": "list-style-type"}, {"name": "margin-bottom"}, {"name": "margin-left"}, {"name": "margin-right"}, {"name": "margin-top"}, {"name": "marker-end"}, {"name": "marker-mid"}, {"name": "marker-start"}, {"name": "mask"}, {"name": "mask-source-type"}, {"name": "mask-type"}, {"name": "max-height"}, {"name": "max-width"}, {"name": "min-height"}, {"name": "min-width"}, {"name": "mix-blend-mode"}, {"name": "object-fit"}, {"name": "object-position"}, {"name": "opacity"}, {"name": "order"}, {"name": "orphans"}, {"name": "outline-color"}, {"name": "outline-offset"}, {"name": "outline-style"}, {"name": "outline-width"}, {"name": "overflow-wrap"}, {"name": "overflow-x"}, {"name": "overflow-y"}, {"name": "padding-bottom"}, {"name": "padding-left"}, {"name": "padding-right"}, {"name": "padding-top"}, {"name": "page-break-after"}, {"name": "page-break-before"}, {"name": "page-break-inside"}, {"name": "paint-order"}, {"name": "perspective"}, {"name": "perspective-origin"}, {"name": "pointer-events"}, {"name": "position"}, {"name": "quotes"}, {"name": "resize"}, {"name": "right"}, {"name": "scroll-behavior"}, {"name": "shape-image-threshold"}, {"name": "shape-margin"}, {"name": "shape-outside"}, {"name": "shape-rendering"}, {"name": "size"}, {"name": "speak"}, {"name": "stop-color"}, {"name": "stop-opacity"}, {"name": "stroke"}, {"name": "stroke-dasharray"}, {"name": "stroke-dashoffset"}, {"name": "stroke-linecap"}, {"name": "stroke-linejoin"}, {"name": "stroke-miterlimit"}, {"name": "stroke-opacity"}, {"name": "stroke-width"}, {"name": "table-layout"}, {"name": "tab-size"}, {"name": "text-align"}, {"name": "text-align-last"}, {"name": "text-anchor"}, {
    "longhands": ["text-decoration-line", "text-decoration-style", "text-decoration-color"],
    "name": "text-decoration"
}, {"name": "text-decoration-color"}, {"name": "text-decoration-line"}, {"name": "text-decoration-style"}, {"name": "text-indent"}, {"name": "text-justify"}, {"name": "text-overflow"}, {"name": "text-shadow"}, {"name": "text-transform"}, {"name": "text-underline-position"}, {"name": "top"}, {"name": "touch-action"}, {"name": "touch-action-delay"}, {"name": "transform"}, {"name": "transform-origin"}, {"name": "transform-style"}, {"name": "unicode-bidi"}, {"name": "vector-effect"}, {"name": "vertical-align"}, {"name": "visibility"}, {"name": "-webkit-animation-delay"}, {"name": "-webkit-animation-direction"}, {"name": "-webkit-animation-duration"}, {"name": "-webkit-animation-fill-mode"}, {"name": "-webkit-animation-iteration-count"}, {"name": "-webkit-animation-name"}, {"name": "-webkit-animation-play-state"}, {"name": "-webkit-animation-timing-function"}, {"name": "-webkit-appearance"}, {"name": "-webkit-app-region"}, {"name": "-webkit-aspect-ratio"}, {"name": "-webkit-backface-visibility"}, {"name": "-webkit-background-clip"}, {"name": "-webkit-background-composite"}, {"name": "-webkit-background-origin"}, {"name": "-webkit-background-size"}, {"name": "-webkit-border-fit"}, {"name": "-webkit-border-horizontal-spacing"}, {"name": "-webkit-border-image"}, {"name": "-webkit-border-vertical-spacing"}, {"name": "-webkit-box-align"}, {"name": "-webkit-box-decoration-break"}, {"name": "-webkit-box-direction"}, {"name": "-webkit-box-flex"}, {"name": "-webkit-box-flex-group"}, {"name": "-webkit-box-lines"}, {"name": "-webkit-box-ordinal-group"}, {"name": "-webkit-box-orient"}, {"name": "-webkit-box-pack"}, {"name": "-webkit-box-reflect"}, {"name": "-webkit-box-shadow"}, {"name": "-webkit-clip-path"}, {"name": "-webkit-column-break-after"}, {"name": "-webkit-column-break-before"}, {"name": "-webkit-column-break-inside"}, {"name": "-webkit-column-count"}, {"name": "-webkit-column-gap"}, {"name": "-webkit-column-rule-color"}, {"name": "-webkit-column-rule-style"}, {"name": "-webkit-column-rule-width"}, {"name": "-webkit-column-span"}, {"name": "-webkit-column-width"}, {"name": "-webkit-filter"}, {"name": "-webkit-highlight"}, {"name": "-webkit-hyphenate-character"}, {"name": "-webkit-line-box-contain"}, {"name": "-webkit-line-break"}, {"name": "-webkit-line-clamp"}, {"name": "-webkit-margin-after-collapse"}, {"name": "-webkit-margin-before-collapse"}, {"name": "-webkit-margin-bottom-collapse"}, {"name": "-webkit-margin-top-collapse"}, {"name": "-webkit-mask-box-image-outset"}, {"name": "-webkit-mask-box-image-repeat"}, {"name": "-webkit-mask-box-image-slice"}, {"name": "-webkit-mask-box-image-source"}, {"name": "-webkit-mask-box-image-width"}, {"name": "-webkit-mask-clip"}, {"name": "-webkit-mask-composite"}, {"name": "-webkit-mask-image"}, {"name": "-webkit-mask-origin"}, {"name": "-webkit-mask-position-x"}, {"name": "-webkit-mask-position-y"}, {"name": "-webkit-mask-repeat-x"}, {"name": "-webkit-mask-repeat-y"}, {"name": "-webkit-mask-size"}, {"name": "-webkit-perspective"}, {"name": "-webkit-perspective-origin"}, {"name": "-webkit-perspective-origin-x"}, {"name": "-webkit-perspective-origin-y"}, {"name": "-webkit-print-color-adjust"}, {"name": "-webkit-rtl-ordering"}, {"name": "-webkit-ruby-position"}, {"name": "-webkit-tap-highlight-color"}, {"name": "-webkit-text-combine"}, {"name": "-webkit-text-emphasis-color"}, {"name": "-webkit-text-emphasis-position"}, {"name": "-webkit-text-emphasis-style"}, {"name": "-webkit-text-fill-color"}, {"name": "-webkit-text-security"}, {"name": "-webkit-text-stroke-color"}, {"name": "-webkit-text-stroke-width"}, {"name": "-webkit-transform"}, {"name": "-webkit-transform-origin-x"}, {"name": "-webkit-transform-origin-y"}, {"name": "-webkit-transform-origin-z"}, {"name": "-webkit-transform-style"}, {"name": "-webkit-transition-delay"}, {"name": "-webkit-transition-duration"}, {"name": "-webkit-transition-property"}, {"name": "-webkit-transition-timing-function"}, {"name": "-webkit-user-drag"}, {"name": "-webkit-user-modify"}, {"name": "-webkit-user-select"}, {"name": "white-space"}, {"name": "widows"}, {"name": "width"}, {"name": "will-change"}, {"name": "word-break"}, {"name": "word-spacing"}, {"name": "word-wrap"}, {"name": "writing-mode"}, {"name": "z-index"}, {"name": "-internal-marquee-direction"}, {"name": "-internal-marquee-increment"}, {"name": "-internal-marquee-repetition"}, {"name": "-internal-marquee-speed"}, {"name": "-internal-marquee-style"}, {"name": "-internal-callback"}, {"name": "-webkit-border-end-color"}, {"name": "-webkit-border-end-style"}, {"name": "-webkit-border-end-width"}, {"name": "-webkit-border-start-color"}, {"name": "-webkit-border-start-style"}, {"name": "-webkit-border-start-width"}, {"name": "-webkit-border-before-color"}, {"name": "-webkit-border-before-style"}, {"name": "-webkit-border-before-width"}, {"name": "-webkit-border-after-color"}, {"name": "-webkit-border-after-style"}, {"name": "-webkit-border-after-width"}, {"name": "-webkit-margin-end"}, {"name": "-webkit-margin-start"}, {"name": "-webkit-margin-before"}, {"name": "-webkit-margin-after"}, {"name": "-webkit-padding-end"}, {"name": "-webkit-padding-start"}, {"name": "-webkit-padding-before"}, {"name": "-webkit-padding-after"}, {"name": "-webkit-logical-width"}, {"name": "-webkit-logical-height"}, {"name": "-webkit-min-logical-width"}, {"name": "-webkit-min-logical-height"}, {"name": "-webkit-max-logical-width"}, {"name": "-webkit-max-logical-height"}, {"name": "all"}, {"name": "animation-delay"}, {"name": "animation-direction"}, {"name": "animation-duration"}, {"name": "animation-fill-mode"}, {"name": "animation-iteration-count"}, {"name": "animation-name"}, {"name": "animation-play-state"}, {"name": "animation-timing-function"}, {"name": "enable-background"}, {"name": "max-zoom"}, {"name": "min-zoom"}, {"name": "orientation"}, {"name": "page"}, {"name": "src"}, {"name": "transition-delay"}, {"name": "transition-duration"}, {"name": "transition-property"}, {"name": "transition-timing-function"}, {"name": "unicode-range"}, {"name": "user-zoom"}, {"name": "-webkit-font-size-delta"}, {"name": "-webkit-text-decorations-in-effect"}, {
    "longhands": ["animation-name", "animation-duration", "animation-timing-function", "animation-delay", "animation-iteration-count", "animation-direction", "animation-fill-mode", "animation-play-state"],
    "name": "animation"
}, {
    "longhands": ["background-image", "background-position-x", "background-position-y", "background-size", "background-repeat-x", "background-repeat-y", "background-attachment", "background-origin", "background-clip", "background-color"],
    "name": "background"
}, {"longhands": ["background-position-x", "background-position-y"], "name": "background-position"}, {
    "longhands": ["background-repeat-x", "background-repeat-y"],
    "name": "background-repeat"
}, {
    "longhands": ["border-top-color", "border-top-style", "border-top-width", "border-right-color", "border-right-style", "border-right-width", "border-bottom-color", "border-bottom-style", "border-bottom-width", "border-left-color", "border-left-style", "border-left-width"],
    "name": "border"
}, {"longhands": ["border-bottom-width", "border-bottom-style", "border-bottom-color"], "name": "border-bottom"}, {
    "longhands": ["border-top-color", "border-right-color", "border-bottom-color", "border-left-color"],
    "name": "border-color"
}, {"longhands": ["border-image-source", "border-image-slice", "border-image-width", "border-image-outset", "border-image-repeat"], "name": "border-image"}, {
    "longhands": ["border-left-width", "border-left-style", "border-left-color"],
    "name": "border-left"
}, {"longhands": ["border-top-left-radius", "border-top-right-radius", "border-bottom-right-radius", "border-bottom-left-radius"], "name": "border-radius"}, {
    "longhands": ["border-right-width", "border-right-style", "border-right-color"],
    "name": "border-right"
}, {"longhands": ["-webkit-border-horizontal-spacing", "-webkit-border-vertical-spacing"], "name": "border-spacing"}, {
    "longhands": ["border-top-style", "border-right-style", "border-bottom-style", "border-left-style"],
    "name": "border-style"
}, {"longhands": ["border-top-width", "border-top-style", "border-top-color"], "name": "border-top"}, {
    "longhands": ["border-top-width", "border-right-width", "border-bottom-width", "border-left-width"],
    "name": "border-width"
}, {"longhands": ["flex-grow", "flex-shrink", "flex-basis"], "name": "flex"}, {"longhands": ["flex-direction", "flex-wrap"], "name": "flex-flow"}, {
    "longhands": ["grid-template", "grid-auto-flow", "grid-auto-columns", "grid-auto-rows"],
    "name": "grid"
}, {"longhands": ["grid-row-start", "grid-column-start", "grid-row-end", "grid-column-end"], "name": "grid-area"}, {
    "longhands": ["grid-column-start", "grid-column-end"],
    "name": "grid-column"
}, {"longhands": ["grid-row-start", "grid-row-end"], "name": "grid-row"}, {
    "longhands": ["grid-template-columns", "grid-template-rows", "grid-template-areas"],
    "name": "grid-template"
}, {"longhands": ["list-style-type", "list-style-position", "list-style-image"], "name": "list-style"}, {
    "longhands": ["margin-top", "margin-right", "margin-bottom", "margin-left"],
    "name": "margin"
}, {"longhands": ["marker-start", "marker-mid", "marker-end"], "name": "marker"}, {"longhands": ["outline-color", "outline-style", "outline-width"], "name": "outline"}, {
    "longhands": ["overflow-x", "overflow-y"],
    "name": "overflow"
}, {"longhands": ["padding-top", "padding-right", "padding-bottom", "padding-left"], "name": "padding"}, {
    "longhands": ["transition-property", "transition-duration", "transition-timing-function", "transition-delay"],
    "name": "transition"
}, {
    "longhands": ["-webkit-animation-name", "-webkit-animation-duration", "-webkit-animation-timing-function", "-webkit-animation-delay", "-webkit-animation-iteration-count", "-webkit-animation-direction", "-webkit-animation-fill-mode", "-webkit-animation-play-state"],
    "name": "-webkit-animation"
}, {
    "longhands": ["-webkit-border-after-width", "-webkit-border-after-style", "-webkit-border-after-color"],
    "name": "-webkit-border-after"
}, {
    "longhands": ["-webkit-border-before-width", "-webkit-border-before-style", "-webkit-border-before-color"],
    "name": "-webkit-border-before"
}, {
    "longhands": ["-webkit-border-end-width", "-webkit-border-end-style", "-webkit-border-end-color"],
    "name": "-webkit-border-end"
}, {
    "longhands": ["border-top-left-radius", "border-top-right-radius", "border-bottom-right-radius", "border-bottom-left-radius"],
    "name": "-webkit-border-radius"
}, {
    "longhands": ["-webkit-border-start-width", "-webkit-border-start-style", "-webkit-border-start-color"],
    "name": "-webkit-border-start"
}, {"longhands": ["-webkit-column-rule-width", "-webkit-column-rule-style", "-webkit-column-rule-color"], "name": "-webkit-column-rule"}, {
    "longhands": ["-webkit-column-width", "-webkit-column-count"],
    "name": "-webkit-columns"
}, {
    "longhands": ["-webkit-margin-before-collapse", "-webkit-margin-after-collapse"],
    "name": "-webkit-margin-collapse"
}, {
    "longhands": ["-webkit-mask-image", "-webkit-mask-position-x", "-webkit-mask-position-y", "-webkit-mask-size", "-webkit-mask-repeat-x", "-webkit-mask-repeat-y", "-webkit-mask-origin", "-webkit-mask-clip"],
    "name": "-webkit-mask"
}, {
    "longhands": ["-webkit-mask-box-image-source", "-webkit-mask-box-image-slice", "-webkit-mask-box-image-width", "-webkit-mask-box-image-outset", "-webkit-mask-box-image-repeat"],
    "name": "-webkit-mask-box-image"
}, {"longhands": ["-webkit-mask-position-x", "-webkit-mask-position-y"], "name": "-webkit-mask-position"}, {
    "longhands": ["-webkit-mask-repeat-x", "-webkit-mask-repeat-y"],
    "name": "-webkit-mask-repeat"
}, {"longhands": ["-webkit-text-emphasis-style", "-webkit-text-emphasis-color"], "name": "-webkit-text-emphasis"}, {
    "longhands": ["-webkit-text-stroke-width", "-webkit-text-stroke-color"],
    "name": "-webkit-text-stroke"
}, {
    "longhands": ["-webkit-transform-origin-x", "-webkit-transform-origin-y", "-webkit-transform-origin-z"],
    "name": "-webkit-transform-origin"
}, {"longhands": ["-webkit-transition-property", "-webkit-transition-duration", "-webkit-transition-timing-function", "-webkit-transition-delay"], "name": "-webkit-transition"}]);
WebInspector.StatusBarItem = function (elementType) {
    this.element = document.createElement(elementType);
    this._enabled = true;
    this._visible = true;
}
WebInspector.StatusBarItem.prototype = {
    setEnabled: function (value) {
        if (this._enabled === value)
            return;
        this._enabled = value;
        this.applyEnabledState();
    }, applyEnabledState: function () {
        this.element.disabled = !this._enabled;
    }, get visible() {
        return this._visible;
    }, set visible(x) {
        if (this._visible === x)
            return;
        this.element.classList.toggle("hidden", !x);
        this._visible = x;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.StatusBarCounter = function (counters, className) {
    WebInspector.StatusBarItem.call(this, "div");
    this.element.className = "status-bar-item status-bar-counter hidden";
    if (className)
        this.element.classList.add(className);
    this.element.addEventListener("click", this._clicked.bind(this), false);
    this._counters = [];
    for (var i = 0; i < counters.length; ++i) {
        var element = this.element.createChild("span", "status-bar-counter-item");
        element.createChild("div", counters[i]);
        element.createChild("span");
        this._counters.push({counter: counters[i], element: element, value: 0, title: ""});
    }
    this._update();
}
WebInspector.StatusBarCounter.prototype = {
    setCounter: function (counter, value, title) {
        for (var i = 0; i < this._counters.length; ++i) {
            if (this._counters[i].counter === counter) {
                this._counters[i].value = value;
                this._counters[i].title = title;
                this._update();
                return;
            }
        }
    }, _update: function () {
        var total = 0;
        var title = "";
        for (var i = 0; i < this._counters.length; ++i) {
            var counter = this._counters[i];
            var value = counter.value;
            if (!counter.value) {
                counter.element.classList.add("hidden");
                continue;
            }
            counter.element.classList.remove("hidden");
            counter.element.classList.toggle("status-bar-counter-item-first", !total);
            counter.element.querySelector("span").textContent = value;
            total += value;
            if (counter.title) {
                if (title)
                    title += ", ";
                title += counter.title;
            }
        }
        this.element.classList.toggle("hidden", !total);
        this.element.title = title;
    }, _clicked: function (event) {
        this.dispatchEventToListeners("click");
    }, __proto__: WebInspector.StatusBarItem.prototype
}
WebInspector.StatusBarText = function (text, className) {
    WebInspector.StatusBarItem.call(this, "span");
    this.element.className = "status-bar-item status-bar-text";
    if (className)
        this.element.classList.add(className);
    this.element.textContent = text;
}
WebInspector.StatusBarText.prototype = {
    setText: function (text) {
        this.element.textContent = text;
    }, __proto__: WebInspector.StatusBarItem.prototype
}
WebInspector.StatusBarInput = function (placeholder, width) {
    WebInspector.StatusBarItem.call(this, "input");
    this.element.className = "status-bar-item";
    this.element.addEventListener("input", this._onChangeCallback.bind(this), false);
    if (width)
        this.element.style.width = width + "px";
    if (placeholder)
        this.element.setAttribute("placeholder", placeholder);
    this._value = "";
}
WebInspector.StatusBarInput.Event = {TextChanged: "TextChanged"};
WebInspector.StatusBarInput.prototype = {
    setValue: function (value) {
        this._value = value;
        this.element.value = value;
    }, value: function () {
        return this.element.value;
    }, _onChangeCallback: function () {
        this.dispatchEventToListeners(WebInspector.StatusBarInput.Event.TextChanged, this.element.value);
    }, __proto__: WebInspector.StatusBarItem.prototype
}
WebInspector.StatusBarButton = function (title, className, states) {
    WebInspector.StatusBarItem.call(this, "button");
    this.element.className = className + " status-bar-item";
    this.element.addEventListener("click", this._clicked.bind(this), false);
    this.glyph = this.element.createChild("div", "glyph");
    this.glyphShadow = this.element.createChild("div", "glyph shadow");
    this.states = states;
    if (!states)
        this.states = 2;
    if (states == 2)
        this._state = false; else
        this._state = 0;
    this.title = title;
    this.className = className;
}
WebInspector.StatusBarButton.prototype = {
    _clicked: function () {
        this.dispatchEventToListeners("click");
        if (this._longClickInterval) {
            clearInterval(this._longClickInterval);
            delete this._longClickInterval;
        }
    }, applyEnabledState: function () {
        this.element.disabled = !this._enabled;
        if (this._longClickInterval) {
            clearInterval(this._longClickInterval);
            delete this._longClickInterval;
        }
    }, enabled: function () {
        return this._enabled;
    }, get title() {
        return this._title;
    }, set title(x) {
        if (this._title === x)
            return;
        this._title = x;
        this.element.title = x;
    }, get state() {
        return this._state;
    }, set state(x) {
        if (this._state === x)
            return;
        if (this.states === 2) {
            this.element.classList.toggle("toggled-on", x);
        } else {
            this.element.classList.remove("toggled-" + this._state);
            if (x !== 0)
                this.element.classList.add("toggled-" + x);
        }
        this._state = x;
    }, get toggled() {
        if (this.states !== 2)
            throw("Only used toggled when there are 2 states, otherwise, use state");
        return this.state;
    }, set toggled(x) {
        if (this.states !== 2)
            throw("Only used toggled when there are 2 states, otherwise, use state");
        this.state = x;
    }, makeLongClickEnabled: function () {
        var boundMouseDown = mouseDown.bind(this);
        var boundMouseUp = mouseUp.bind(this);
        this.element.addEventListener("mousedown", boundMouseDown, false);
        this.element.addEventListener("mouseout", boundMouseUp, false);
        this.element.addEventListener("mouseup", boundMouseUp, false);
        var longClicks = 0;
        this._longClickData = {mouseUp: boundMouseUp, mouseDown: boundMouseDown};
        function mouseDown(e) {
            if (e.which !== 1)
                return;
            longClicks = 0;
            this._longClickInterval = setInterval(longClicked.bind(this), 200);
        }

        function mouseUp(e) {
            if (e.which !== 1)
                return;
            if (this._longClickInterval) {
                clearInterval(this._longClickInterval);
                delete this._longClickInterval;
            }
        }

        function longClicked() {
            ++longClicks;
            this.dispatchEventToListeners(longClicks === 1 ? "longClickDown" : "longClickPress");
        }
    }, unmakeLongClickEnabled: function () {
        if (!this._longClickData)
            return;
        this.element.removeEventListener("mousedown", this._longClickData.mouseDown, false);
        this.element.removeEventListener("mouseout", this._longClickData.mouseUp, false);
        this.element.removeEventListener("mouseup", this._longClickData.mouseUp, false);
        delete this._longClickData;
    }, setLongClickOptionsEnabled: function (buttonsProvider) {
        if (buttonsProvider) {
            if (!this._longClickOptionsData) {
                this.makeLongClickEnabled();
                this.longClickGlyph = this.element.createChild("div", "fill long-click-glyph");
                this.longClickGlyphShadow = this.element.createChild("div", "fill long-click-glyph shadow");
                var longClickDownListener = this._showOptions.bind(this);
                this.addEventListener("longClickDown", longClickDownListener, this);
                this._longClickOptionsData = {glyphElement: this.longClickGlyph, glyphShadowElement: this.longClickGlyphShadow, longClickDownListener: longClickDownListener};
            }
            this._longClickOptionsData.buttonsProvider = buttonsProvider;
        } else {
            if (!this._longClickOptionsData)
                return;
            this.element.removeChild(this._longClickOptionsData.glyphElement);
            this.element.removeChild(this._longClickOptionsData.glyphShadowElement);
            this.removeEventListener("longClickDown", this._longClickOptionsData.longClickDownListener, this);
            delete this._longClickOptionsData;
            this.unmakeLongClickEnabled();
        }
    }, _showOptions: function () {
        var buttons = this._longClickOptionsData.buttonsProvider();
        var mainButtonClone = new WebInspector.StatusBarButton(this.title, this.className, this.states);
        mainButtonClone.addEventListener("click", this._clicked, this);
        mainButtonClone.state = this.state;
        buttons.push(mainButtonClone);
        document.documentElement.addEventListener("mouseup", mouseUp, false);
        var optionsGlassPane = new WebInspector.GlassPane();
        var optionsBarElement = optionsGlassPane.element.createChild("div", "alternate-status-bar-buttons-bar");
        const buttonHeight = 23;
        var hostButtonPosition = this.element.totalOffset();
        var topNotBottom = hostButtonPosition.top + buttonHeight * buttons.length < document.documentElement.offsetHeight;
        if (topNotBottom)
            buttons = buttons.reverse();
        optionsBarElement.style.height = (buttonHeight * buttons.length) + "px";
        if (topNotBottom)
            optionsBarElement.style.top = (hostButtonPosition.top + 1) + "px"; else
            optionsBarElement.style.top = (hostButtonPosition.top - (buttonHeight * (buttons.length - 1))) + "px";
        optionsBarElement.style.left = (hostButtonPosition.left + 1) + "px";
        for (var i = 0; i < buttons.length; ++i) {
            buttons[i].element.addEventListener("mousemove", mouseOver, false);
            buttons[i].element.addEventListener("mouseout", mouseOut, false);
            optionsBarElement.appendChild(buttons[i].element);
        }
        var hostButtonIndex = topNotBottom ? 0 : buttons.length - 1;
        buttons[hostButtonIndex].element.classList.add("emulate-active");
        function mouseOver(e) {
            if (e.which !== 1)
                return;
            var buttonElement = e.target.enclosingNodeOrSelfWithClass("status-bar-item");
            buttonElement.classList.add("emulate-active");
        }

        function mouseOut(e) {
            if (e.which !== 1)
                return;
            var buttonElement = e.target.enclosingNodeOrSelfWithClass("status-bar-item");
            buttonElement.classList.remove("emulate-active");
        }

        function mouseUp(e) {
            if (e.which !== 1)
                return;
            optionsGlassPane.dispose();
            document.documentElement.removeEventListener("mouseup", mouseUp, false);
            for (var i = 0; i < buttons.length; ++i) {
                if (buttons[i].element.classList.contains("emulate-active")) {
                    buttons[i].element.classList.remove("emulate-active");
                    buttons[i]._clicked();
                    break;
                }
            }
        }
    }, __proto__: WebInspector.StatusBarItem.prototype
}
WebInspector.StatusBarItem.Provider = function () {
}
WebInspector.StatusBarItem.Provider.prototype = {
    item: function () {
    }
}
WebInspector.StatusBarComboBox = function (changeHandler, className) {
    WebInspector.StatusBarItem.call(this, "span");
    this.element.className = "status-bar-select-container";
    this._selectElement = this.element.createChild("select", "status-bar-item");
    this.element.createChild("div", "status-bar-select-arrow");
    if (changeHandler)
        this._selectElement.addEventListener("change", changeHandler, false);
    if (className)
        this._selectElement.classList.add(className);
}
WebInspector.StatusBarComboBox.prototype = {
    selectElement: function () {
        return this._selectElement;
    }, size: function () {
        return this._selectElement.childElementCount;
    }, addOption: function (option) {
        this._selectElement.appendChild(option);
    }, createOption: function (label, title, value) {
        var option = this._selectElement.createChild("option");
        option.text = label;
        if (title)
            option.title = title;
        if (typeof value !== "undefined")
            option.value = value;
        return option;
    }, applyEnabledState: function () {
        this._selectElement.disabled = !this._enabled;
    }, removeOption: function (option) {
        this._selectElement.removeChild(option);
    }, removeOptions: function () {
        this._selectElement.removeChildren();
    }, selectedOption: function () {
        if (this._selectElement.selectedIndex >= 0)
            return this._selectElement[this._selectElement.selectedIndex];
        return null;
    }, select: function (option) {
        this._selectElement.selectedIndex = Array.prototype.indexOf.call((this._selectElement), option);
    }, setSelectedIndex: function (index) {
        this._selectElement.selectedIndex = index;
    }, selectedIndex: function () {
        return this._selectElement.selectedIndex;
    }, __proto__: WebInspector.StatusBarItem.prototype
}
WebInspector.StatusBarCheckbox = function (title) {
    WebInspector.StatusBarItem.call(this, "label");
    this.element.classList.add("status-bar-item", "checkbox");
    this.inputElement = this.element.createChild("input");
    this.inputElement.type = "checkbox";
    this.element.createTextChild(title);
}
WebInspector.StatusBarCheckbox.prototype = {
    checked: function () {
        return this.inputElement.checked;
    }, __proto__: WebInspector.StatusBarItem.prototype
}
WebInspector.StatusBarStatesSettingButton = function (className, states, titles, initialState, currentStateSetting, lastStateSetting, stateChangedCallback) {
    WebInspector.StatusBarButton.call(this, "", className, states.length);
    var onClickBound = this._onClick.bind(this);
    this.addEventListener("click", onClickBound, this);
    this._states = states;
    this._buttons = [];
    for (var index = 0; index < states.length; index++) {
        var button = new WebInspector.StatusBarButton(titles[index], className, states.length);
        button.state = this._states[index];
        button.addEventListener("click", onClickBound, this);
        this._buttons.push(button);
    }
    this._currentStateSetting = currentStateSetting;
    this._lastStateSetting = lastStateSetting;
    this._stateChangedCallback = stateChangedCallback;
    this.setLongClickOptionsEnabled(this._createOptions.bind(this));
    this._currentState = null;
    this.toggleState(initialState);
}
WebInspector.StatusBarStatesSettingButton.prototype = {
    _onClick: function (e) {
        this.toggleState(e.target.state);
    }, toggleState: function (state) {
        if (this._currentState === state)
            return;
        if (this._currentState)
            this._lastStateSetting.set(this._currentState);
        this._currentState = state;
        this._currentStateSetting.set(this._currentState);
        if (this._stateChangedCallback)
            this._stateChangedCallback(state);
        var defaultState = this._defaultState();
        this.state = defaultState;
        this.title = this._buttons[this._states.indexOf(defaultState)].title;
    }, _defaultState: function () {
        var lastState = this._lastStateSetting.get();
        if (lastState && this._states.indexOf(lastState) >= 0 && lastState != this._currentState)
            return lastState;
        if (this._states.length > 1 && this._currentState === this._states[0])
            return this._states[1];
        return this._states[0];
    }, _createOptions: function () {
        var options = [];
        for (var index = 0; index < this._states.length; index++) {
            if (this._states[index] !== this.state && this._states[index] !== this._currentState)
                options.push(this._buttons[index]);
        }
        return options;
    }, __proto__: WebInspector.StatusBarButton.prototype
}
WebInspector.DropDownMenu = function () {
    this.element = document.createElementWithClass("select", "drop-down-menu");
    this.element.addEventListener("mousedown", this._onBeforeMouseDown.bind(this), true);
    this.element.addEventListener("mousedown", consumeEvent, false);
    this.element.addEventListener("change", this._onChange.bind(this), false);
}
WebInspector.DropDownMenu.Events = {BeforeShow: "BeforeShow", ItemSelected: "ItemSelected"}
WebInspector.DropDownMenu.prototype = {
    _onBeforeMouseDown: function () {
        this.dispatchEventToListeners(WebInspector.DropDownMenu.Events.BeforeShow, null);
    }, _onChange: function () {
        var options = this.element.options;
        var selectedOption = options[this.element.selectedIndex];
        this.dispatchEventToListeners(WebInspector.DropDownMenu.Events.ItemSelected, selectedOption.id);
    }, addItem: function (id, title) {
        var option = new Option(title);
        option.id = id;
        this.element.appendChild(option);
    }, selectItem: function (id) {
        var children = this.element.children;
        for (var i = 0; i < children.length; ++i) {
            var child = children[i];
            if (child.id === id) {
                this.element.selectedIndex = i;
                return;
            }
        }
        this.element.selectedIndex = -1;
    }, clear: function () {
        this.element.removeChildren();
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.InplaceEditor = function () {
};
WebInspector.InplaceEditor.startEditing = function (element, config) {
    if (config.multiline)
        return self.runtime.instance(WebInspector.InplaceEditor).startEditing(element, config);
    if (!WebInspector.InplaceEditor._defaultInstance)
        WebInspector.InplaceEditor._defaultInstance = new WebInspector.InplaceEditor();
    return WebInspector.InplaceEditor._defaultInstance.startEditing(element, config);
}
WebInspector.InplaceEditor.prototype = {
    editorContent: function (editingContext) {
        var element = editingContext.element;
        if (element.tagName === "INPUT" && element.type === "text")
            return element.value;
        return element.textContent;
    }, setUpEditor: function (editingContext) {
        var element = editingContext.element;
        element.classList.add("editing");
        var oldTabIndex = element.getAttribute("tabIndex");
        if (typeof oldTabIndex !== "number" || oldTabIndex < 0)
            element.tabIndex = 0;
        WebInspector.setCurrentFocusElement(element);
        editingContext.oldTabIndex = oldTabIndex;
    }, closeEditor: function (editingContext) {
        var element = editingContext.element;
        element.classList.remove("editing");
        if (typeof editingContext.oldTabIndex !== "number")
            element.removeAttribute("tabIndex"); else
            element.tabIndex = editingContext.oldTabIndex;
        element.scrollTop = 0;
        element.scrollLeft = 0;
    }, cancelEditing: function (editingContext) {
        var element = editingContext.element;
        if (element.tagName === "INPUT" && element.type === "text")
            element.value = editingContext.oldText; else
            element.textContent = editingContext.oldText;
    }, augmentEditingHandle: function (editingContext, handle) {
    }, startEditing: function (element, config) {
        if (!WebInspector.markBeingEdited(element, true))
            return null;
        config = config || new WebInspector.InplaceEditor.Config(function () {
        }, function () {
        });
        var editingContext = {element: element, config: config};
        var committedCallback = config.commitHandler;
        var cancelledCallback = config.cancelHandler;
        var pasteCallback = config.pasteHandler;
        var context = config.context;
        var isMultiline = config.multiline || false;
        var moveDirection = "";
        var self = this;

        function consumeCopy(e) {
            e.consume();
        }

        this.setUpEditor(editingContext);
        editingContext.oldText = isMultiline ? config.initialValue : this.editorContent(editingContext);
        function blurEventListener(e) {
            if (!isMultiline || !e || !e.relatedTarget || !e.relatedTarget.isSelfOrDescendant(element))
                editingCommitted.call(element);
        }

        function cleanUpAfterEditing() {
            WebInspector.markBeingEdited(element, false);
            element.removeEventListener("blur", blurEventListener, isMultiline);
            element.removeEventListener("keydown", keyDownEventListener, true);
            if (pasteCallback)
                element.removeEventListener("paste", pasteEventListener, true);
            WebInspector.restoreFocusFromElement(element);
            self.closeEditor(editingContext);
        }

        function editingCancelled() {
            self.cancelEditing(editingContext);
            cleanUpAfterEditing();
            cancelledCallback(this, context);
        }

        function editingCommitted() {
            cleanUpAfterEditing();
            committedCallback(this, self.editorContent(editingContext), editingContext.oldText, context, moveDirection);
        }

        function defaultFinishHandler(event) {
            var isMetaOrCtrl = WebInspector.isMac() ? event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey : event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
            if (isEnterKey(event) && (event.isMetaOrCtrlForTest || !isMultiline || isMetaOrCtrl))
                return "commit"; else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code || event.keyIdentifier === "U+001B")
                return "cancel"; else if (!isMultiline && event.keyIdentifier === "U+0009")
                return "move-" + (event.shiftKey ? "backward" : "forward");
        }

        function handleEditingResult(result, event) {
            if (result === "commit") {
                editingCommitted.call(element);
                event.consume(true);
            } else if (result === "cancel") {
                editingCancelled.call(element);
                event.consume(true);
            } else if (result && result.startsWith("move-")) {
                moveDirection = result.substring(5);
                if (event.keyIdentifier !== "U+0009")
                    blurEventListener();
            }
        }

        function pasteEventListener(event) {
            var result = pasteCallback(event);
            handleEditingResult(result, event);
        }

        function keyDownEventListener(event) {
            var handler = config.customFinishHandler || defaultFinishHandler;
            var result = handler(event);
            handleEditingResult(result, event);
        }

        element.addEventListener("blur", blurEventListener, isMultiline);
        element.addEventListener("keydown", keyDownEventListener, true);
        if (pasteCallback)
            element.addEventListener("paste", pasteEventListener, true);
        var handle = {cancel: editingCancelled.bind(element), commit: editingCommitted.bind(element)};
        this.augmentEditingHandle(editingContext, handle);
        return handle;
    }
}
WebInspector.InplaceEditor.Config = function (commitHandler, cancelHandler, context) {
    this.commitHandler = commitHandler;
    this.cancelHandler = cancelHandler
    this.context = context;
    this.pasteHandler;
    this.multiline;
    this.customFinishHandler;
}
WebInspector.InplaceEditor.Config.prototype = {
    setPasteHandler: function (pasteHandler) {
        this.pasteHandler = pasteHandler;
    }, setMultilineOptions: function (initialValue, mode, theme, lineWrapping, smartIndent) {
        this.multiline = true;
        this.initialValue = initialValue;
        this.mode = mode;
        this.theme = theme;
        this.lineWrapping = lineWrapping;
        this.smartIndent = smartIndent;
    }, setCustomFinishHandler: function (customFinishHandler) {
        this.customFinishHandler = customFinishHandler;
    }
}
WebInspector.TextEditor = function () {
};
WebInspector.TextEditor.Events = {GutterClick: "gutterClick"};
WebInspector.TextEditor.GutterClickEventData;
WebInspector.TextEditor.prototype = {
    undo: function () {
    }, redo: function () {
    }, isClean: function () {
    }, markClean: function () {
    }, indent: function () {
    }, cursorPositionToCoordinates: function (lineNumber, column) {
        return null;
    }, coordinatesToCursorPosition: function (x, y) {
        return null;
    }, tokenAtTextPosition: function (lineNumber, column) {
        return null;
    }, setMimeType: function (mimeType) {
    }, setReadOnly: function (readOnly) {
    }, readOnly: function () {
    }, defaultFocusedElement: function () {
    }, highlightRange: function (range, cssClass) {
    }, removeHighlight: function (highlightDescriptor) {
    }, addBreakpoint: function (lineNumber, disabled, conditional) {
    }, removeBreakpoint: function (lineNumber) {
    }, setExecutionLine: function (lineNumber) {
    }, clearExecutionLine: function () {
    }, toggleLineClass: function (lineNumber, className, toggled) {
    }, addDecoration: function (lineNumber, element) {
    }, removeDecoration: function (lineNumber, element) {
    }, highlightSearchResults: function (regex, range) {
    }, revealPosition: function (lineNumber, columnNumber, shouldHighlight) {
    }, clearPositionHighlight: function () {
    }, elementsToRestoreScrollPositionsFor: function () {
    }, inheritScrollPositions: function (textEditor) {
    }, beginUpdates: function () {
    }, endUpdates: function () {
    }, onResize: function () {
    }, editRange: function (range, text) {
    }, scrollToLine: function (lineNumber) {
    }, firstVisibleLine: function () {
    }, lastVisibleLine: function () {
    }, selection: function () {
    }, selections: function () {
    }, lastSelection: function () {
    }, setSelection: function (textRange) {
    }, copyRange: function (range) {
    }, setText: function (text) {
    }, text: function () {
    }, range: function () {
    }, line: function (lineNumber) {
    }, get linesCount() {
    }, setAttribute: function (line, name, value) {
    }, getAttribute: function (line, name) {
    }, removeAttribute: function (line, name) {
    }, wasShown: function () {
    }, willHide: function () {
    }, setCompletionDictionary: function (dictionary) {
    }, textEditorPositionHandle: function (lineNumber, columnNumber) {
    }, dispose: function () {
    }
}
WebInspector.TextEditorPositionHandle = function () {
}
WebInspector.TextEditorPositionHandle.prototype = {
    resolve: function () {
    }, equal: function (positionHandle) {
    }
}
WebInspector.TextEditorDelegate = function () {
}
WebInspector.TextEditorDelegate.prototype = {
    onTextChanged: function (oldRange, newRange) {
    }, selectionChanged: function (textRange) {
    }, scrollChanged: function (lineNumber) {
    }, editorFocused: function () {
    }, populateLineGutterContextMenu: function (contextMenu, lineNumber) {
    }, populateTextAreaContextMenu: function (contextMenu, lineNumber) {
    }, createLink: function (hrefValue, isExternal) {
    }, onJumpToPosition: function (from, to) {
    }
}
WebInspector.TokenizerFactory = function () {
}
WebInspector.TokenizerFactory.prototype = {
    createTokenizer: function (mimeType) {
    }
}
WebInspector.SplitView = function (isVertical, secondIsSidebar, settingName, defaultSidebarWidth, defaultSidebarHeight, constraintsInDip) {
    WebInspector.View.call(this);
    this.element.classList.add("split-view");
    this._mainView = new WebInspector.VBox();
    this._mainElement = this._mainView.element;
    this._mainElement.className = "split-view-contents split-view-main vbox";
    this._sidebarView = new WebInspector.VBox();
    this._sidebarElement = this._sidebarView.element;
    this._sidebarElement.className = "split-view-contents split-view-sidebar vbox";
    this._resizerElement = this.element.createChild("div", "split-view-resizer");
    this._resizerElement.createChild("div", "split-view-resizer-border");
    if (secondIsSidebar) {
        this._mainView.show(this.element);
        this._sidebarView.show(this.element);
    } else {
        this._sidebarView.show(this.element);
        this._mainView.show(this.element);
    }
    this._resizerWidget = new WebInspector.ResizerWidget();
    this._resizerWidget.setEnabled(true);
    this._resizerWidget.addEventListener(WebInspector.ResizerWidget.Events.ResizeStart, this._onResizeStart, this);
    this._resizerWidget.addEventListener(WebInspector.ResizerWidget.Events.ResizeUpdate, this._onResizeUpdate, this);
    this._resizerWidget.addEventListener(WebInspector.ResizerWidget.Events.ResizeEnd, this._onResizeEnd, this);
    this._defaultSidebarWidth = defaultSidebarWidth || 200;
    this._defaultSidebarHeight = defaultSidebarHeight || this._defaultSidebarWidth;
    this._constraintsInDip = !!constraintsInDip;
    this._settingName = settingName;
    this.setSecondIsSidebar(secondIsSidebar);
    this._innerSetVertical(isVertical);
    this._showMode = WebInspector.SplitView.ShowMode.Both;
    this.installResizer(this._resizerElement);
}
WebInspector.SplitView.SettingForOrientation;
WebInspector.SplitView.ShowMode = {Both: "Both", OnlyMain: "OnlyMain", OnlySidebar: "OnlySidebar"}
WebInspector.SplitView.Events = {SidebarSizeChanged: "SidebarSizeChanged", ShowModeChanged: "ShowModeChanged"}
WebInspector.SplitView.MinPadding = 20;
WebInspector.SplitView.prototype = {
    isVertical: function () {
        return this._isVertical;
    }, setVertical: function (isVertical) {
        if (this._isVertical === isVertical)
            return;
        this._innerSetVertical(isVertical);
        if (this.isShowing())
            this._updateLayout();
    }, _innerSetVertical: function (isVertical) {
        this.element.classList.remove(this._isVertical ? "hbox" : "vbox");
        this._isVertical = isVertical;
        this.element.classList.add(this._isVertical ? "hbox" : "vbox");
        delete this._resizerElementSize;
        this._sidebarSize = -1;
        this._restoreSidebarSizeFromSettings();
        if (this._shouldSaveShowMode)
            this._restoreAndApplyShowModeFromSettings();
        this._updateShowHideSidebarButton();
        this._resizerWidget.setVertical(!isVertical);
        this.invalidateConstraints();
    }, _updateLayout: function (animate) {
        delete this._totalSize;
        delete this._totalSizeOtherDimension;
        this._mainElement.style.removeProperty("width");
        this._mainElement.style.removeProperty("height");
        this._sidebarElement.style.removeProperty("width");
        this._sidebarElement.style.removeProperty("height");
        this._innerSetSidebarSize(this._preferredSidebarSize(), !!animate);
    }, mainElement: function () {
        return this._mainElement;
    }, sidebarElement: function () {
        return this._sidebarElement;
    }, isSidebarSecond: function () {
        return this._secondIsSidebar;
    }, enableShowModeSaving: function () {
        this._shouldSaveShowMode = true;
        this._restoreAndApplyShowModeFromSettings();
    }, showMode: function () {
        return this._showMode;
    }, setSecondIsSidebar: function (secondIsSidebar) {
        this._mainElement.classList.toggle("split-view-contents-first", secondIsSidebar);
        this._mainElement.classList.toggle("split-view-contents-second", !secondIsSidebar);
        this._sidebarElement.classList.toggle("split-view-contents-first", !secondIsSidebar);
        this._sidebarElement.classList.toggle("split-view-contents-second", secondIsSidebar);
        if (secondIsSidebar) {
            if (this._sidebarElement.parentElement && this._sidebarElement.nextSibling)
                this.element.appendChild(this._sidebarElement);
        } else {
            if (this._mainElement.parentElement && this._mainElement.nextSibling)
                this.element.appendChild(this._mainElement);
        }
        this._secondIsSidebar = secondIsSidebar;
    }, sidebarSide: function () {
        if (this._showMode !== WebInspector.SplitView.ShowMode.Both)
            return null;
        return this._isVertical ? (this._secondIsSidebar ? "right" : "left") : (this._secondIsSidebar ? "bottom" : "top");
    }, preferredSidebarSize: function () {
        return this._preferredSidebarSize();
    }, resizerElement: function () {
        return this._resizerElement;
    }, hideMain: function (animate) {
        this._showOnly(this._sidebarView, this._mainView, animate);
        this._updateShowMode(WebInspector.SplitView.ShowMode.OnlySidebar);
    }, hideSidebar: function (animate) {
        this._showOnly(this._mainView, this._sidebarView, animate);
        this._updateShowMode(WebInspector.SplitView.ShowMode.OnlyMain);
    }, detachChildViews: function () {
        this._mainView.detachChildViews();
        this._sidebarView.detachChildViews();
    }, _showOnly: function (sideToShow, sideToHide, animate) {
        this._cancelAnimation();
        function callback() {
            sideToShow.show(this.element);
            sideToHide.detach();
            sideToShow.element.classList.add("maximized");
            sideToHide.element.classList.remove("maximized");
            this._resizerElement.classList.add("hidden");
            this._removeAllLayoutProperties();
        }

        if (animate) {
            this._animate(true, callback.bind(this));
        } else {
            callback.call(this);
            this.doResize();
        }
        this._sidebarSize = -1;
        this.setResizable(false);
    }, _removeAllLayoutProperties: function () {
        this._sidebarElement.style.removeProperty("flexBasis");
        this._mainElement.style.removeProperty("width");
        this._mainElement.style.removeProperty("height");
        this._sidebarElement.style.removeProperty("width");
        this._sidebarElement.style.removeProperty("height");
        this._resizerElement.style.removeProperty("left");
        this._resizerElement.style.removeProperty("right");
        this._resizerElement.style.removeProperty("top");
        this._resizerElement.style.removeProperty("bottom");
        this._resizerElement.style.removeProperty("margin-left");
        this._resizerElement.style.removeProperty("margin-right");
        this._resizerElement.style.removeProperty("margin-top");
        this._resizerElement.style.removeProperty("margin-bottom");
    }, showBoth: function (animate) {
        if (this._showMode === WebInspector.SplitView.ShowMode.Both)
            animate = false;
        this._cancelAnimation();
        this._mainElement.classList.remove("maximized");
        this._sidebarElement.classList.remove("maximized");
        this._resizerElement.classList.remove("hidden");
        this._mainView.show(this.element);
        this._sidebarView.show(this.element);
        this.setSecondIsSidebar(this._secondIsSidebar);
        this._sidebarSize = -1;
        this.setResizable(true);
        this._updateShowMode(WebInspector.SplitView.ShowMode.Both);
        this._updateLayout(animate);
    }, setResizable: function (resizable) {
        this._resizerWidget.setEnabled(resizable);
    }, isResizable: function () {
        return this._resizerWidget.isEnabled();
    }, setSidebarSize: function (size) {
        size *= WebInspector.zoomManager.zoomFactor();
        this._savedSidebarSize = size;
        this._saveSetting();
        this._innerSetSidebarSize(size, false, true);
    }, sidebarSize: function () {
        var size = Math.max(0, this._sidebarSize);
        return size / WebInspector.zoomManager.zoomFactor();
    }, _totalSizeDIP: function () {
        if (!this._totalSize) {
            this._totalSize = this._isVertical ? this.element.offsetWidth : this.element.offsetHeight;
            this._totalSizeOtherDimension = this._isVertical ? this.element.offsetHeight : this.element.offsetWidth;
        }
        return this._totalSize * WebInspector.zoomManager.zoomFactor();
    }, _updateShowMode: function (showMode) {
        this._showMode = showMode;
        this._saveShowModeToSettings();
        this._updateShowHideSidebarButton();
        this.dispatchEventToListeners(WebInspector.SplitView.Events.ShowModeChanged, showMode);
        this.invalidateConstraints();
    }, _innerSetSidebarSize: function (size, animate, userAction) {
        if (this._showMode !== WebInspector.SplitView.ShowMode.Both || !this.isShowing())
            return;
        size = this._applyConstraints(size, userAction);
        if (this._sidebarSize === size)
            return;
        if (!this._resizerElementSize)
            this._resizerElementSize = this._isVertical ? this._resizerElement.offsetWidth : this._resizerElement.offsetHeight;
        this._removeAllLayoutProperties();
        var sidebarSizeValue = (size / WebInspector.zoomManager.zoomFactor()) + "px";
        var mainSizeValue = (this._totalSize - size / WebInspector.zoomManager.zoomFactor()) + "px";
        this.sidebarElement().style.flexBasis = sidebarSizeValue;
        if (this._isVertical) {
            this._sidebarElement.style.width = sidebarSizeValue;
            this._mainElement.style.width = mainSizeValue;
            this._sidebarElement.style.height = this._totalSizeOtherDimension + "px";
            this._mainElement.style.height = this._totalSizeOtherDimension + "px";
        } else {
            this._sidebarElement.style.height = sidebarSizeValue;
            this._mainElement.style.height = mainSizeValue;
            this._sidebarElement.style.width = this._totalSizeOtherDimension + "px";
            this._mainElement.style.width = this._totalSizeOtherDimension + "px";
        }
        if (this._isVertical) {
            if (this._secondIsSidebar) {
                this._resizerElement.style.right = sidebarSizeValue;
                this._resizerElement.style.marginRight = -this._resizerElementSize / 2 + "px";
            } else {
                this._resizerElement.style.left = sidebarSizeValue;
                this._resizerElement.style.marginLeft = -this._resizerElementSize / 2 + "px";
            }
        } else {
            if (this._secondIsSidebar) {
                this._resizerElement.style.bottom = sidebarSizeValue;
                this._resizerElement.style.marginBottom = -this._resizerElementSize / 2 + "px";
            } else {
                this._resizerElement.style.top = sidebarSizeValue;
                this._resizerElement.style.marginTop = -this._resizerElementSize / 2 + "px";
            }
        }
        this._sidebarSize = size;
        if (animate) {
            this._animate(false);
        } else {
            this.doResize();
            this.dispatchEventToListeners(WebInspector.SplitView.Events.SidebarSizeChanged, this.sidebarSize());
        }
    }, _animate: function (reverse, callback) {
        var animationTime = 50;
        this._animationCallback = callback;
        var animatedMarginPropertyName;
        if (this._isVertical)
            animatedMarginPropertyName = this._secondIsSidebar ? "margin-right" : "margin-left"; else
            animatedMarginPropertyName = this._secondIsSidebar ? "margin-bottom" : "margin-top";
        var zoomFactor = WebInspector.zoomManager.zoomFactor();
        var marginFrom = reverse ? "0" : "-" + (this._sidebarSize / zoomFactor) + "px";
        var marginTo = reverse ? "-" + (this._sidebarSize / zoomFactor) + "px" : "0";
        this.element.style.setProperty(animatedMarginPropertyName, marginFrom);
        if (!reverse) {
            suppressUnused(this._mainElement.offsetWidth);
            suppressUnused(this._sidebarElement.offsetWidth);
        }
        if (!reverse)
            this._sidebarView.doResize();
        this.element.style.setProperty("transition", animatedMarginPropertyName + " " + animationTime + "ms linear");
        var boundAnimationFrame;
        var startTime;

        function animationFrame() {
            delete this._animationFrameHandle;
            if (!startTime) {
                this.element.style.setProperty(animatedMarginPropertyName, marginTo);
                startTime = window.performance.now();
            } else if (window.performance.now() < startTime + animationTime) {
                this._mainView.doResize();
            } else {
                this._cancelAnimation();
                this._mainView.doResize();
                this.dispatchEventToListeners(WebInspector.SplitView.Events.SidebarSizeChanged, this.sidebarSize());
                return;
            }
            this._animationFrameHandle = window.requestAnimationFrame(boundAnimationFrame);
        }

        boundAnimationFrame = animationFrame.bind(this);
        this._animationFrameHandle = window.requestAnimationFrame(boundAnimationFrame);
    }, _cancelAnimation: function () {
        this.element.style.removeProperty("margin-top");
        this.element.style.removeProperty("margin-right");
        this.element.style.removeProperty("margin-bottom");
        this.element.style.removeProperty("margin-left");
        this.element.style.removeProperty("transition");
        if (this._animationFrameHandle) {
            window.cancelAnimationFrame(this._animationFrameHandle);
            delete this._animationFrameHandle;
        }
        if (this._animationCallback) {
            this._animationCallback();
            delete this._animationCallback;
        }
    }, _applyConstraints: function (sidebarSize, userAction) {
        var totalSize = this._totalSizeDIP();
        var zoomFactor = this._constraintsInDip ? 1 : WebInspector.zoomManager.zoomFactor();
        var constraints = this._sidebarView.constraints();
        var minSidebarSize = this.isVertical() ? constraints.minimum.width : constraints.minimum.height;
        if (!minSidebarSize)
            minSidebarSize = WebInspector.SplitView.MinPadding;
        minSidebarSize *= zoomFactor;
        var preferredSidebarSize = this.isVertical() ? constraints.preferred.width : constraints.preferred.height;
        if (!preferredSidebarSize)
            preferredSidebarSize = WebInspector.SplitView.MinPadding;
        preferredSidebarSize *= zoomFactor;
        if (sidebarSize < preferredSidebarSize)
            preferredSidebarSize = Math.max(sidebarSize, minSidebarSize);
        constraints = this._mainView.constraints();
        var minMainSize = this.isVertical() ? constraints.minimum.width : constraints.minimum.height;
        if (!minMainSize)
            minMainSize = WebInspector.SplitView.MinPadding;
        minMainSize *= zoomFactor;
        var preferredMainSize = this.isVertical() ? constraints.preferred.width : constraints.preferred.height;
        if (!preferredMainSize)
            preferredMainSize = WebInspector.SplitView.MinPadding;
        preferredMainSize *= zoomFactor;
        var savedMainSize = this.isVertical() ? this._savedVerticalMainSize : this._savedHorizontalMainSize;
        if (typeof savedMainSize !== "undefined")
            preferredMainSize = Math.min(preferredMainSize, savedMainSize * zoomFactor);
        if (userAction)
            preferredMainSize = minMainSize;
        var totalPreferred = preferredMainSize + preferredSidebarSize;
        if (totalPreferred <= totalSize)
            return Number.constrain(sidebarSize, preferredSidebarSize, totalSize - preferredMainSize);
        if (minMainSize + minSidebarSize <= totalSize) {
            var delta = totalPreferred - totalSize;
            var sidebarDelta = delta * preferredSidebarSize / totalPreferred;
            sidebarSize = preferredSidebarSize - sidebarDelta;
            return Number.constrain(sidebarSize, minSidebarSize, totalSize - minMainSize);
        }
        return Math.max(0, totalSize - minMainSize);
    }, wasShown: function () {
        this._forceUpdateLayout();
        WebInspector.zoomManager.addEventListener(WebInspector.ZoomManager.Events.ZoomChanged, this._onZoomChanged, this);
    }, willHide: function () {
        WebInspector.zoomManager.removeEventListener(WebInspector.ZoomManager.Events.ZoomChanged, this._onZoomChanged, this);
    }, onResize: function () {
        this._updateLayout();
    }, onLayout: function () {
        this._updateLayout();
    }, calculateConstraints: function () {
        if (this._showMode === WebInspector.SplitView.ShowMode.OnlyMain)
            return this._mainView.constraints();
        if (this._showMode === WebInspector.SplitView.ShowMode.OnlySidebar)
            return this._sidebarView.constraints();
        var mainConstraints = this._mainView.constraints();
        var sidebarConstraints = this._sidebarView.constraints();
        var min = WebInspector.SplitView.MinPadding;
        if (this._isVertical) {
            mainConstraints = mainConstraints.widthToMax(min);
            sidebarConstraints = sidebarConstraints.widthToMax(min);
            return mainConstraints.addWidth(sidebarConstraints).heightToMax(sidebarConstraints);
        } else {
            mainConstraints = mainConstraints.heightToMax(min);
            sidebarConstraints = sidebarConstraints.heightToMax(min);
            return mainConstraints.widthToMax(sidebarConstraints).addHeight(sidebarConstraints);
        }
    }, _onResizeStart: function (event) {
        this._resizeStartSize = this._sidebarSize;
    }, _onResizeUpdate: function (event) {
        var cssOffset = event.data.currentPosition - event.data.startPosition;
        var dipOffset = cssOffset * WebInspector.zoomManager.zoomFactor();
        var newSize = this._secondIsSidebar ? this._resizeStartSize - dipOffset : this._resizeStartSize + dipOffset;
        var constrainedSize = this._applyConstraints(newSize, true);
        this._savedSidebarSize = constrainedSize;
        this._saveSetting();
        this._innerSetSidebarSize(constrainedSize, false, true);
        if (this.isVertical())
            this._savedVerticalMainSize = this._totalSizeDIP() - this._sidebarSize; else
            this._savedHorizontalMainSize = this._totalSizeDIP() - this._sidebarSize;
    }, _onResizeEnd: function (event) {
        delete this._resizeStartSize;
    }, hideDefaultResizer: function () {
        this.uninstallResizer(this._resizerElement);
    }, installResizer: function (resizerElement) {
        this._resizerWidget.addElement(resizerElement);
    }, uninstallResizer: function (resizerElement) {
        this._resizerWidget.removeElement(resizerElement);
    }, hasCustomResizer: function () {
        var elements = this._resizerWidget.elements();
        return elements.length > 1 || (elements.length == 1 && elements[0] !== this._resizerElement);
    }, toggleResizer: function (resizer, on) {
        if (on)
            this.installResizer(resizer); else
            this.uninstallResizer(resizer);
    }, _setting: function () {
        if (!this._settingName)
            return null;
        if (!WebInspector.settings[this._settingName])
            WebInspector.settings[this._settingName] = WebInspector.settings.createSetting(this._settingName, {});
        return WebInspector.settings[this._settingName];
    }, _settingForOrientation: function () {
        var state = this._setting() ? this._setting().get() : {};
        return this._isVertical ? state.vertical : state.horizontal;
    }, _preferredSidebarSize: function () {
        var size = this._savedSidebarSize;
        if (!size) {
            size = this._isVertical ? this._defaultSidebarWidth : this._defaultSidebarHeight;
            if (0 < size && size < 1)
                size *= this._totalSizeDIP();
        }
        return size;
    }, _restoreSidebarSizeFromSettings: function () {
        var settingForOrientation = this._settingForOrientation();
        this._savedSidebarSize = settingForOrientation ? settingForOrientation.size : 0;
    }, _restoreAndApplyShowModeFromSettings: function () {
        var orientationState = this._settingForOrientation();
        this._savedShowMode = orientationState ? orientationState.showMode : WebInspector.SplitView.ShowMode.Both;
        this._showMode = this._savedShowMode;
        switch (this._savedShowMode) {
            case WebInspector.SplitView.ShowMode.Both:
                this.showBoth();
                break;
            case WebInspector.SplitView.ShowMode.OnlyMain:
                this.hideSidebar();
                break;
            case WebInspector.SplitView.ShowMode.OnlySidebar:
                this.hideMain();
                break;
        }
    }, _saveShowModeToSettings: function () {
        this._savedShowMode = this._showMode;
        this._saveSetting();
    }, _saveSetting: function () {
        var setting = this._setting();
        if (!setting)
            return;
        var state = setting.get();
        var orientationState = (this._isVertical ? state.vertical : state.horizontal) || {};
        orientationState.size = this._savedSidebarSize;
        if (this._shouldSaveShowMode)
            orientationState.showMode = this._savedShowMode;
        if (this._isVertical)
            state.vertical = orientationState; else
            state.horizontal = orientationState;
        setting.set(state);
    }, _forceUpdateLayout: function () {
        this._sidebarSize = -1;
        this._updateLayout();
    }, _onZoomChanged: function (event) {
        this._forceUpdateLayout();
    }, createShowHideSidebarButton: function (title, className) {
        console.assert(this.isVertical(), "Buttons for split view with horizontal split are not supported yet.");
        this._showHideSidebarButtonTitle = WebInspector.UIString(title);
        this._showHideSidebarButton = new WebInspector.StatusBarButton("", "sidebar-show-hide-button " + className, 3);
        this._showHideSidebarButton.addEventListener("click", buttonClicked.bind(this));
        this._updateShowHideSidebarButton();
        function buttonClicked(event) {
            if (this._showMode !== WebInspector.SplitView.ShowMode.Both)
                this.showBoth(true); else
                this.hideSidebar(true);
        }

        return this._showHideSidebarButton;
    }, _updateShowHideSidebarButton: function () {
        if (!this._showHideSidebarButton)
            return;
        var sidebarHidden = this._showMode === WebInspector.SplitView.ShowMode.OnlyMain;
        this._showHideSidebarButton.state = sidebarHidden ? "show" : "hide";
        this._showHideSidebarButton.element.classList.toggle("top-sidebar-show-hide-button", !this.isVertical() && !this.isSidebarSecond());
        this._showHideSidebarButton.element.classList.toggle("right-sidebar-show-hide-button", this.isVertical() && this.isSidebarSecond());
        this._showHideSidebarButton.element.classList.toggle("bottom-sidebar-show-hide-button", !this.isVertical() && this.isSidebarSecond());
        this._showHideSidebarButton.element.classList.toggle("left-sidebar-show-hide-button", this.isVertical() && !this.isSidebarSecond());
        this._showHideSidebarButton.title = sidebarHidden ? WebInspector.UIString("Show %s", this._showHideSidebarButtonTitle) : WebInspector.UIString("Hide %s", this._showHideSidebarButtonTitle);
    }, __proto__: WebInspector.View.prototype
}
WebInspector.StackView = function (isVertical) {
    WebInspector.VBox.call(this);
    this._isVertical = isVertical;
    this._currentSplitView = null;
}
WebInspector.StackView.prototype = {
    appendView: function (view, sidebarSizeSettingName, defaultSidebarWidth, defaultSidebarHeight) {
        var splitView = new WebInspector.SplitView(this._isVertical, true, sidebarSizeSettingName, defaultSidebarWidth, defaultSidebarHeight);
        view.show(splitView.mainElement());
        splitView.hideSidebar();
        if (!this._currentSplitView) {
            splitView.show(this.element);
        } else {
            splitView.show(this._currentSplitView.sidebarElement());
            this._currentSplitView.showBoth();
        }
        this._currentSplitView = splitView;
        return splitView;
    }, detachChildViews: function () {
        WebInspector.View.prototype.detachChildViews.call(this);
        this._currentSplitView = null;
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.EmptyView = function (text) {
    WebInspector.VBox.call(this);
    this._text = text;
}
WebInspector.EmptyView.prototype = {
    wasShown: function () {
        this.element.classList.add("empty-view");
        this.element.textContent = this._text;
    }, set text(text) {
        this._text = text;
        if (this.isShowing())
            this.element.textContent = this._text;
    }, __proto__: WebInspector.VBox.prototype
}
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
WebInspector.TempFile = function (dirPath, name, callback) {
    this._fileEntry = null;
    this._writer = null;
    function didInitFs(fs) {
        fs.root.getDirectory(dirPath, {create: true}, didGetDir.bind(this), errorHandler);
    }

    function didGetDir(dir) {
        dir.getFile(name, {create: true}, didCreateFile.bind(this), errorHandler);
    }

    function didCreateFile(fileEntry) {
        this._fileEntry = fileEntry;
        fileEntry.createWriter(didCreateWriter.bind(this), errorHandler);
    }

    function didCreateWriter(writer) {
        function didTruncate(e) {
            this._writer = writer;
            writer.onwrite = null;
            writer.onerror = null;
            callback(this);
        }

        function onTruncateError(e) {
            WebInspector.console.error("Failed to truncate temp file " + e.code + " : " + e.message);
            callback(null);
        }

        if (writer.length) {
            writer.onwrite = didTruncate.bind(this);
            writer.onerror = onTruncateError;
            writer.truncate(0);
        } else {
            this._writer = writer;
            callback(this);
        }
    }

    function errorHandler(e) {
        WebInspector.console.error("Failed to create temp file " + e.code + " : " + e.message);
        callback(null);
    }

    function didClearTempStorage() {
        window.requestFileSystem(window.TEMPORARY, 10, didInitFs.bind(this), errorHandler);
    }

    WebInspector.TempFile._ensureTempStorageCleared(didClearTempStorage.bind(this));
}
WebInspector.TempFile.prototype = {
    write: function (data, callback) {
        var blob = new Blob([data], {type: 'text/plain'});
        this._writer.onerror = function (e) {
            WebInspector.console.error("Failed to write into a temp file: " + e.message);
            callback(false);
        }
        this._writer.onwrite = function (e) {
            callback(true);
        }
        this._writer.write(blob);
    }, finishWriting: function () {
        this._writer = null;
    }, read: function (callback) {
        function didGetFile(file) {
            var reader = new FileReader();
            reader.onloadend = function (e) {
                callback((this.result));
            }
            reader.onerror = function (error) {
                WebInspector.console.error("Failed to read from temp file: " + error.message);
            }
            reader.readAsText(file);
        }

        function didFailToGetFile(error) {
            WebInspector.console.error("Failed to load temp file: " + error.message);
            callback(null);
        }

        this._fileEntry.file(didGetFile, didFailToGetFile);
    }, writeToOutputSteam: function (outputStream, delegate) {
        function didGetFile(file) {
            var reader = new WebInspector.ChunkedFileReader(file, 10 * 1000 * 1000, delegate);
            reader.start(outputStream);
        }

        function didFailToGetFile(error) {
            WebInspector.console.error("Failed to load temp file: " + error.message);
            outputStream.close();
        }

        this._fileEntry.file(didGetFile, didFailToGetFile);
    }, remove: function () {
        if (this._fileEntry)
            this._fileEntry.remove(function () {
            });
    }
}
WebInspector.BufferedTempFileWriter = function (dirPath, name) {
    this._chunks = [];
    this._tempFile = null;
    this._isWriting = false;
    this._finishCallback = null;
    this._isFinished = false;
    new WebInspector.TempFile(dirPath, name, this._didCreateTempFile.bind(this));
}
WebInspector.BufferedTempFileWriter.prototype = {
    write: function (data) {
        if (!this._chunks)
            return;
        if (this._finishCallback)
            throw new Error("No writes are allowed after close.");
        this._chunks.push(data);
        if (this._tempFile && !this._isWriting)
            this._writeNextChunk();
    }, close: function (callback) {
        this._finishCallback = callback;
        if (this._isFinished)
            callback(this._tempFile); else if (!this._isWriting && !this._chunks.length)
            this._notifyFinished();
    }, _didCreateTempFile: function (tempFile) {
        this._tempFile = tempFile;
        if (!tempFile) {
            this._chunks = null;
            this._notifyFinished();
            return;
        }
        if (this._chunks.length)
            this._writeNextChunk();
    }, _writeNextChunk: function () {
        var chunkSize = 0;
        var endIndex = 0;
        for (; endIndex < this._chunks.length; endIndex++) {
            chunkSize += this._chunks[endIndex].length;
            if (chunkSize > 10 * 1000 * 1000)
                break;
        }
        var chunk = this._chunks.slice(0, endIndex + 1).join("");
        this._chunks.splice(0, endIndex + 1);
        this._isWriting = true;
        this._tempFile.write(chunk, this._didWriteChunk.bind(this));
    }, _didWriteChunk: function (success) {
        this._isWriting = false;
        if (!success) {
            this._tempFile = null;
            this._chunks = null;
            this._notifyFinished();
            return;
        }
        if (this._chunks.length)
            this._writeNextChunk(); else if (this._finishCallback)
            this._notifyFinished();
    }, _notifyFinished: function () {
        this._isFinished = true;
        if (this._tempFile)
            this._tempFile.finishWriting();
        if (this._finishCallback)
            this._finishCallback(this._tempFile);
    }
}
WebInspector.TempStorageCleaner = function () {
    this._worker = new SharedWorker("temp_storage_shared_worker/TempStorageSharedWorker.js", "TempStorage");
    this._callbacks = [];
    this._worker.port.onmessage = this._handleMessage.bind(this);
    this._worker.port.onerror = this._handleError.bind(this);
}
WebInspector.TempStorageCleaner.prototype = {
    ensureStorageCleared: function (callback) {
        if (this._callbacks)
            this._callbacks.push(callback); else
            callback();
    }, _handleMessage: function (event) {
        if (event.data.type === "tempStorageCleared") {
            if (event.data.error)
                WebInspector.console.error(event.data.error);
            this._notifyCallbacks();
        }
    }, _handleError: function (event) {
        WebInspector.console.error(WebInspector.UIString("Failed to clear temp storage: %s", event.data));
        this._notifyCallbacks();
    }, _notifyCallbacks: function () {
        var callbacks = this._callbacks;
        this._callbacks = null;
        for (var i = 0; i < callbacks.length; i++)
            callbacks[i]();
    }
}
WebInspector.TempFile._ensureTempStorageCleared = function (callback) {
    if (!WebInspector.TempFile._storageCleaner)
        WebInspector.TempFile._storageCleaner = new WebInspector.TempStorageCleaner();
    WebInspector.TempFile._storageCleaner.ensureStorageCleared(callback);
}
WebInspector.FileSystemModel = function (target) {
    WebInspector.SDKObject.call(this, target);
    this._fileSystemsForOrigin = {};
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginAdded, this._securityOriginAdded, this);
    target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginRemoved, this._securityOriginRemoved, this);
    this._agent = target.fileSystemAgent();
    this._agent.enable();
    this._reset();
}
WebInspector.FileSystemModel.prototype = {
    _reset: function () {
        for (var securityOrigin in this._fileSystemsForOrigin)
            this._removeOrigin(securityOrigin);
        var securityOrigins = this.target().resourceTreeModel.securityOrigins();
        for (var i = 0; i < securityOrigins.length; ++i)
            this._addOrigin(securityOrigins[i]);
    }, _securityOriginAdded: function (event) {
        var securityOrigin = (event.data);
        this._addOrigin(securityOrigin);
    }, _securityOriginRemoved: function (event) {
        var securityOrigin = (event.data);
        this._removeOrigin(securityOrigin);
    }, _addOrigin: function (securityOrigin) {
        this._fileSystemsForOrigin[securityOrigin] = {};
        var types = ["persistent", "temporary"];
        for (var i = 0; i < types.length; ++i)
            this._requestFileSystemRoot(securityOrigin, types[i], this._fileSystemRootReceived.bind(this, securityOrigin, types[i], this._fileSystemsForOrigin[securityOrigin]));
    }, _removeOrigin: function (securityOrigin) {
        for (var type in this._fileSystemsForOrigin[securityOrigin]) {
            var fileSystem = this._fileSystemsForOrigin[securityOrigin][type];
            delete this._fileSystemsForOrigin[securityOrigin][type];
            this._fileSystemRemoved(fileSystem);
        }
        delete this._fileSystemsForOrigin[securityOrigin];
    }, _requestFileSystemRoot: function (origin, type, callback) {
        function innerCallback(error, errorCode, backendRootEntry) {
            if (error) {
                callback(FileError.SECURITY_ERR);
                return;
            }
            callback(errorCode, backendRootEntry);
        }

        this._agent.requestFileSystemRoot(origin, type, innerCallback);
    }, _fileSystemAdded: function (fileSystem) {
        this.dispatchEventToListeners(WebInspector.FileSystemModel.EventTypes.FileSystemAdded, fileSystem);
    }, _fileSystemRemoved: function (fileSystem) {
        this.dispatchEventToListeners(WebInspector.FileSystemModel.EventTypes.FileSystemRemoved, fileSystem);
    }, refreshFileSystemList: function () {
        this._reset();
    }, _fileSystemRootReceived: function (origin, type, store, errorCode, backendRootEntry) {
        if (!errorCode && backendRootEntry && this._fileSystemsForOrigin[origin] === store) {
            var fileSystem = new WebInspector.FileSystemModel.FileSystem(this, origin, type, backendRootEntry);
            store[type] = fileSystem;
            this._fileSystemAdded(fileSystem);
        }
    }, requestDirectoryContent: function (directory, callback) {
        this._requestDirectoryContent(directory.url, this._directoryContentReceived.bind(this, directory, callback));
    }, _requestDirectoryContent: function (url, callback) {
        function innerCallback(error, errorCode, backendEntries) {
            if (error) {
                callback(FileError.SECURITY_ERR);
                return;
            }
            if (errorCode !== 0) {
                callback(errorCode);
                return;
            }
            callback(errorCode, backendEntries);
        }

        this._agent.requestDirectoryContent(url, innerCallback);
    }, _directoryContentReceived: function (parentDirectory, callback, errorCode, backendEntries) {
        if (!backendEntries) {
            callback(errorCode);
            return;
        }
        var entries = [];
        for (var i = 0; i < backendEntries.length; ++i) {
            if (backendEntries[i].isDirectory)
                entries.push(new WebInspector.FileSystemModel.Directory(this, parentDirectory.fileSystem, backendEntries[i])); else
                entries.push(new WebInspector.FileSystemModel.File(this, parentDirectory.fileSystem, backendEntries[i]));
        }
        callback(errorCode, entries);
    }, requestMetadata: function (entry, callback) {
        function innerCallback(error, errorCode, metadata) {
            if (error) {
                callback(FileError.SECURITY_ERR);
                return;
            }
            callback(errorCode, metadata);
        }

        this._agent.requestMetadata(entry.url, innerCallback);
    }, requestFileContent: function (file, readAsText, start, end, charset, callback) {
        this._requestFileContent(file.url, readAsText, start, end, charset, callback);
    }, _requestFileContent: function (url, readAsText, start, end, charset, callback) {
        function innerCallback(error, errorCode, content, charset) {
            if (error) {
                if (callback)
                    callback(FileError.SECURITY_ERR);
                return;
            }
            if (callback)
                callback(errorCode, content, charset);
        }

        this._agent.requestFileContent(url, readAsText, start, end, charset, innerCallback);
    }, deleteEntry: function (entry, callback) {
        var fileSystemModel = this;
        if (entry === entry.fileSystem.root)
            this._deleteEntry(entry.url, hookFileSystemDeletion); else
            this._deleteEntry(entry.url, callback);
        function hookFileSystemDeletion(errorCode) {
            callback(errorCode);
            if (!errorCode)
                fileSystemModel._removeFileSystem(entry.fileSystem);
        }
    }, _deleteEntry: function (url, callback) {
        function innerCallback(error, errorCode) {
            if (error) {
                if (callback)
                    callback(FileError.SECURITY_ERR);
                return;
            }
            if (callback)
                callback(errorCode);
        }

        this._agent.deleteEntry(url, innerCallback);
    }, _removeFileSystem: function (fileSystem) {
        var origin = fileSystem.origin;
        var type = fileSystem.type;
        if (this._fileSystemsForOrigin[origin] && this._fileSystemsForOrigin[origin][type]) {
            delete this._fileSystemsForOrigin[origin][type];
            this._fileSystemRemoved(fileSystem);
            if (Object.isEmpty(this._fileSystemsForOrigin[origin]))
                delete this._fileSystemsForOrigin[origin];
        }
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.FileSystemModel.EventTypes = {FileSystemAdded: "FileSystemAdded", FileSystemRemoved: "FileSystemRemoved"}
WebInspector.FileSystemModel.FileSystem = function (fileSystemModel, origin, type, backendRootEntry) {
    this.origin = origin;
    this.type = type;
    this.root = new WebInspector.FileSystemModel.Directory(fileSystemModel, this, backendRootEntry);
}
WebInspector.FileSystemModel.FileSystem.prototype = {
    get name() {
        return "filesystem:" + this.origin + "/" + this.type;
    }
}
WebInspector.FileSystemModel.Entry = function (fileSystemModel, fileSystem, backendEntry) {
    this._fileSystemModel = fileSystemModel;
    this._fileSystem = fileSystem;
    this._url = backendEntry.url;
    this._name = backendEntry.name;
    this._isDirectory = backendEntry.isDirectory;
}
WebInspector.FileSystemModel.Entry.compare = function (x, y) {
    if (x.isDirectory != y.isDirectory)
        return y.isDirectory ? 1 : -1;
    return x.name.compareTo(y.name);
}
WebInspector.FileSystemModel.Entry.prototype = {
    get fileSystemModel() {
        return this._fileSystemModel;
    }, get fileSystem() {
        return this._fileSystem;
    }, get url() {
        return this._url;
    }, get name() {
        return this._name;
    }, get isDirectory() {
        return this._isDirectory;
    }, requestMetadata: function (callback) {
        this.fileSystemModel.requestMetadata(this, callback);
    }, deleteEntry: function (callback) {
        this.fileSystemModel.deleteEntry(this, callback);
    }
}
WebInspector.FileSystemModel.Directory = function (fileSystemModel, fileSystem, backendEntry) {
    WebInspector.FileSystemModel.Entry.call(this, fileSystemModel, fileSystem, backendEntry);
}
WebInspector.FileSystemModel.Directory.prototype = {
    requestDirectoryContent: function (callback) {
        this.fileSystemModel.requestDirectoryContent(this, callback);
    }, __proto__: WebInspector.FileSystemModel.Entry.prototype
}
WebInspector.FileSystemModel.File = function (fileSystemModel, fileSystem, backendEntry) {
    WebInspector.FileSystemModel.Entry.call(this, fileSystemModel, fileSystem, backendEntry);
    this._mimeType = backendEntry.mimeType;
    this._resourceType = WebInspector.resourceTypes[backendEntry.resourceType];
    this._isTextFile = backendEntry.isTextFile;
}
WebInspector.FileSystemModel.File.prototype = {
    get mimeType() {
        return this._mimeType;
    }, get resourceType() {
        return this._resourceType;
    }, get isTextFile() {
        return this._isTextFile;
    }, requestFileContent: function (readAsText, start, end, charset, callback) {
        this.fileSystemModel.requestFileContent(this, readAsText, start, end, charset, callback);
    }, __proto__: WebInspector.FileSystemModel.Entry.prototype
}
WebInspector.OutputStreamDelegate = function () {
}
WebInspector.OutputStreamDelegate.prototype = {
    onTransferStarted: function () {
    }, onTransferFinished: function () {
    }, onChunkTransferred: function (reader) {
    }, onError: function (reader, event) {
    },
}
WebInspector.OutputStream = function () {
}
WebInspector.OutputStream.prototype = {
    write: function (data, callback) {
    }, close: function () {
    }
}
WebInspector.ChunkedReader = function () {
}
WebInspector.ChunkedReader.prototype = {
    fileSize: function () {
    }, loadedSize: function () {
    }, fileName: function () {
    }, cancel: function () {
    }
}
WebInspector.ChunkedFileReader = function (file, chunkSize, delegate) {
    this._file = file;
    this._fileSize = file.size;
    this._loadedSize = 0;
    this._chunkSize = chunkSize;
    this._delegate = delegate;
    this._isCanceled = false;
}
WebInspector.ChunkedFileReader.prototype = {
    start: function (output) {
        this._output = output;
        this._reader = new FileReader();
        this._reader.onload = this._onChunkLoaded.bind(this);
        this._reader.onerror = this._delegate.onError.bind(this._delegate, this);
        this._delegate.onTransferStarted();
        this._loadChunk();
    }, cancel: function () {
        this._isCanceled = true;
    }, loadedSize: function () {
        return this._loadedSize;
    }, fileSize: function () {
        return this._fileSize;
    }, fileName: function () {
        return this._file.name;
    }, _onChunkLoaded: function (event) {
        if (this._isCanceled)
            return;
        if (event.target.readyState !== FileReader.DONE)
            return;
        var data = event.target.result;
        this._loadedSize += data.length;
        this._output.write(data);
        if (this._isCanceled)
            return;
        this._delegate.onChunkTransferred(this);
        if (this._loadedSize === this._fileSize) {
            this._file = null;
            this._reader = null;
            this._output.close();
            this._delegate.onTransferFinished();
            return;
        }
        this._loadChunk();
    }, _loadChunk: function () {
        var chunkStart = this._loadedSize;
        var chunkEnd = Math.min(this._fileSize, chunkStart + this._chunkSize)
        var nextPart = this._file.slice(chunkStart, chunkEnd);
        this._reader.readAsText(nextPart);
    }
}
WebInspector.createFileSelectorElement = function (callback) {
    var fileSelectorElement = document.createElement("input");
    fileSelectorElement.type = "file";
    fileSelectorElement.style.display = "none";
    fileSelectorElement.setAttribute("tabindex", -1);
    fileSelectorElement.onchange = onChange;
    function onChange(event) {
        callback(fileSelectorElement.files[0]);
    };
    return fileSelectorElement;
}
WebInspector.FileOutputStream = function () {
}
WebInspector.FileOutputStream.prototype = {
    open: function (fileName, callback) {
        this._closed = false;
        this._writeCallbacks = [];
        this._fileName = fileName;
        function callbackWrapper(accepted) {
            if (accepted)
                WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this);
            callback(accepted);
        }

        WebInspector.fileManager.save(this._fileName, "", true, callbackWrapper.bind(this));
    }, write: function (data, callback) {
        this._writeCallbacks.push(callback);
        WebInspector.fileManager.append(this._fileName, data);
    }, close: function () {
        this._closed = true;
        if (this._writeCallbacks.length)
            return;
        WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this);
        WebInspector.fileManager.close(this._fileName);
    }, _onAppendDone: function (event) {
        if (event.data !== this._fileName)
            return;
        var callback = this._writeCallbacks.shift();
        if (callback)
            callback(this);
        if (!this._writeCallbacks.length) {
            if (this._closed) {
                WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this);
                WebInspector.fileManager.close(this._fileName);
            }
        }
    }
}
WebInspector.DebuggerModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.DebuggerModel, target);
    target.registerDebuggerDispatcher(new WebInspector.DebuggerDispatcher(this));
    this._agent = target.debuggerAgent();
    this._debuggerPausedDetails = null;
    this._scripts = {};
    this._scriptsBySourceURL = new StringMap();
    this._breakpointResolvedEventTarget = new WebInspector.Object();
    this._isPausing = false;
    WebInspector.settings.pauseOnExceptionEnabled.addChangeListener(this._pauseOnExceptionStateChanged, this);
    WebInspector.settings.pauseOnCaughtException.addChangeListener(this._pauseOnExceptionStateChanged, this);
    WebInspector.settings.enableAsyncStackTraces.addChangeListener(this._asyncStackTracesStateChanged, this);
    WebInspector.profilingLock().addEventListener(WebInspector.Lock.Events.StateChanged, this._profilingStateChanged, this);
    this.enableDebugger();
    WebInspector.settings.skipStackFramesPattern.addChangeListener(this._applySkipStackFrameSettings, this);
    this._applySkipStackFrameSettings();
}
WebInspector.DebuggerModel.FunctionDetails;
WebInspector.DebuggerModel.PauseOnExceptionsState = {DontPauseOnExceptions: "none", PauseOnAllExceptions: "all", PauseOnUncaughtExceptions: "uncaught"};
WebInspector.DebuggerModel.Events = {
    DebuggerWasEnabled: "DebuggerWasEnabled",
    DebuggerWasDisabled: "DebuggerWasDisabled",
    DebuggerPaused: "DebuggerPaused",
    DebuggerResumed: "DebuggerResumed",
    ParsedScriptSource: "ParsedScriptSource",
    FailedToParseScriptSource: "FailedToParseScriptSource",
    GlobalObjectCleared: "GlobalObjectCleared",
    CallFrameSelected: "CallFrameSelected",
    ConsoleCommandEvaluatedInSelectedCallFrame: "ConsoleCommandEvaluatedInSelectedCallFrame",
}
WebInspector.DebuggerModel.BreakReason = {DOM: "DOM", EventListener: "EventListener", XHR: "XHR", Exception: "exception", Assert: "assert", CSPViolation: "CSPViolation", DebugCommand: "debugCommand"}
WebInspector.DebuggerModel.prototype = {
    debuggerEnabled: function () {
        return !!this._debuggerEnabled;
    }, enableDebugger: function () {
        if (this._debuggerEnabled)
            return;
        this._agent.enable();
        this._debuggerEnabled = true;
        this._pauseOnExceptionStateChanged();
        this._asyncStackTracesStateChanged();
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasEnabled);
    }, disableDebugger: function () {
        if (!this._debuggerEnabled)
            return;
        this._agent.disable();
        this._debuggerEnabled = false;
        this._isPausing = false;
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasDisabled);
    }, skipAllPauses: function (skip, untilReload) {
        if (this._skipAllPausesTimeout) {
            clearTimeout(this._skipAllPausesTimeout);
            delete this._skipAllPausesTimeout;
        }
        this._agent.setSkipAllPauses(skip, untilReload);
    }, skipAllPausesUntilReloadOrTimeout: function (timeout) {
        if (this._skipAllPausesTimeout)
            clearTimeout(this._skipAllPausesTimeout);
        this._agent.setSkipAllPauses(true, true);
        this._skipAllPausesTimeout = setTimeout(this.skipAllPauses.bind(this, false), timeout);
    }, _pauseOnExceptionStateChanged: function () {
        var state;
        if (!WebInspector.settings.pauseOnExceptionEnabled.get()) {
            state = WebInspector.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions;
        } else if (WebInspector.settings.pauseOnCaughtException.get()) {
            state = WebInspector.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions;
        } else {
            state = WebInspector.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions;
        }
        this._agent.setPauseOnExceptions(state);
    }, _profilingStateChanged: function () {
        if (WebInspector.experimentsSettings.disableAgentsWhenProfile.isEnabled()) {
            if (WebInspector.profilingLock().isAcquired())
                this.disableDebugger(); else
                this.enableDebugger();
        }
        this._asyncStackTracesStateChanged();
    }, _asyncStackTracesStateChanged: function () {
        const maxAsyncStackChainDepth = 4;
        var enabled = WebInspector.settings.enableAsyncStackTraces.get() && !WebInspector.profilingLock().isAcquired();
        this._agent.setAsyncCallStackDepth(enabled ? maxAsyncStackChainDepth : 0);
    }, stepInto: function () {
        function callback() {
            this._agent.stepInto();
        }

        this._agent.setOverlayMessage(undefined, callback.bind(this));
    }, stepOver: function () {
        function callback() {
            this._agent.stepOver();
        }

        this._agent.setOverlayMessage(undefined, callback.bind(this));
    }, stepOut: function () {
        function callback() {
            this._agent.stepOut();
        }

        this._agent.setOverlayMessage(undefined, callback.bind(this));
    }, resume: function () {
        function callback() {
            this._agent.resume();
        }

        this._agent.setOverlayMessage(undefined, callback.bind(this));
        this._isPausing = false;
    }, pause: function () {
        this._isPausing = true;
        this.skipAllPauses(false);
        this._agent.pause();
    }, setBreakpointByURL: function (url, lineNumber, columnNumber, condition, callback) {
        var minColumnNumber = 0;
        var scripts = this._scriptsBySourceURL.get(url) || [];
        for (var i = 0, l = scripts.length; i < l; ++i) {
            var script = scripts[i];
            if (lineNumber === script.lineOffset)
                minColumnNumber = minColumnNumber ? Math.min(minColumnNumber, script.columnOffset) : script.columnOffset;
        }
        columnNumber = Math.max(columnNumber, minColumnNumber);
        var target = this.target();

        function didSetBreakpoint(error, breakpointId, locations) {
            if (callback) {
                var rawLocations = locations ? locations.map(WebInspector.DebuggerModel.Location.fromPayload.bind(WebInspector.DebuggerModel.Location, target)) : [];
                callback(error ? null : breakpointId, rawLocations);
            }
        }

        this._agent.setBreakpointByUrl(lineNumber, url, undefined, columnNumber, condition, undefined, didSetBreakpoint);
        WebInspector.userMetrics.ScriptsBreakpointSet.record();
    }, setBreakpointBySourceId: function (rawLocation, condition, callback) {
        var target = this.target();

        function didSetBreakpoint(error, breakpointId, actualLocation) {
            if (callback) {
                var location = WebInspector.DebuggerModel.Location.fromPayload(target, actualLocation);
                callback(error ? null : breakpointId, [location]);
            }
        }

        this._agent.setBreakpoint(rawLocation.payload(), condition, didSetBreakpoint);
        WebInspector.userMetrics.ScriptsBreakpointSet.record();
    }, removeBreakpoint: function (breakpointId, callback) {
        this._agent.removeBreakpoint(breakpointId, innerCallback);
        function innerCallback(error) {
            if (error)
                console.error("Failed to remove breakpoint: " + error);
            if (callback)
                callback();
        }
    }, _breakpointResolved: function (breakpointId, location) {
        this._breakpointResolvedEventTarget.dispatchEventToListeners(breakpointId, WebInspector.DebuggerModel.Location.fromPayload(this.target(), location));
    }, _globalObjectCleared: function () {
        this._setDebuggerPausedDetails(null);
        this._reset();
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.GlobalObjectCleared);
    }, _reset: function () {
        this._scripts = {};
        this._scriptsBySourceURL.clear();
    }, get scripts() {
        return this._scripts;
    }, scriptForId: function (scriptId) {
        return this._scripts[scriptId] || null;
    }, scriptsForSourceURL: function (sourceURL) {
        if (!sourceURL)
            return [];
        return this._scriptsBySourceURL.get(sourceURL) || [];
    }, setScriptSource: function (scriptId, newSource, callback) {
        this._scripts[scriptId].editSource(newSource, this._didEditScriptSource.bind(this, scriptId, newSource, callback));
    }, _didEditScriptSource: function (scriptId, newSource, callback, error, errorData, callFrames, asyncStackTrace, needsStepIn) {
        if (needsStepIn) {
            this.stepInto();
            this._pendingLiveEditCallback = callback.bind(this, error, errorData);
            return;
        }
        if (!error && callFrames && callFrames.length)
            this._pausedScript(callFrames, this._debuggerPausedDetails.reason, this._debuggerPausedDetails.auxData, this._debuggerPausedDetails.breakpointIds, asyncStackTrace);
        callback(error, errorData);
    }, get callFrames() {
        return this._debuggerPausedDetails ? this._debuggerPausedDetails.callFrames : null;
    }, debuggerPausedDetails: function () {
        return this._debuggerPausedDetails;
    }, _setDebuggerPausedDetails: function (debuggerPausedDetails) {
        this._isPausing = false;
        this._debuggerPausedDetails = debuggerPausedDetails;
        if (this._debuggerPausedDetails)
            this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPausedDetails);
        if (debuggerPausedDetails) {
            this.setSelectedCallFrame(debuggerPausedDetails.callFrames[0]);
            this._agent.setOverlayMessage(WebInspector.UIString("Paused in debugger"));
        } else {
            this.setSelectedCallFrame(null);
            this._agent.setOverlayMessage();
        }
    }, _pausedScript: function (callFrames, reason, auxData, breakpointIds, asyncStackTrace) {
        this._setDebuggerPausedDetails(new WebInspector.DebuggerPausedDetails(this.target(), callFrames, reason, auxData, breakpointIds, asyncStackTrace));
        if (this._pendingLiveEditCallback) {
            var callback = this._pendingLiveEditCallback;
            delete this._pendingLiveEditCallback;
            callback();
        }
    }, _resumedScript: function () {
        this._setDebuggerPausedDetails(null);
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerResumed);
    }, _parsedScriptSource: function (scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL, hasSyntaxError, contextData) {
        var script = new WebInspector.Script(this.target(), scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL, contextData);
        this._registerScript(script);
        if (!hasSyntaxError)
            this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ParsedScriptSource, script); else
            this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.FailedToParseScriptSource, script);
    }, _registerScript: function (script) {
        this._scripts[script.scriptId] = script;
        if (script.isAnonymousScript())
            return;
        var scripts = this._scriptsBySourceURL.get(script.sourceURL);
        if (!scripts) {
            scripts = [];
            this._scriptsBySourceURL.put(script.sourceURL, scripts);
        }
        if (scripts.length && scripts[0].scriptId < script.scriptId)
            scripts.unshift(script); else
            scripts.push(script);
    }, createRawLocation: function (script, lineNumber, columnNumber) {
        if (script.sourceURL)
            return this.createRawLocationByURL(script.sourceURL, lineNumber, columnNumber);
        return new WebInspector.DebuggerModel.Location(this.target(), script.scriptId, lineNumber, columnNumber);
    }, createRawLocationByURL: function (sourceURL, lineNumber, columnNumber) {
        var closestScript = null;
        var scripts = this._scriptsBySourceURL.get(sourceURL) || [];
        for (var i = 0, l = scripts.length; i < l; ++i) {
            var script = scripts[i];
            if (!closestScript)
                closestScript = script;
            if (script.lineOffset > lineNumber || (script.lineOffset === lineNumber && script.columnOffset > columnNumber))
                continue;
            if (script.endLine < lineNumber || (script.endLine === lineNumber && script.endColumn <= columnNumber))
                continue;
            closestScript = script;
            break;
        }
        return closestScript ? new WebInspector.DebuggerModel.Location(this.target(), closestScript.scriptId, lineNumber, columnNumber) : null;
    }, createRawLocationByScriptId: function (scriptId, sourceUrl, lineNumber, columnNumber) {
        var script = scriptId ? this.scriptForId(scriptId) : null;
        return script ? this.createRawLocation(script, lineNumber, columnNumber) : this.createRawLocationByURL(sourceUrl, lineNumber, columnNumber);
    }, isPaused: function () {
        return !!this.debuggerPausedDetails();
    }, isPausing: function () {
        return this._isPausing;
    }, setSelectedCallFrame: function (callFrame) {
        this._selectedCallFrame = callFrame;
        if (!this._selectedCallFrame)
            return;
        this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.CallFrameSelected, callFrame);
    }, selectedCallFrame: function () {
        return this._selectedCallFrame;
    }, evaluateOnSelectedCallFrame: function (code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback) {
        function didEvaluate(result, wasThrown, exceptionDetails) {
            if (!result)
                callback(null, false); else if (returnByValue)
                callback(null, !!wasThrown, wasThrown ? null : result, exceptionDetails); else
                callback(this.target().runtimeModel.createRemoteObject(result), !!wasThrown, undefined, exceptionDetails);
            if (objectGroup === "console")
                this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ConsoleCommandEvaluatedInSelectedCallFrame);
        }

        this.selectedCallFrame().evaluate(code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, didEvaluate.bind(this));
    }, getSelectedCallFrameVariables: function (callback) {
        var result = {this: true};
        var selectedCallFrame = this._selectedCallFrame;
        if (!selectedCallFrame)
            callback(result);
        var pendingRequests = 0;

        function propertiesCollected(properties) {
            for (var i = 0; properties && i < properties.length; ++i)
                result[properties[i].name] = true;
            if (--pendingRequests == 0)
                callback(result);
        }

        for (var i = 0; i < selectedCallFrame.scopeChain.length; ++i) {
            var scope = selectedCallFrame.scopeChain[i];
            var object = this.target().runtimeModel.createRemoteObject(scope.object);
            pendingRequests++;
            object.getAllProperties(false, propertiesCollected);
        }
    }, callStackModified: function (newCallFrames, details, asyncStackTrace) {
        if (details && details["stack_update_needs_step_in"])
            this.stepInto(); else if (newCallFrames && newCallFrames.length)
            this._pausedScript(newCallFrames, this._debuggerPausedDetails.reason, this._debuggerPausedDetails.auxData, this._debuggerPausedDetails.breakpointIds, asyncStackTrace);
    }, _applySkipStackFrameSettings: function () {
        this._agent.skipStackFrames(WebInspector.settings.skipStackFramesPattern.get());
    }, functionDetails: function (remoteObject, callback) {
        this._agent.getFunctionDetails(remoteObject.objectId, didGetDetails.bind(this));
        function didGetDetails(error, response) {
            if (error) {
                console.error(error);
                callback(null);
                return;
            }
            var location = response.location;
            var script = this.scriptForId(location.scriptId);
            var rawLocation = script ? this.createRawLocation(script, location.lineNumber + 1, location.columnNumber + 1) : null;
            var sourceURL = script ? script.contentURL() : null;
            callback({location: rawLocation, sourceURL: sourceURL, functionName: response.functionName, scopeChain: response.scopeChain || null});
        }
    }, addBreakpointListener: function (breakpointId, listener, thisObject) {
        this._breakpointResolvedEventTarget.addEventListener(breakpointId, listener, thisObject)
    }, removeBreakpointListener: function (breakpointId, listener, thisObject) {
        this._breakpointResolvedEventTarget.removeEventListener(breakpointId, listener, thisObject);
    }, dispose: function () {
        WebInspector.settings.pauseOnExceptionEnabled.removeChangeListener(this._pauseOnExceptionStateChanged, this);
        WebInspector.settings.pauseOnCaughtException.removeChangeListener(this._pauseOnExceptionStateChanged, this);
        WebInspector.settings.skipStackFramesPattern.removeChangeListener(this._applySkipStackFrameSettings, this);
        WebInspector.settings.enableAsyncStackTraces.removeChangeListener(this._asyncStackTracesStateChanged, this);
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.DebuggerEventTypes = {JavaScriptPause: 0, JavaScriptBreakpoint: 1, NativeBreakpoint: 2};
WebInspector.DebuggerDispatcher = function (debuggerModel) {
    this._debuggerModel = debuggerModel;
}
WebInspector.DebuggerDispatcher.prototype = {
    paused: function (callFrames, reason, auxData, breakpointIds, asyncStackTrace) {
        this._debuggerModel._pausedScript(callFrames, reason, auxData, breakpointIds || [], asyncStackTrace);
    }, resumed: function () {
        this._debuggerModel._resumedScript();
    }, globalObjectCleared: function () {
        this._debuggerModel._globalObjectCleared();
    }, scriptParsed: function (scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL, contextData) {
        this._debuggerModel._parsedScriptSource(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, !!isContentScript, sourceMapURL, hasSourceURL, false, contextData);
    }, scriptFailedToParse: function (scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL) {
        this._debuggerModel._parsedScriptSource(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, !!isContentScript, sourceMapURL, hasSourceURL, true);
    }, breakpointResolved: function (breakpointId, location) {
        this._debuggerModel._breakpointResolved(breakpointId, location);
    }
}
WebInspector.DebuggerModel.Location = function (target, scriptId, lineNumber, columnNumber) {
    WebInspector.SDKObject.call(this, target);
    this._debuggerModel = target.debuggerModel;
    this.scriptId = scriptId;
    this.lineNumber = lineNumber;
    this.columnNumber = columnNumber || 0;
}
WebInspector.DebuggerModel.Location.fromPayload = function (target, payload) {
    return new WebInspector.DebuggerModel.Location(target, payload.scriptId, payload.lineNumber, payload.columnNumber);
}
WebInspector.DebuggerModel.Location.prototype = {
    payload: function () {
        return {scriptId: this.scriptId, lineNumber: this.lineNumber, columnNumber: this.columnNumber};
    }, script: function () {
        return this._debuggerModel.scriptForId(this.scriptId);
    }, continueToLocation: function () {
        this._debuggerModel._agent.continueToLocation(this.payload());
    }, id: function () {
        return this.target().id() + ":" + this.scriptId + ":" + this.lineNumber + ":" + this.columnNumber
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.DebuggerModel.CallFrame = function (target, script, payload, isAsync) {
    WebInspector.SDKObject.call(this, target);
    this._debuggerAgent = target.debuggerModel._agent;
    this._script = script;
    this._payload = payload;
    this._isAsync = isAsync;
    this._location = WebInspector.DebuggerModel.Location.fromPayload(target, payload.location);
}
WebInspector.DebuggerModel.CallFrame.fromPayloadArray = function (target, callFrames, isAsync) {
    var result = [];
    for (var i = 0; i < callFrames.length; ++i) {
        var callFrame = callFrames[i];
        var script = target.debuggerModel.scriptForId(callFrame.location.scriptId);
        if (script)
            result.push(new WebInspector.DebuggerModel.CallFrame(target, script, callFrame, isAsync));
    }
    return result;
}
WebInspector.DebuggerModel.CallFrame.prototype = {
    get script() {
        return this._script;
    }, get type() {
        return this._payload.type;
    }, get id() {
        return this._payload.callFrameId;
    }, get scopeChain() {
        return this._payload.scopeChain;
    }, thisObject: function () {
        return this._payload.this ? this.target().runtimeModel.createRemoteObject(this._payload.this) : null;
    }, returnValue: function () {
        return this._payload.returnValue ? this.target().runtimeModel.createRemoteObject(this._payload.returnValue) : null
    }, get functionName() {
        return this._payload.functionName;
    }, location: function () {
        return this._location;
    }, isAsync: function () {
        return !!this._isAsync;
    }, evaluate: function (code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback) {
        function didEvaluateOnCallFrame(error, result, wasThrown, exceptionDetails) {
            if (error) {
                console.error(error);
                callback(null, false);
                return;
            }
            callback(result, wasThrown, exceptionDetails);
        }

        this._debuggerAgent.evaluateOnCallFrame(this._payload.callFrameId, code, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, didEvaluateOnCallFrame);
    }, restart: function (callback) {
        function protocolCallback(error, callFrames, details, asyncStackTrace) {
            if (!error)
                this.target().debuggerModel.callStackModified(callFrames, details, asyncStackTrace);
            if (callback)
                callback(error);
        }

        this._debuggerAgent.restartFrame(this._payload.callFrameId, protocolCallback.bind(this));
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.DebuggerModel.StackTrace = function (callFrames, asyncStackTrace, description) {
    this.callFrames = callFrames;
    this.asyncStackTrace = asyncStackTrace;
    this.description = description;
}
WebInspector.DebuggerModel.StackTrace.fromPayload = function (target, payload, isAsync) {
    if (!payload)
        return null;
    var callFrames = WebInspector.DebuggerModel.CallFrame.fromPayloadArray(target, payload.callFrames, isAsync);
    if (!callFrames.length)
        return null;
    var asyncStackTrace = WebInspector.DebuggerModel.StackTrace.fromPayload(target, payload.asyncStackTrace, true);
    return new WebInspector.DebuggerModel.StackTrace(callFrames, asyncStackTrace, payload.description);
}
WebInspector.DebuggerPausedDetails = function (target, callFrames, reason, auxData, breakpointIds, asyncStackTrace) {
    WebInspector.SDKObject.call(this, target);
    this.callFrames = WebInspector.DebuggerModel.CallFrame.fromPayloadArray(target, callFrames);
    this.reason = reason;
    this.auxData = auxData;
    this.breakpointIds = breakpointIds;
    this.asyncStackTrace = WebInspector.DebuggerModel.StackTrace.fromPayload(target, asyncStackTrace, true);
}
WebInspector.DebuggerPausedDetails.prototype = {
    exception: function () {
        if (this.reason !== WebInspector.DebuggerModel.BreakReason.Exception)
            return null;
        return this.target().runtimeModel.createRemoteObject((this.auxData));
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.debuggerModel;
WebInspector.DebuggerWorkspaceBinding = function (targetManager, workspace, networkWorkspaceBinding) {
    this._workspace = workspace;
    this._networkWorkspaceBinding = networkWorkspaceBinding;
    this._targetToData = new Map();
    targetManager.observeTargets(this);
    targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._globalObjectCleared, this);
    targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.DebuggerResumed, this._debuggerResumed, this);
    workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this);
}
WebInspector.DebuggerWorkspaceBinding.prototype = {
    targetAdded: function (target) {
        this._targetToData.put(target, new WebInspector.DebuggerWorkspaceBinding.TargetData(target, this));
    }, targetRemoved: function (target) {
        this._targetToData.remove(target)._dispose();
    }, _uiSourceCodeRemoved: function (event) {
        var uiSourceCode = (event.data);
        var targetDatas = this._targetToData.values();
        for (var i = 0; i < targetDatas.length; ++i)
            targetDatas[i]._uiSourceCodeRemoved(uiSourceCode);
    }, pushSourceMapping: function (script, sourceMapping) {
        var info = this._ensureInfoForScript(script);
        info._pushSourceMapping(sourceMapping);
    }, popSourceMapping: function (script) {
        var info = this._infoForScript(script.target(), script.scriptId);
        console.assert(info);
        return info._popSourceMapping();
    }, setSourceMapping: function (target, uiSourceCode, sourceMapping) {
        var data = this._targetToData.get(target);
        if (data)
            data._setSourceMapping(uiSourceCode, sourceMapping);
    }, updateLocations: function (script) {
        var info = this._infoForScript(script.target(), script.scriptId);
        if (info)
            info._updateLocations();
    }, createLiveLocation: function (rawLocation, updateDelegate) {
        var info = this._infoForScript(rawLocation.target(), rawLocation.scriptId);
        console.assert(info);
        var location = new WebInspector.DebuggerWorkspaceBinding.Location(info._script, rawLocation, this, updateDelegate);
        info._addLocation(location);
        return location;
    }, createCallFrameLiveLocation: function (callFrame, updateDelegate) {
        var target = callFrame.target();
        this._ensureInfoForScript(callFrame.script)
        var location = this.createLiveLocation(callFrame.location(), updateDelegate);
        this._registerCallFrameLiveLocation(target, location);
        return location;
    }, rawLocationToUILocation: function (rawLocation) {
        var info = this._infoForScript(rawLocation.target(), rawLocation.scriptId);
        console.assert(info);
        return info._rawLocationToUILocation(rawLocation);
    }, uiLocationToRawLocation: function (target, uiSourceCode, lineNumber, columnNumber) {
        var targetData = this._targetToData.get(target);
        return targetData ? (targetData._uiLocationToRawLocation(uiSourceCode, lineNumber, columnNumber)) : null;
    }, uiLocationToRawLocations: function (uiSourceCode, lineNumber, columnNumber) {
        var result = [];
        var targetDatas = this._targetToData.values();
        for (var i = 0; i < targetDatas.length; ++i) {
            var rawLocation = targetDatas[i]._uiLocationToRawLocation(uiSourceCode, lineNumber, columnNumber);
            if (rawLocation)
                result.push(rawLocation);
        }
        return result;
    }, uiLineHasMapping: function (uiSourceCode, lineNumber) {
        var targetDatas = this._targetToData.values();
        for (var i = 0; i < targetDatas.length; ++i) {
            if (!targetDatas[i]._uiLineHasMapping(uiSourceCode, lineNumber))
                return false;
        }
        return true;
    }, liveEditSupport: function (target) {
        var targetData = this._targetToData.get(target);
        return targetData ? targetData._liveEditSupport : null;
    }, scriptFile: function (uiSourceCode, target) {
        var targetData = this._targetToData.get(target);
        return targetData ? targetData._resourceMapping.scriptFile(uiSourceCode) : null;
    }, _globalObjectCleared: function (event) {
        var debuggerModel = (event.target);
        this._reset(debuggerModel.target());
    }, _reset: function (target) {
        var targetData = this._targetToData.get(target);
        targetData.callFrameLocations.values().forEach(function (location) {
            location.dispose();
        });
        targetData.callFrameLocations.clear();
    }, _ensureInfoForScript: function (script) {
        var scriptDataMap = this._targetToData.get(script.target()).scriptDataMap;
        var info = scriptDataMap.get(script.scriptId);
        if (!info) {
            info = new WebInspector.DebuggerWorkspaceBinding.ScriptInfo(script);
            scriptDataMap.put(script.scriptId, info);
        }
        return info;
    }, _infoForScript: function (target, scriptId) {
        var data = this._targetToData.get(target);
        if (!data)
            return null;
        return data.scriptDataMap.get(scriptId) || null;
    }, _registerCallFrameLiveLocation: function (target, location) {
        var locations = this._targetToData.get(target).callFrameLocations;
        locations.add(location);
    }, _removeLiveLocation: function (location) {
        var info = this._infoForScript(location._script.target(), location._script.scriptId);
        if (info)
            info._removeLocation(location);
    }, _debuggerResumed: function (event) {
        var debuggerModel = (event.target);
        this._reset(debuggerModel.target());
    }
}
WebInspector.DebuggerWorkspaceBinding.TargetData = function (target, debuggerWorkspaceBinding) {
    this._target = target;
    this.scriptDataMap = new StringMap();
    this.callFrameLocations = new Set();
    var debuggerModel = target.debuggerModel;
    var workspace = debuggerWorkspaceBinding._workspace;
    this._liveEditSupport = new WebInspector.LiveEditSupport(target, workspace, debuggerWorkspaceBinding);
    this._defaultMapping = new WebInspector.DefaultScriptMapping(debuggerModel, workspace, debuggerWorkspaceBinding);
    this._resourceMapping = new WebInspector.ResourceScriptMapping(debuggerModel, workspace, debuggerWorkspaceBinding);
    this._compilerMapping = new WebInspector.CompilerScriptMapping(debuggerModel, workspace, debuggerWorkspaceBinding._networkWorkspaceBinding, debuggerWorkspaceBinding);
    this._liveEditSupport = new WebInspector.LiveEditSupport(target, workspace, debuggerWorkspaceBinding);
    this._uiSourceCodeToSourceMapping = new Map();
    debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this);
    debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this);
}
WebInspector.DebuggerWorkspaceBinding.TargetData.prototype = {
    _parsedScriptSource: function (event) {
        var script = (event.data);
        this._defaultMapping.addScript(script);
        if (script.isSnippet()) {
            WebInspector.scriptSnippetModel.addScript(script);
            return;
        }
        this._resourceMapping.addScript(script);
        if (WebInspector.settings.jsSourceMapsEnabled.get())
            this._compilerMapping.addScript(script);
    }, _setSourceMapping: function (uiSourceCode, sourceMapping) {
        if (this._uiSourceCodeToSourceMapping.get(uiSourceCode) === sourceMapping)
            return;
        if (sourceMapping)
            this._uiSourceCodeToSourceMapping.put(uiSourceCode, sourceMapping); else
            this._uiSourceCodeToSourceMapping.remove(uiSourceCode);
        uiSourceCode.dispatchEventToListeners(WebInspector.UISourceCode.Events.SourceMappingChanged, {target: this._target, isIdentity: sourceMapping ? sourceMapping.isIdentity() : false});
    }, _uiLocationToRawLocation: function (uiSourceCode, lineNumber, columnNumber) {
        var sourceMapping = this._uiSourceCodeToSourceMapping.get(uiSourceCode);
        return sourceMapping ? sourceMapping.uiLocationToRawLocation(uiSourceCode, lineNumber, columnNumber) : null;
    }, _uiLineHasMapping: function (uiSourceCode, lineNumber) {
        var sourceMapping = this._uiSourceCodeToSourceMapping.get(uiSourceCode);
        return sourceMapping ? sourceMapping.uiLineHasMapping(uiSourceCode, lineNumber) : true;
    }, _uiSourceCodeRemoved: function (uiSourceCode) {
        this._uiSourceCodeToSourceMapping.remove(uiSourceCode);
    }, _dispose: function () {
        this._compilerMapping.dispose();
        this._resourceMapping.dispose();
        this._defaultMapping.dispose();
        this._uiSourceCodeToSourceMapping.clear();
    }
}
WebInspector.DebuggerWorkspaceBinding.ScriptInfo = function (script) {
    this._script = script;
    this._sourceMappings = [];
    this._locations = new Set();
}
WebInspector.DebuggerWorkspaceBinding.ScriptInfo.prototype = {
    _pushSourceMapping: function (sourceMapping) {
        this._sourceMappings.push(sourceMapping);
        this._updateLocations();
    }, _popSourceMapping: function () {
        var sourceMapping = this._sourceMappings.pop();
        this._updateLocations();
        return sourceMapping;
    }, _addLocation: function (location) {
        this._locations.add(location);
        location.update();
    }, _removeLocation: function (location) {
        this._locations.remove(location);
    }, _updateLocations: function () {
        var items = this._locations.values();
        for (var i = 0; i < items.length; ++i)
            items[i].update();
    }, _rawLocationToUILocation: function (rawLocation) {
        var uiLocation;
        for (var i = this._sourceMappings.length - 1; !uiLocation && i >= 0; --i)
            uiLocation = this._sourceMappings[i].rawLocationToUILocation(rawLocation);
        console.assert(uiLocation, "Script raw location cannot be mapped to any UI location.");
        return (uiLocation);
    }
}
WebInspector.DebuggerWorkspaceBinding.Location = function (script, rawLocation, binding, updateDelegate) {
    WebInspector.LiveLocation.call(this, updateDelegate);
    this._script = script;
    this._rawLocation = rawLocation;
    this._binding = binding;
}
WebInspector.DebuggerWorkspaceBinding.Location.prototype = {
    uiLocation: function () {
        var debuggerModelLocation = this._rawLocation;
        return this._binding.rawLocationToUILocation(debuggerModelLocation);
    }, dispose: function () {
        WebInspector.LiveLocation.prototype.dispose.call(this);
        this._binding._removeLiveLocation(this);
    }, __proto__: WebInspector.LiveLocation.prototype
}
WebInspector.DebuggerSourceMapping = function () {
}
WebInspector.DebuggerSourceMapping.prototype = {
    rawLocationToUILocation: function (rawLocation) {
    }, uiLocationToRawLocation: function (uiSourceCode, lineNumber, columnNumber) {
    }, isIdentity: function () {
    }, uiLineHasMapping: function (uiSourceCode, lineNumber) {
    }
}
WebInspector.debuggerWorkspaceBinding;
function SourceMapV3() {
    this.version;
    this.file;
    this.sources;
    this.sections;
    this.mappings;
    this.sourceRoot;
}
SourceMapV3.Section = function () {
    this.map;
    this.offset;
}
SourceMapV3.Offset = function () {
    this.line;
    this.column;
}
WebInspector.SourceMap = function (sourceMappingURL, payload) {
    if (!WebInspector.SourceMap.prototype._base64Map) {
        const base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        WebInspector.SourceMap.prototype._base64Map = {};
        for (var i = 0; i < base64Digits.length; ++i)
            WebInspector.SourceMap.prototype._base64Map[base64Digits.charAt(i)] = i;
    }
    this._sourceMappingURL = sourceMappingURL;
    this._reverseMappingsBySourceURL = {};
    this._mappings = [];
    this._sources = {};
    this._sourceContentByURL = {};
    this._parseMappingPayload(payload);
}
WebInspector.SourceMap.load = function (sourceMapURL, compiledURL, callback) {
    var resourceTreeModel = WebInspector.resourceTreeModel;
    if (resourceTreeModel.cachedResourcesLoaded())
        loadResource(); else
        resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded, cachedResourcesLoaded);
    function cachedResourcesLoaded() {
        resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded, cachedResourcesLoaded);
        loadResource();
    }

    function loadResource() {
        var headers = {};
        NetworkAgent.loadResourceForFrontend(resourceTreeModel.mainFrame.id, sourceMapURL, headers, contentLoaded);
    }

    function contentLoaded(error, statusCode, headers, content) {
        if (error || !content || statusCode >= 400) {
            callback(null);
            return;
        }
        if (content.slice(0, 3) === ")]}")
            content = content.substring(content.indexOf('\n'));
        try {
            var payload = (JSON.parse(content));
            var baseURL = sourceMapURL.startsWith("data:") ? compiledURL : sourceMapURL;
            callback(new WebInspector.SourceMap(baseURL, payload));
        } catch (e) {
            console.error(e.message);
            callback(null);
        }
    }
}
WebInspector.SourceMap.prototype = {
    url: function () {
        return this._sourceMappingURL;
    }, sources: function () {
        return Object.keys(this._sources);
    }, sourceContent: function (sourceURL) {
        return this._sourceContentByURL[sourceURL];
    }, sourceContentProvider: function (sourceURL, contentType) {
        var sourceContent = this.sourceContent(sourceURL);
        if (sourceContent)
            return new WebInspector.StaticContentProvider(contentType, sourceContent);
        return new WebInspector.CompilerSourceMappingContentProvider(sourceURL, contentType);
    }, _parseMappingPayload: function (mappingPayload) {
        if (mappingPayload.sections)
            this._parseSections(mappingPayload.sections); else
            this._parseMap(mappingPayload, 0, 0);
    }, _parseSections: function (sections) {
        for (var i = 0; i < sections.length; ++i) {
            var section = sections[i];
            this._parseMap(section.map, section.offset.line, section.offset.column);
        }
    }, findEntry: function (lineNumber, columnNumber) {
        var first = 0;
        var count = this._mappings.length;
        while (count > 1) {
            var step = count >> 1;
            var middle = first + step;
            var mapping = this._mappings[middle];
            if (lineNumber < mapping[0] || (lineNumber === mapping[0] && columnNumber < mapping[1]))
                count = step; else {
                first = middle;
                count -= step;
            }
        }
        var entry = this._mappings[first];
        if (!first && entry && (lineNumber < entry[0] || (lineNumber === entry[0] && columnNumber < entry[1])))
            return null;
        return entry;
    }, findEntryReversed: function (sourceURL, lineNumber, span) {
        var mappings = this._reverseMappingsBySourceURL[sourceURL];
        var maxLineNumber = typeof span === "number" ? Math.min(lineNumber + span + 1, mappings.length) : mappings.length;
        for (; lineNumber < maxLineNumber; ++lineNumber) {
            var mapping = mappings[lineNumber];
            if (mapping)
                return mapping;
        }
        return null;
    }, _parseMap: function (map, lineNumber, columnNumber) {
        var sourceIndex = 0;
        var sourceLineNumber = 0;
        var sourceColumnNumber = 0;
        var nameIndex = 0;
        var sources = [];
        var originalToCanonicalURLMap = {};
        for (var i = 0; i < map.sources.length; ++i) {
            var originalSourceURL = map.sources[i];
            var sourceRoot = map.sourceRoot || "";
            if (sourceRoot && !sourceRoot.endsWith("/"))
                sourceRoot += "/";
            var href = sourceRoot + originalSourceURL;
            var url = WebInspector.ParsedURL.completeURL(this._sourceMappingURL, href) || href;
            originalToCanonicalURLMap[originalSourceURL] = url;
            sources.push(url);
            this._sources[url] = true;
            if (map.sourcesContent && map.sourcesContent[i])
                this._sourceContentByURL[url] = map.sourcesContent[i];
        }
        var stringCharIterator = new WebInspector.SourceMap.StringCharIterator(map.mappings);
        var sourceURL = sources[sourceIndex];
        while (true) {
            if (stringCharIterator.peek() === ",")
                stringCharIterator.next(); else {
                while (stringCharIterator.peek() === ";") {
                    lineNumber += 1;
                    columnNumber = 0;
                    stringCharIterator.next();
                }
                if (!stringCharIterator.hasNext())
                    break;
            }
            columnNumber += this._decodeVLQ(stringCharIterator);
            if (!stringCharIterator.hasNext() || this._isSeparator(stringCharIterator.peek())) {
                this._mappings.push([lineNumber, columnNumber]);
                continue;
            }
            var sourceIndexDelta = this._decodeVLQ(stringCharIterator);
            if (sourceIndexDelta) {
                sourceIndex += sourceIndexDelta;
                sourceURL = sources[sourceIndex];
            }
            sourceLineNumber += this._decodeVLQ(stringCharIterator);
            sourceColumnNumber += this._decodeVLQ(stringCharIterator);
            if (!this._isSeparator(stringCharIterator.peek()))
                nameIndex += this._decodeVLQ(stringCharIterator);
            this._mappings.push([lineNumber, columnNumber, sourceURL, sourceLineNumber, sourceColumnNumber]);
        }
        for (var i = 0; i < this._mappings.length; ++i) {
            var mapping = this._mappings[i];
            var url = mapping[2];
            if (!url)
                continue;
            if (!this._reverseMappingsBySourceURL[url])
                this._reverseMappingsBySourceURL[url] = [];
            var reverseMappings = this._reverseMappingsBySourceURL[url];
            var sourceLine = mapping[3];
            if (!reverseMappings[sourceLine])
                reverseMappings[sourceLine] = [mapping[0], mapping[1]];
        }
    }, _isSeparator: function (char) {
        return char === "," || char === ";";
    }, _decodeVLQ: function (stringCharIterator) {
        var result = 0;
        var shift = 0;
        do {
            var digit = this._base64Map[stringCharIterator.next()];
            result += (digit & this._VLQ_BASE_MASK) << shift;
            shift += this._VLQ_BASE_SHIFT;
        } while (digit & this._VLQ_CONTINUATION_MASK);
        var negative = result & 1;
        result >>= 1;
        return negative ? -result : result;
    }, _VLQ_BASE_SHIFT: 5, _VLQ_BASE_MASK: (1 << 5) - 1, _VLQ_CONTINUATION_MASK: 1 << 5
}
WebInspector.SourceMap.StringCharIterator = function (string) {
    this._string = string;
    this._position = 0;
}
WebInspector.SourceMap.StringCharIterator.prototype = {
    next: function () {
        return this._string.charAt(this._position++);
    }, peek: function () {
        return this._string.charAt(this._position);
    }, hasNext: function () {
        return this._position < this._string.length;
    }
}
WebInspector.TracingLayerPayload;
WebInspector.LayerTreeModel = function (target) {
    WebInspector.SDKObject.call(this, target);
    target.registerLayerTreeDispatcher(new WebInspector.LayerTreeDispatcher(this));
    target.domModel.addEventListener(WebInspector.DOMModel.Events.DocumentUpdated, this._onDocumentUpdated, this);
    this._layerTree = null;
}
WebInspector.LayerTreeModel.Events = {LayerTreeChanged: "LayerTreeChanged", LayerPainted: "LayerPainted",}
WebInspector.LayerTreeModel.ScrollRectType = {
    NonFastScrollable: {name: "NonFastScrollable", description: "Non fast scrollable"},
    TouchEventHandler: {name: "TouchEventHandler", description: "Touch event handler"},
    WheelEventHandler: {name: "WheelEventHandler", description: "Wheel event handler"},
    RepaintsOnScroll: {name: "RepaintsOnScroll", description: "Repaints on scroll"}
}
WebInspector.LayerTreeModel.prototype = {
    disable: function () {
        if (!this._enabled)
            return;
        this._enabled = false;
        this._layerTree = null;
        this.target().layerTreeAgent().disable();
    }, enable: function () {
        if (this._enabled)
            return;
        this._enabled = true;
        this._layerTree = new WebInspector.AgentLayerTree(this.target());
        this._lastPaintRectByLayerId = {};
        this.target().layerTreeAgent().enable();
    }, setLayerTree: function (layerTree) {
        this.disable();
        this._layerTree = layerTree;
        this.dispatchEventToListeners(WebInspector.LayerTreeModel.Events.LayerTreeChanged);
    }, layerTree: function () {
        return this._layerTree;
    }, _layerTreeChanged: function (layers) {
        if (!this._enabled)
            return;
        var layerTree = (this._layerTree);
        layerTree.setLayers(layers, onLayersSet.bind(this));
        function onLayersSet() {
            for (var layerId in this._lastPaintRectByLayerId) {
                var lastPaintRect = this._lastPaintRectByLayerId[layerId];
                var layer = layerTree.layerById(layerId);
                if (layer)
                    layer._lastPaintRect = lastPaintRect;
            }
            this._lastPaintRectByLayerId = {};
            this.dispatchEventToListeners(WebInspector.LayerTreeModel.Events.LayerTreeChanged);
        }
    }, _layerPainted: function (layerId, clipRect) {
        if (!this._enabled)
            return;
        var layerTree = (this._layerTree);
        var layer = layerTree.layerById(layerId);
        if (!layer) {
            this._lastPaintRectByLayerId[layerId] = clipRect;
            return;
        }
        layer._didPaint(clipRect);
        this.dispatchEventToListeners(WebInspector.LayerTreeModel.Events.LayerPainted, layer);
    }, _onDocumentUpdated: function () {
        if (!this._enabled)
            return;
        this.disable();
        this.enable();
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.LayerTreeBase = function (target) {
    this._target = target;
    this._layersById = {};
    this._backendNodeIdToNodeId = {};
    this._reset();
}
WebInspector.LayerTreeBase.prototype = {
    _reset: function () {
        this._root = null;
        this._contentRoot = null;
    }, root: function () {
        return this._root;
    }, contentRoot: function () {
        return this._contentRoot;
    }, forEachLayer: function (callback, root) {
        if (!root) {
            root = this.root();
            if (!root)
                return false;
        }
        return callback(root) || root.children().some(this.forEachLayer.bind(this, callback));
    }, layerById: function (id) {
        return this._layersById[id] || null;
    }, _resolveBackendNodeIds: function (requestedNodeIds, callback) {
        if (!requestedNodeIds.length || !this._target) {
            callback();
            return;
        }
        this._target.domModel.pushNodesByBackendIdsToFrontend(requestedNodeIds, populateBackendNodeIdMap.bind(this));
        function populateBackendNodeIdMap(nodeIds) {
            if (nodeIds) {
                for (var i = 0; i < requestedNodeIds.length; ++i) {
                    var nodeId = nodeIds[i];
                    if (nodeId)
                        this._backendNodeIdToNodeId[requestedNodeIds[i]] = nodeId;
                }
            }
            callback();
        }
    }, setViewportSize: function (viewportSize) {
        this._viewportSize = viewportSize;
    }, viewportSize: function () {
        return this._viewportSize;
    }, _nodeForId: function (id) {
        return this._target ? this._target.domModel.nodeForId(id) : null;
    }
};
WebInspector.TracingLayerTree = function (target) {
    WebInspector.LayerTreeBase.call(this, target);
}
WebInspector.TracingLayerTree.prototype = {
    setLayers: function (root, callback) {
        var idsToResolve = [];
        this._extractNodeIdsToResolve(idsToResolve, {}, root);
        this._resolveBackendNodeIds(idsToResolve, onBackendNodeIdsResolved.bind(this));
        function onBackendNodeIdsResolved() {
            var oldLayersById = this._layersById;
            this._layersById = {};
            this._contentRoot = null;
            this._root = this._innerSetLayers(oldLayersById, root);
            callback();
        }
    }, _innerSetLayers: function (oldLayersById, payload) {
        var layer = (oldLayersById[payload.layer_id]);
        if (layer)
            layer._reset(payload); else
            layer = new WebInspector.TracingLayer(payload);
        this._layersById[payload.layer_id] = layer;
        if (!this._contentRoot && payload.draws_content)
            this._contentRoot = layer;
        if (payload.owner_node && this._backendNodeIdToNodeId[payload.owner_node])
            layer._setNode(this._nodeForId(this._backendNodeIdToNodeId[payload.owner_node]));
        for (var i = 0; payload.children && i < payload.children.length; ++i)
            layer.addChild(this._innerSetLayers(oldLayersById, payload.children[i]));
        return layer;
    }, _extractNodeIdsToResolve: function (nodeIdsToResolve, seenNodeIds, payload) {
        var backendNodeId = payload.owner_node;
        if (backendNodeId && !seenNodeIds[backendNodeId] && !(this._backendNodeIdToNodeId[backendNodeId] && this._nodeForId(backendNodeId))) {
            seenNodeIds[backendNodeId] = true;
            nodeIdsToResolve.push(backendNodeId);
        }
        for (var i = 0; payload.children && i < payload.children.length; ++i)
            this._extractNodeIdsToResolve(nodeIdsToResolve, seenNodeIds, payload.children[i]);
    }, __proto__: WebInspector.LayerTreeBase.prototype
}
WebInspector.AgentLayerTree = function (target) {
    WebInspector.LayerTreeBase.call(this, target);
}
WebInspector.AgentLayerTree.prototype = {
    setLayers: function (payload, callback) {
        if (!payload) {
            onBackendNodeIdsResolved.call(this);
            return;
        }
        var idsToResolve = {};
        var requestedIds = [];
        for (var i = 0; i < payload.length; ++i) {
            var backendNodeId = payload[i].backendNodeId;
            if (!backendNodeId || idsToResolve[backendNodeId] || (this._backendNodeIdToNodeId[backendNodeId] && this._nodeForId(this._backendNodeIdToNodeId[backendNodeId]))) {
                continue;
            }
            idsToResolve[backendNodeId] = true;
            requestedIds.push(backendNodeId);
        }
        this._resolveBackendNodeIds(requestedIds, onBackendNodeIdsResolved.bind(this));
        function onBackendNodeIdsResolved() {
            this._innerSetLayers(payload);
            callback();
        }
    }, _innerSetLayers: function (layers) {
        this._reset();
        if (!layers)
            return;
        var oldLayersById = this._layersById;
        this._layersById = {};
        for (var i = 0; i < layers.length; ++i) {
            var layerId = layers[i].layerId;
            var layer = oldLayersById[layerId];
            if (layer)
                layer._reset(layers[i]); else
                layer = new WebInspector.AgentLayer(this._target, layers[i]);
            this._layersById[layerId] = layer;
            if (layers[i].backendNodeId) {
                layer._setNode(this._nodeForId(this._backendNodeIdToNodeId[layers[i].backendNodeId]));
                if (!this._contentRoot)
                    this._contentRoot = layer;
            }
            var parentId = layer.parentId();
            if (parentId) {
                var parent = this._layersById[parentId];
                if (!parent)
                    console.assert(parent, "missing parent " + parentId + " for layer " + layerId);
                parent.addChild(layer);
            } else {
                if (this._root)
                    console.assert(false, "Multiple root layers");
                this._root = layer;
            }
        }
        if (this._root)
            this._root._calculateQuad(new WebKitCSSMatrix());
    }, __proto__: WebInspector.LayerTreeBase.prototype
}
WebInspector.Layer = function () {
}
WebInspector.Layer.prototype = {
    id: function () {
    }, parentId: function () {
    }, parent: function () {
    }, isRoot: function () {
    }, children: function () {
    }, addChild: function (child) {
    }, node: function () {
    }, nodeForSelfOrAncestor: function () {
    }, offsetX: function () {
    }, offsetY: function () {
    }, width: function () {
    }, height: function () {
    }, transform: function () {
    }, quad: function () {
    }, anchorPoint: function () {
    }, invisible: function () {
    }, paintCount: function () {
    }, lastPaintRect: function () {
    }, scrollRects: function () {
    }, requestCompositingReasons: function (callback) {
    }, requestSnapshot: function (callback) {
    },
}
WebInspector.AgentLayer = function (target, layerPayload) {
    this._target = target;
    this._reset(layerPayload);
}
WebInspector.AgentLayer.prototype = {
    id: function () {
        return this._layerPayload.layerId;
    }, parentId: function () {
        return this._layerPayload.parentLayerId;
    }, parent: function () {
        return this._parent;
    }, isRoot: function () {
        return !this.parentId();
    }, children: function () {
        return this._children;
    }, addChild: function (child) {
        if (child._parent)
            console.assert(false, "Child already has a parent");
        this._children.push(child);
        child._parent = this;
    }, _setNode: function (node) {
        this._node = node;
    }, node: function () {
        return this._node;
    }, nodeForSelfOrAncestor: function () {
        for (var layer = this; layer; layer = layer._parent) {
            if (layer._node)
                return layer._node;
        }
        return null;
    }, offsetX: function () {
        return this._layerPayload.offsetX;
    }, offsetY: function () {
        return this._layerPayload.offsetY;
    }, width: function () {
        return this._layerPayload.width;
    }, height: function () {
        return this._layerPayload.height;
    }, transform: function () {
        return this._layerPayload.transform;
    }, quad: function () {
        return this._quad;
    }, anchorPoint: function () {
        return [this._layerPayload.anchorX || 0, this._layerPayload.anchorY || 0, this._layerPayload.anchorZ || 0,];
    }, invisible: function () {
        return this._layerPayload.invisible;
    }, paintCount: function () {
        return this._paintCount || this._layerPayload.paintCount;
    }, lastPaintRect: function () {
        return this._lastPaintRect;
    }, scrollRects: function () {
        return this._scrollRects;
    }, requestCompositingReasons: function (callback) {
        if (!this._target) {
            callback([]);
            return;
        }
        var wrappedCallback = InspectorBackend.wrapClientCallback(callback, "LayerTreeAgent.reasonsForCompositingLayer(): ", undefined, []);
        this._target.layerTreeAgent().compositingReasons(this.id(), wrappedCallback);
    }, requestSnapshot: function (callback) {
        if (!this._target) {
            callback();
            return;
        }
        var wrappedCallback = InspectorBackend.wrapClientCallback(callback, "LayerTreeAgent.makeSnapshot(): ", WebInspector.PaintProfilerSnapshot.bind(null, this._target));
        this._target.layerTreeAgent().makeSnapshot(this.id(), wrappedCallback);
    }, _didPaint: function (rect) {
        this._lastPaintRect = rect;
        this._paintCount = this.paintCount() + 1;
        this._image = null;
    }, _reset: function (layerPayload) {
        this._node = null;
        this._children = [];
        this._parent = null;
        this._paintCount = 0;
        this._layerPayload = layerPayload;
        this._image = null;
        this._scrollRects = this._layerPayload.scrollRects || [];
    }, _matrixFromArray: function (a) {
        function toFixed9(x) {
            return x.toFixed(9);
        }

        return new WebKitCSSMatrix("matrix3d(" + a.map(toFixed9).join(",") + ")");
    }, _calculateTransformToViewport: function (parentTransform) {
        var offsetMatrix = new WebKitCSSMatrix().translate(this._layerPayload.offsetX, this._layerPayload.offsetY);
        var matrix = offsetMatrix;
        if (this._layerPayload.transform) {
            var transformMatrix = this._matrixFromArray(this._layerPayload.transform);
            var anchorVector = new WebInspector.Geometry.Vector(this._layerPayload.width * this.anchorPoint()[0], this._layerPayload.height * this.anchorPoint()[1], this.anchorPoint()[2]);
            var anchorPoint = WebInspector.Geometry.multiplyVectorByMatrixAndNormalize(anchorVector, matrix);
            var anchorMatrix = new WebKitCSSMatrix().translate(-anchorPoint.x, -anchorPoint.y, -anchorPoint.z);
            matrix = anchorMatrix.inverse().multiply(transformMatrix.multiply(anchorMatrix.multiply(matrix)));
        }
        matrix = parentTransform.multiply(matrix);
        return matrix;
    }, _createVertexArrayForRect: function (width, height) {
        return [0, 0, 0, width, 0, 0, width, height, 0, 0, height, 0];
    }, _calculateQuad: function (parentTransform) {
        var matrix = this._calculateTransformToViewport(parentTransform);
        this._quad = [];
        var vertices = this._createVertexArrayForRect(this._layerPayload.width, this._layerPayload.height);
        for (var i = 0; i < 4; ++i) {
            var point = WebInspector.Geometry.multiplyVectorByMatrixAndNormalize(new WebInspector.Geometry.Vector(vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]), matrix);
            this._quad.push(point.x, point.y);
        }
        function calculateQuadForLayer(layer) {
            layer._calculateQuad(matrix);
        }

        this._children.forEach(calculateQuadForLayer);
    }
}
WebInspector.TracingLayer = function (payload) {
    this._reset(payload);
}
WebInspector.TracingLayer.prototype = {
    _reset: function (payload) {
        this._node = null;
        this._layerId = String(payload.layer_id);
        this._offsetX = payload.position[0];
        this._offsetY = payload.position[1];
        this._width = payload.bounds.width;
        this._height = payload.bounds.height;
        this._children = [];
        this._parentLayerId = null;
        this._parent = null;
        this._quad = payload.layer_quad || [];
        this._createScrollRects(payload);
    }, id: function () {
        return this._layerId;
    }, parentId: function () {
        return this._parentLayerId;
    }, parent: function () {
        return this._parent;
    }, isRoot: function () {
        return !this.parentId();
    }, children: function () {
        return this._children;
    }, addChild: function (child) {
        if (child._parent)
            console.assert(false, "Child already has a parent");
        this._children.push(child);
        child._parent = this;
        child._parentLayerId = this._layerId;
    }, _setNode: function (node) {
        this._node = node;
    }, node: function () {
        return this._node;
    }, nodeForSelfOrAncestor: function () {
        for (var layer = this; layer; layer = layer._parent) {
            if (layer._node)
                return layer._node;
        }
        return null;
    }, offsetX: function () {
        return this._offsetX;
    }, offsetY: function () {
        return this._offsetY;
    }, width: function () {
        return this._width;
    }, height: function () {
        return this._height;
    }, transform: function () {
        return null;
    }, quad: function () {
        return this._quad;
    }, anchorPoint: function () {
        return [0.5, 0.5, 0];
    }, invisible: function () {
        return false;
    }, paintCount: function () {
        return 0;
    }, lastPaintRect: function () {
        return null;
    }, scrollRects: function () {
        return this._scrollRects;
    }, _scrollRectsFromParams: function (params, type) {
        return {rect: {x: params[0], y: params[1], width: params[2], height: params[3]}, type: type};
    }, _createScrollRects: function (payload) {
        this._scrollRects = [];
        if (payload.non_fast_scrollable_region)
            this._scrollRects.push(this._scrollRectsFromParams(payload.non_fast_scrollable_region, WebInspector.LayerTreeModel.ScrollRectType.NonFastScrollable.name));
        if (payload.touch_event_handler_region)
            this._scrollRects.push(this._scrollRectsFromParams(payload.touch_event_handler_region, WebInspector.LayerTreeModel.ScrollRectType.TouchEventHandler.name));
        if (payload.wheel_event_handler_region)
            this._scrollRects.push(this._scrollRectsFromParams(payload.wheel_event_handler_region, WebInspector.LayerTreeModel.ScrollRectType.WheelEventHandler.name));
        if (payload.scroll_event_handler_region)
            this._scrollRects.push(this._scrollRectsFromParams(payload.scroll_event_handler_region, WebInspector.LayerTreeModel.ScrollRectType.RepaintsOnScroll.name));
    }, requestCompositingReasons: function (callback) {
        var wrappedCallback = InspectorBackend.wrapClientCallback(callback, "LayerTreeAgent.reasonsForCompositingLayer(): ", undefined, []);
        LayerTreeAgent.compositingReasons(this.id(), wrappedCallback);
    }, requestSnapshot: function (callback) {
        var wrappedCallback = InspectorBackend.wrapClientCallback(callback, "LayerTreeAgent.makeSnapshot(): ", WebInspector.PaintProfilerSnapshot);
        LayerTreeAgent.makeSnapshot(this.id(), wrappedCallback);
    }
}
WebInspector.DeferredLayerTree = function (target) {
    this._target = target;
}
WebInspector.DeferredLayerTree.prototype = {
    resolve: function (callback) {
    }, target: function () {
        return this._target;
    }
};
WebInspector.DeferredAgentLayerTree = function (target, layers) {
    WebInspector.DeferredLayerTree.call(this, target);
    this._layers = layers;
}
WebInspector.DeferredAgentLayerTree.prototype = {
    resolve: function (callback) {
        var result = new WebInspector.AgentLayerTree(this._target);
        result.setLayers(this._layers, callback.bind(null, result));
    }, __proto__: WebInspector.DeferredLayerTree.prototype
};
WebInspector.DeferredTracingLayerTree = function (target, root, viewportSize) {
    WebInspector.DeferredLayerTree.call(this, target);
    this._root = root;
    this._viewportSize = viewportSize;
}
WebInspector.DeferredTracingLayerTree.prototype = {
    resolve: function (callback) {
        var result = new WebInspector.TracingLayerTree(this._target);
        result.setViewportSize(this._viewportSize);
        result.setLayers(this._root, callback.bind(null, result));
    }, __proto__: WebInspector.DeferredLayerTree.prototype
};
WebInspector.LayerTreeDispatcher = function (layerTreeModel) {
    this._layerTreeModel = layerTreeModel;
}
WebInspector.LayerTreeDispatcher.prototype = {
    layerTreeDidChange: function (layers) {
        this._layerTreeModel._layerTreeChanged(layers || null);
    }, layerPainted: function (layerId, clipRect) {
        this._layerTreeModel._layerPainted(layerId, clipRect);
    }
}
WebInspector.Script = function (target, scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, sourceMapURL, hasSourceURL, contextData) {
    WebInspector.SDKObject.call(this, target);
    this.scriptId = scriptId;
    this.sourceURL = sourceURL;
    this.lineOffset = startLine;
    this.columnOffset = startColumn;
    this.endLine = endLine;
    this.endColumn = endColumn;
    this._isContentScript = isContentScript;
    this.sourceMapURL = sourceMapURL;
    this.hasSourceURL = hasSourceURL;
    this._contextData = contextData;
}
WebInspector.Script.Events = {ScriptEdited: "ScriptEdited", SourceMapURLAdded: "SourceMapURLAdded",}
WebInspector.Script.snippetSourceURLPrefix = "snippets:///";
WebInspector.Script.sourceURLRegex = /\n[\040\t]*\/\/[@#]\ssourceURL=\s*(\S*?)\s*$/mg;
WebInspector.Script._trimSourceURLComment = function (source) {
    return source.replace(WebInspector.Script.sourceURLRegex, "");
}
WebInspector.Script.prototype = {
    isContentScript: function () {
        return this._isContentScript;
    }, contentURL: function () {
        return this.sourceURL;
    }, contentType: function () {
        return WebInspector.resourceTypes.Script;
    }, requestContent: function (callback) {
        if (this._source) {
            callback(this._source);
            return;
        }
        function didGetScriptSource(error, source) {
            this._source = WebInspector.Script._trimSourceURLComment(error ? "" : source);
            callback(this._source);
        }

        if (this.scriptId) {
            this.target().debuggerAgent().getScriptSource(this.scriptId, didGetScriptSource.bind(this));
        } else
            callback("");
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        function innerCallback(error, searchMatches) {
            if (error)
                console.error(error);
            var result = [];
            for (var i = 0; i < searchMatches.length; ++i) {
                var searchMatch = new WebInspector.ContentProvider.SearchMatch(searchMatches[i].lineNumber, searchMatches[i].lineContent);
                result.push(searchMatch);
            }
            callback(result || []);
        }

        if (this.scriptId) {
            this.target().debuggerAgent().searchInContent(this.scriptId, query, caseSensitive, isRegex, innerCallback);
        } else {
            callback([]);
        }
    }, _appendSourceURLCommentIfNeeded: function (source) {
        if (!this.hasSourceURL)
            return source;
        return source + "\n //# sourceURL=" + this.sourceURL;
    }, editSource: function (newSource, callback) {
        function didEditScriptSource(error, errorData, callFrames, debugData, asyncStackTrace) {
            if (!error)
                this._source = newSource;
            var needsStepIn = !!debugData && debugData["stack_update_needs_step_in"] === true;
            callback(error, errorData, callFrames, asyncStackTrace, needsStepIn);
            if (!error)
                this.dispatchEventToListeners(WebInspector.Script.Events.ScriptEdited, newSource);
        }

        newSource = WebInspector.Script._trimSourceURLComment(newSource);
        newSource = this._appendSourceURLCommentIfNeeded(newSource);
        if (this.scriptId)
            this.target().debuggerAgent().setScriptSource(this.scriptId, newSource, undefined, didEditScriptSource.bind(this)); else
            callback("Script failed to parse");
    }, rawLocation: function (lineNumber, columnNumber) {
        return new WebInspector.DebuggerModel.Location(this.target(), this.scriptId, lineNumber, columnNumber || 0);
    }, isInlineScript: function () {
        var startsAtZero = !this.lineOffset && !this.columnOffset;
        return !!this.sourceURL && !startsAtZero;
    }, addSourceMapURL: function (sourceMapURL) {
        if (this.sourceMapURL)
            return;
        this.sourceMapURL = sourceMapURL;
        this.dispatchEventToListeners(WebInspector.Script.Events.SourceMapURLAdded, this.sourceMapURL);
    }, isAnonymousScript: function () {
        return !this.sourceURL;
    }, isSnippet: function () {
        return !!this.sourceURL && this.sourceURL.startsWith(WebInspector.Script.snippetSourceURLPrefix);
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.LinkifierFormatter = function () {
}
WebInspector.LinkifierFormatter.prototype = {
    formatLiveAnchor: function (anchor, uiLocation) {
    }
}
WebInspector.Linkifier = function (formatter) {
    this._formatter = formatter || new WebInspector.Linkifier.DefaultFormatter(WebInspector.Linkifier.MaxLengthForDisplayedURLs);
    this._liveLocationsByTarget = new Map();
    WebInspector.targetManager.observeTargets(this);
}
WebInspector.Linkifier.setLinkHandler = function (handler) {
    WebInspector.Linkifier._linkHandler = handler;
}
WebInspector.Linkifier.handleLink = function (url, lineNumber) {
    if (!WebInspector.Linkifier._linkHandler)
        return false;
    return WebInspector.Linkifier._linkHandler.handleLink(url, lineNumber)
}
WebInspector.Linkifier.linkifyUsingRevealer = function (revealable, text, fallbackHref, fallbackLineNumber, title, classes) {
    var a = document.createElement("a");
    a.className = (classes || "") + " webkit-html-resource-link";
    a.textContent = text.trimMiddle(WebInspector.Linkifier.MaxLengthForDisplayedURLs);
    a.title = title || text;
    if (fallbackHref) {
        a.href = fallbackHref;
        a.lineNumber = fallbackLineNumber;
    }
    function clickHandler(event) {
        event.stopImmediatePropagation();
        event.preventDefault();
        if (fallbackHref && WebInspector.Linkifier.handleLink(fallbackHref, fallbackLineNumber))
            return;
        WebInspector.Revealer.reveal(this);
    }

    a.addEventListener("click", clickHandler.bind(revealable), false);
    return a;
}
WebInspector.Linkifier.prototype = {
    targetAdded: function (target) {
        this._liveLocationsByTarget.put(target, []);
    }, targetRemoved: function (target) {
        var liveLocations = this._liveLocationsByTarget.remove(target);
        for (var i = 0; i < liveLocations.length; ++i) {
            delete liveLocations[i].anchor.__uiLocation;
            var anchor = liveLocations[i].anchor;
            if (anchor.__fallbackAnchor) {
                anchor.href = anchor.__fallbackAnchor.href;
                anchor.lineNumber = anchor.__fallbackAnchor.lineNumber;
                anchor.title = anchor.__fallbackAnchor.title;
                anchor.className = anchor.__fallbackAnchor.className;
                anchor.textContent = anchor.__fallbackAnchor.textContent;
            }
            liveLocations[i].location.dispose();
        }
    }, linkifyScriptLocation: function (target, scriptId, sourceURL, lineNumber, columnNumber, classes) {
        var rawLocation = target && !target.isDetached() ? target.debuggerModel.createRawLocationByScriptId(scriptId, sourceURL, lineNumber, columnNumber || 0) : null;
        var fallbackAnchor = WebInspector.linkifyResourceAsNode(sourceURL, lineNumber, classes);
        if (!rawLocation)
            return fallbackAnchor;
        var anchor = this._createAnchor(classes);
        var liveLocation = WebInspector.debuggerWorkspaceBinding.createLiveLocation(rawLocation, this._updateAnchor.bind(this, anchor));
        this._liveLocationsByTarget.get(rawLocation.target()).push({anchor: anchor, location: liveLocation});
        anchor.__fallbackAnchor = fallbackAnchor;
        return anchor;
    }, linkifyRawLocation: function (rawLocation, fallbackUrl, classes) {
        return this.linkifyScriptLocation(rawLocation.target(), rawLocation.scriptId, fallbackUrl, rawLocation.lineNumber, rawLocation.columnNumber, classes);
    }, linkifyConsoleCallFrame: function (target, callFrame, classes) {
        var lineNumber = callFrame.lineNumber ? callFrame.lineNumber - 1 : 0;
        var columnNumber = callFrame.columnNumber ? callFrame.columnNumber - 1 : 0;
        var anchor = this.linkifyScriptLocation(target, callFrame.scriptId, callFrame.url, lineNumber, columnNumber, classes);
        if (WebInspector.BlackboxSupport.isBlackboxedURL(callFrame.url))
            anchor.classList.add("webkit-html-blackbox-link");
        return anchor;
    }, linkifyCSSLocation: function (rawLocation, classes) {
        var anchor = this._createAnchor(classes);
        var liveLocation = WebInspector.cssWorkspaceBinding.createLiveLocation(rawLocation, this._updateAnchor.bind(this, anchor));
        if (!liveLocation)
            return null;
        this._liveLocationsByTarget.get(rawLocation.target()).push({anchor: anchor, location: liveLocation});
        return anchor;
    }, linkifyMedia: function (media) {
        var location = media.rawLocation();
        if (location)
            return this.linkifyCSSLocation(location);
        return WebInspector.linkifyResourceAsNode(media.sourceURL, undefined, "subtitle", media.sourceURL);
    }, _createAnchor: function (classes) {
        var anchor = document.createElement("a");
        anchor.className = (classes || "") + " webkit-html-resource-link";
        function clickHandler(event) {
            if (!anchor.__uiLocation)
                return;
            event.stopImmediatePropagation();
            event.preventDefault();
            if (WebInspector.Linkifier.handleLink(anchor.__uiLocation.uiSourceCode.url, anchor.__uiLocation.lineNumber))
                return;
            WebInspector.Revealer.reveal(anchor.__uiLocation);
        }

        anchor.addEventListener("click", clickHandler, false);
        return anchor;
    }, reset: function () {
        var keys = this._liveLocationsByTarget.keys();
        for (var i = 0; i < keys.length; ++i) {
            var target = keys[i];
            this.targetRemoved(target);
            this.targetAdded(target);
        }
    }, _updateAnchor: function (anchor, uiLocation) {
        anchor.__uiLocation = uiLocation;
        this._formatter.formatLiveAnchor(anchor, uiLocation);
    }
}
WebInspector.Linkifier.DefaultFormatter = function (maxLength) {
    this._maxLength = maxLength;
}
WebInspector.Linkifier.DefaultFormatter.prototype = {
    formatLiveAnchor: function (anchor, uiLocation) {
        var text = uiLocation.linkText();
        if (this._maxLength)
            text = text.trimMiddle(this._maxLength);
        anchor.textContent = text;
        var titleText = uiLocation.uiSourceCode.originURL();
        if (typeof uiLocation.lineNumber === "number")
            titleText += ":" + (uiLocation.lineNumber + 1);
        anchor.title = titleText;
    }
}
WebInspector.Linkifier.DefaultCSSFormatter = function () {
    WebInspector.Linkifier.DefaultFormatter.call(this, WebInspector.Linkifier.DefaultCSSFormatter.MaxLengthForDisplayedURLs);
}
WebInspector.Linkifier.DefaultCSSFormatter.MaxLengthForDisplayedURLs = 30;
WebInspector.Linkifier.DefaultCSSFormatter.prototype = {
    formatLiveAnchor: function (anchor, uiLocation) {
        WebInspector.Linkifier.DefaultFormatter.prototype.formatLiveAnchor.call(this, anchor, uiLocation);
        anchor.classList.add("webkit-html-resource-link");
        anchor.setAttribute("data-uncopyable", anchor.textContent);
        anchor.textContent = "";
    }, __proto__: WebInspector.Linkifier.DefaultFormatter.prototype
}
WebInspector.Linkifier.MaxLengthForDisplayedURLs = 150;
WebInspector.Linkifier.LinkHandler = function () {
}
WebInspector.Linkifier.LinkHandler.prototype = {
    handleLink: function (url, lineNumber) {
    }
}
WebInspector.Linkifier.liveLocationText = function (target, scriptId, lineNumber, columnNumber) {
    var script = target.debuggerModel.scriptForId(scriptId);
    if (!script)
        return "";
    var location = (target.debuggerModel.createRawLocation(script, lineNumber, columnNumber || 0));
    var uiLocation = (WebInspector.debuggerWorkspaceBinding.rawLocationToUILocation(location));
    return uiLocation.linkText();
}
WebInspector.PresentationConsoleMessageHelper = function (workspace) {
    this._pendingConsoleMessages = {};
    this._presentationConsoleMessages = [];
    this._workspace = workspace;
    WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._consoleCleared, this);
    WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, this._onConsoleMessageAdded, this);
    WebInspector.multitargetConsoleModel.messages().forEach(this._consoleMessageAdded, this);
    WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this);
    WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this);
    WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
}
WebInspector.PresentationConsoleMessageHelper.prototype = {
    _onConsoleMessageAdded: function (event) {
        var message = (event.data);
        this._consoleMessageAdded(message)
    }, _consoleMessageAdded: function (message) {
        if (!message.url || !message.isErrorOrWarning())
            return;
        var rawLocation = this._rawLocation(message);
        if (rawLocation)
            this._addConsoleMessageToScript(message, rawLocation); else
            this._addPendingConsoleMessage(message);
    }, _rawLocation: function (message) {
        var lineNumber = message.stackTrace ? message.stackTrace[0].lineNumber - 1 : message.line - 1;
        var columnNumber = message.stackTrace && message.stackTrace[0].columnNumber ? message.stackTrace[0].columnNumber - 1 : 0;
        return message.target().debuggerModel.createRawLocationByURL(message.url || "", lineNumber, columnNumber);
    }, _addConsoleMessageToScript: function (message, rawLocation) {
        this._presentationConsoleMessages.push(new WebInspector.PresentationConsoleMessage(message, rawLocation));
    }, _addPendingConsoleMessage: function (message) {
        if (!message.url)
            return;
        if (!this._pendingConsoleMessages[message.url])
            this._pendingConsoleMessages[message.url] = [];
        this._pendingConsoleMessages[message.url].push(message);
    }, _parsedScriptSource: function (event) {
        var script = (event.data);
        var messages = this._pendingConsoleMessages[script.sourceURL];
        if (!messages)
            return;
        var pendingMessages = [];
        for (var i = 0; i < messages.length; i++) {
            var message = messages[i];
            var rawLocation = this._rawLocation(message);
            if (script.target() === message.target() && script.scriptId === rawLocation.scriptId)
                this._addConsoleMessageToScript(message, rawLocation); else
                pendingMessages.push(message);
        }
        if (pendingMessages.length)
            this._pendingConsoleMessages[script.sourceURL] = pendingMessages; else
            delete this._pendingConsoleMessages[script.sourceURL];
    }, _consoleCleared: function () {
        this._pendingConsoleMessages = {};
        for (var i = 0; i < this._presentationConsoleMessages.length; ++i)
            this._presentationConsoleMessages[i].dispose();
        this._presentationConsoleMessages = [];
        var uiSourceCodes = this._workspace.uiSourceCodes();
        for (var i = 0; i < uiSourceCodes.length; ++i)
            uiSourceCodes[i].consoleMessagesCleared();
    }, _debuggerReset: function () {
        this._pendingConsoleMessages = {};
        this._presentationConsoleMessages = [];
    }
}
WebInspector.PresentationConsoleMessage = function (message, rawLocation) {
    this.originalMessage = message;
    this._liveLocation = WebInspector.debuggerWorkspaceBinding.createLiveLocation(rawLocation, this._updateLocation.bind(this));
}
WebInspector.PresentationConsoleMessage.prototype = {
    _updateLocation: function (uiLocation) {
        if (this._uiLocation)
            this._uiLocation.uiSourceCode.consoleMessageRemoved(this);
        this._uiLocation = uiLocation;
        this._uiLocation.uiSourceCode.consoleMessageAdded(this);
    }, get lineNumber() {
        return this._uiLocation.lineNumber;
    }, dispose: function () {
        this._liveLocation.dispose();
    }
}
WebInspector.FileSystemWorkspaceBinding = function (isolatedFileSystemManager, workspace) {
    this._isolatedFileSystemManager = isolatedFileSystemManager;
    this._workspace = workspace;
    this._isolatedFileSystemManager.addEventListener(WebInspector.IsolatedFileSystemManager.Events.FileSystemAdded, this._fileSystemAdded, this);
    this._isolatedFileSystemManager.addEventListener(WebInspector.IsolatedFileSystemManager.Events.FileSystemRemoved, this._fileSystemRemoved, this);
    this._boundFileSystems = new StringMap();
    this._callbacks = {};
    this._progresses = {};
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingTotalWorkCalculated, this._onIndexingTotalWorkCalculated, this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingWorked, this._onIndexingWorked, this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.IndexingDone, this._onIndexingDone, this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SearchCompleted, this._onSearchCompleted, this);
}
WebInspector.FileSystemWorkspaceBinding._scriptExtensions = ["js", "java", "coffee", "ts", "dart"].keySet();
WebInspector.FileSystemWorkspaceBinding._styleSheetExtensions = ["css", "scss", "sass", "less"].keySet();
WebInspector.FileSystemWorkspaceBinding._documentExtensions = ["htm", "html", "asp", "aspx", "phtml", "jsp"].keySet();
WebInspector.FileSystemWorkspaceBinding._lastRequestId = 0;
WebInspector.FileSystemWorkspaceBinding.projectId = function (fileSystemPath) {
    return "filesystem:" + fileSystemPath;
}
WebInspector.FileSystemWorkspaceBinding.prototype = {
    _fileSystemAdded: function (event) {
        var fileSystem = (event.data);
        var boundFileSystem = new WebInspector.FileSystemWorkspaceBinding.FileSystem(this, fileSystem, this._workspace);
        this._boundFileSystems.put(fileSystem.normalizedPath(), boundFileSystem);
    }, _fileSystemRemoved: function (event) {
        var fileSystem = (event.data);
        var boundFileSystem = this._boundFileSystems.get(fileSystem.normalizedPath());
        boundFileSystem.dispose();
        this._boundFileSystems.remove(fileSystem.normalizedPath());
    }, fileSystemPath: function (projectId) {
        var fileSystemPath = projectId.substr("filesystem:".length);
        var normalizedPath = WebInspector.IsolatedFileSystem.normalizePath(fileSystemPath);
        var boundFileSystem = this._boundFileSystems.get(normalizedPath);
        return projectId.substr("filesystem:".length);
    }, _nextId: function () {
        return ++WebInspector.FileSystemWorkspaceBinding._lastRequestId;
    }, registerCallback: function (callback) {
        var requestId = this._nextId();
        this._callbacks[requestId] = callback;
        return requestId;
    }, registerProgress: function (progress) {
        var requestId = this._nextId();
        this._progresses[requestId] = progress;
        return requestId;
    }, _onIndexingTotalWorkCalculated: function (event) {
        var requestId = (event.data["requestId"]);
        var fileSystemPath = (event.data["fileSystemPath"]);
        var totalWork = (event.data["totalWork"]);
        var progress = this._progresses[requestId];
        if (!progress)
            return;
        progress.setTotalWork(totalWork);
    }, _onIndexingWorked: function (event) {
        var requestId = (event.data["requestId"]);
        var fileSystemPath = (event.data["fileSystemPath"]);
        var worked = (event.data["worked"]);
        var progress = this._progresses[requestId];
        if (!progress)
            return;
        progress.worked(worked);
    }, _onIndexingDone: function (event) {
        var requestId = (event.data["requestId"]);
        var fileSystemPath = (event.data["fileSystemPath"]);
        var progress = this._progresses[requestId];
        if (!progress)
            return;
        progress.done();
        delete this._progresses[requestId];
    }, _onSearchCompleted: function (event) {
        var requestId = (event.data["requestId"]);
        var fileSystemPath = (event.data["fileSystemPath"]);
        var files = (event.data["files"]);
        var callback = this._callbacks[requestId];
        if (!callback)
            return;
        callback.call(null, files);
        delete this._callbacks[requestId];
    },
}
WebInspector.FileSystemWorkspaceBinding.FileSystem = function (fileSystemWorkspaceBinding, isolatedFileSystem, workspace) {
    this._fileSystemWorkspaceBinding = fileSystemWorkspaceBinding;
    this._fileSystem = isolatedFileSystem;
    this._fileSystemURL = "file://" + this._fileSystem.normalizedPath() + "/";
    this._workspace = workspace;
    this._projectId = WebInspector.FileSystemWorkspaceBinding.projectId(this._fileSystem.path());
    console.assert(!this._workspace.project(this._projectId));
    this._projectStore = this._workspace.addProject(this._projectId, this);
    this.populate();
}
WebInspector.FileSystemWorkspaceBinding.FileSystem.prototype = {
    type: function () {
        return WebInspector.projectTypes.FileSystem;
    }, fileSystemPath: function () {
        return this._fileSystem.path();
    }, displayName: function () {
        var normalizedPath = this._fileSystem.normalizedPath();
        return normalizedPath.substr(normalizedPath.lastIndexOf("/") + 1);
    }, _filePathForPath: function (path) {
        return "/" + path;
    }, requestFileContent: function (path, callback) {
        var filePath = this._filePathForPath(path);
        this._fileSystem.requestFileContent(filePath, callback);
    }, requestMetadata: function (path, callback) {
        var filePath = this._filePathForPath(path);
        this._fileSystem.requestMetadata(filePath, callback);
    }, canSetFileContent: function () {
        return true;
    }, setFileContent: function (path, newContent, callback) {
        var filePath = this._filePathForPath(path);
        this._fileSystem.setFileContent(filePath, newContent, callback.bind(this, ""));
    }, canRename: function () {
        return true;
    }, rename: function (path, newName, callback) {
        var filePath = this._filePathForPath(path);
        this._fileSystem.renameFile(filePath, newName, innerCallback.bind(this));
        function innerCallback(success, newName) {
            if (!success) {
                callback(false, newName);
                return;
            }
            var validNewName = (newName);
            console.assert(validNewName);
            var slash = filePath.lastIndexOf("/");
            var parentPath = filePath.substring(0, slash);
            filePath = parentPath + "/" + validNewName;
            filePath = filePath.substr(1);
            var newURL = this._workspace.urlForPath(this._fileSystem.path(), filePath);
            var extension = this._extensionForPath(validNewName);
            var newOriginURL = this._fileSystemURL + filePath
            var newContentType = this._contentTypeForExtension(extension);
            callback(true, validNewName, newURL, newOriginURL, newContentType);
        }
    }, searchInFileContent: function (path, query, caseSensitive, isRegex, callback) {
        var filePath = this._filePathForPath(path);
        this._fileSystem.requestFileContent(filePath, contentCallback);
        function contentCallback(content) {
            var result = [];
            if (content !== null)
                result = WebInspector.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex);
            callback(result);
        }
    }, findFilesMatchingSearchRequest: function (searchConfig, filesMathingFileQuery, progress, callback) {
        var result = filesMathingFileQuery;
        var queriesToRun = searchConfig.queries().slice();
        if (!queriesToRun.length)
            queriesToRun.push("");
        progress.setTotalWork(queriesToRun.length);
        searchNextQuery.call(this);
        function searchNextQuery() {
            if (!queriesToRun.length) {
                progress.done();
                callback(result);
                return;
            }
            var query = queriesToRun.shift();
            this._searchInPath(searchConfig.isRegex() ? "" : query, progress, innerCallback.bind(this));
        }

        function innerCallback(files) {
            files = files.sort();
            progress.worked(1);
            result = result.intersectOrdered(files, String.naturalOrderComparator);
            searchNextQuery.call(this);
        }
    }, _searchInPath: function (query, progress, callback) {
        var requestId = this._fileSystemWorkspaceBinding.registerCallback(innerCallback.bind(this));
        InspectorFrontendHost.searchInPath(requestId, this._fileSystem.path(), query);
        function innerCallback(files) {
            function trimAndNormalizeFileSystemPath(fullPath) {
                var trimmedPath = fullPath.substr(this._fileSystem.path().length + 1);
                if (WebInspector.isWin())
                    trimmedPath = trimmedPath.replace(/\\/g, "/");
                return trimmedPath;
            }

            files = files.map(trimAndNormalizeFileSystemPath.bind(this));
            progress.worked(1);
            callback(files);
        }
    }, indexContent: function (progress) {
        progress.setTotalWork(1);
        var requestId = this._fileSystemWorkspaceBinding.registerProgress(progress);
        progress.addEventListener(WebInspector.Progress.Events.Canceled, this._indexingCanceled.bind(this, requestId));
        InspectorFrontendHost.indexPath(requestId, this._fileSystem.path());
    }, _indexingCanceled: function (requestId) {
        InspectorFrontendHost.stopIndexing(requestId);
    }, _extensionForPath: function (path) {
        var extensionIndex = path.lastIndexOf(".");
        if (extensionIndex === -1)
            return "";
        return path.substring(extensionIndex + 1).toLowerCase();
    }, _contentTypeForExtension: function (extension) {
        if (WebInspector.FileSystemWorkspaceBinding._scriptExtensions[extension])
            return WebInspector.resourceTypes.Script;
        if (WebInspector.FileSystemWorkspaceBinding._styleSheetExtensions[extension])
            return WebInspector.resourceTypes.Stylesheet;
        if (WebInspector.FileSystemWorkspaceBinding._documentExtensions[extension])
            return WebInspector.resourceTypes.Document;
        return WebInspector.resourceTypes.Other;
    }, populate: function () {
        this._fileSystem.requestFilesRecursive("", this._addFile.bind(this));
    }, refresh: function (path, callback) {
        this._fileSystem.requestFilesRecursive(path, this._addFile.bind(this), callback);
    }, excludeFolder: function (path) {
        this._fileSystemWorkspaceBinding._isolatedFileSystemManager.mapping().addExcludedFolder(this._fileSystem.path(), path);
    }, createFile: function (path, name, content, callback) {
        this._fileSystem.createFile(path, name, innerCallback.bind(this));
        var createFilePath;

        function innerCallback(filePath) {
            if (!filePath) {
                callback(null);
                return;
            }
            createFilePath = filePath;
            if (!content) {
                contentSet.call(this);
                return;
            }
            this._fileSystem.setFileContent(filePath, content, contentSet.bind(this));
        }

        function contentSet() {
            this._addFile(createFilePath);
            callback(createFilePath);
        }
    }, deleteFile: function (path) {
        this._fileSystem.deleteFile(path);
        this._removeFile(path);
    }, remove: function () {
        this._fileSystemWorkspaceBinding._isolatedFileSystemManager.removeFileSystem(this._fileSystem.path());
    }, _addFile: function (filePath) {
        if (!filePath)
            console.assert(false);
        var slash = filePath.lastIndexOf("/");
        var parentPath = filePath.substring(0, slash);
        var name = filePath.substring(slash + 1);
        var url = this._workspace.urlForPath(this._fileSystem.path(), filePath);
        var extension = this._extensionForPath(name);
        var contentType = this._contentTypeForExtension(extension);
        var fileDescriptor = new WebInspector.FileDescriptor(parentPath, name, this._fileSystemURL + filePath, url, contentType);
        this._projectStore.addFile(fileDescriptor);
    }, _removeFile: function (path) {
        this._projectStore.removeFile(path);
    }, dispose: function () {
        this._workspace.removeProject(this._projectId);
    }
}
WebInspector.fileSystemWorkspaceBinding;
WebInspector.FileSystemMapping = function () {
    WebInspector.Object.call(this);
    this._fileSystemMappingSetting = WebInspector.settings.createSetting("fileSystemMapping", {});
    this._excludedFoldersSetting = WebInspector.settings.createSetting("workspaceExcludedFolders", {});
    var defaultCommonExcludedFolders = ["/\\.git/", "/\\.sass-cache/", "/\\.hg/", "/\\.idea/", "/\\.svn/", "/\\.cache/", "/\\.project/"];
    var defaultWinExcludedFolders = ["/Thumbs.db$", "/ehthumbs.db$", "/Desktop.ini$", "/\\$RECYCLE.BIN/"];
    var defaultMacExcludedFolders = ["/\\.DS_Store$", "/\\.Trashes$", "/\\.Spotlight-V100$", "/\\.AppleDouble$", "/\\.LSOverride$", "/Icon$", "/\\._.*$"];
    var defaultLinuxExcludedFolders = ["/.*~$"];
    var defaultExcludedFolders = defaultCommonExcludedFolders;
    if (WebInspector.isWin())
        defaultExcludedFolders = defaultExcludedFolders.concat(defaultWinExcludedFolders); else if (WebInspector.isMac())
        defaultExcludedFolders = defaultExcludedFolders.concat(defaultMacExcludedFolders); else
        defaultExcludedFolders = defaultExcludedFolders.concat(defaultLinuxExcludedFolders);
    var defaultExcludedFoldersPattern = defaultExcludedFolders.join("|");
    WebInspector.settings.workspaceFolderExcludePattern = WebInspector.settings.createRegExpSetting("workspaceFolderExcludePattern", defaultExcludedFoldersPattern, WebInspector.isWin() ? "i" : "");
    this._fileSystemMappings = {};
    this._excludedFolders = {};
    this._loadFromSettings();
}
WebInspector.FileSystemMapping.Events = {FileMappingAdded: "FileMappingAdded", FileMappingRemoved: "FileMappingRemoved", ExcludedFolderAdded: "ExcludedFolderAdded", ExcludedFolderRemoved: "ExcludedFolderRemoved"}
WebInspector.FileSystemMapping.prototype = {
    _loadFromSettings: function () {
        var savedMapping = this._fileSystemMappingSetting.get();
        this._fileSystemMappings = {};
        for (var fileSystemPath in savedMapping) {
            var savedFileSystemMappings = savedMapping[fileSystemPath];
            this._fileSystemMappings[fileSystemPath] = [];
            var fileSystemMappings = this._fileSystemMappings[fileSystemPath];
            for (var i = 0; i < savedFileSystemMappings.length; ++i) {
                var savedEntry = savedFileSystemMappings[i];
                var entry = new WebInspector.FileSystemMapping.Entry(savedEntry.fileSystemPath, savedEntry.urlPrefix, savedEntry.pathPrefix);
                fileSystemMappings.push(entry);
            }
        }
        var savedExcludedFolders = this._excludedFoldersSetting.get();
        this._excludedFolders = {};
        for (var fileSystemPath in savedExcludedFolders) {
            var savedExcludedFoldersForPath = savedExcludedFolders[fileSystemPath];
            this._excludedFolders[fileSystemPath] = [];
            var excludedFolders = this._excludedFolders[fileSystemPath];
            for (var i = 0; i < savedExcludedFoldersForPath.length; ++i) {
                var savedEntry = savedExcludedFoldersForPath[i];
                var entry = new WebInspector.FileSystemMapping.ExcludedFolderEntry(savedEntry.fileSystemPath, savedEntry.path);
                excludedFolders.push(entry);
            }
        }
        this._rebuildIndexes();
    }, _saveToSettings: function () {
        var savedMapping = this._fileSystemMappings;
        this._fileSystemMappingSetting.set(savedMapping);
        var savedExcludedFolders = this._excludedFolders;
        this._excludedFoldersSetting.set(savedExcludedFolders);
        this._rebuildIndexes();
    }, _rebuildIndexes: function () {
        this._mappingForURLPrefix = {};
        this._urlPrefixes = [];
        for (var fileSystemPath in this._fileSystemMappings) {
            var fileSystemMapping = this._fileSystemMappings[fileSystemPath];
            for (var i = 0; i < fileSystemMapping.length; ++i) {
                var entry = fileSystemMapping[i];
                this._mappingForURLPrefix[entry.urlPrefix] = entry;
                this._urlPrefixes.push(entry.urlPrefix);
            }
        }
        this._urlPrefixes.sort();
    }, addFileSystem: function (fileSystemPath) {
        if (this._fileSystemMappings[fileSystemPath])
            return;
        this._fileSystemMappings[fileSystemPath] = [];
        this._saveToSettings();
    }, removeFileSystem: function (fileSystemPath) {
        if (!this._fileSystemMappings[fileSystemPath])
            return;
        delete this._fileSystemMappings[fileSystemPath];
        delete this._excludedFolders[fileSystemPath];
        this._saveToSettings();
    }, addFileMapping: function (fileSystemPath, urlPrefix, pathPrefix) {
        var entry = new WebInspector.FileSystemMapping.Entry(fileSystemPath, urlPrefix, pathPrefix);
        this._fileSystemMappings[fileSystemPath].push(entry);
        this._saveToSettings();
        this.dispatchEventToListeners(WebInspector.FileSystemMapping.Events.FileMappingAdded, entry);
    }, removeFileMapping: function (fileSystemPath, urlPrefix, pathPrefix) {
        var entry = this._mappingEntryForPathPrefix(fileSystemPath, pathPrefix);
        if (!entry)
            return;
        this._fileSystemMappings[fileSystemPath].remove(entry);
        this._saveToSettings();
        this.dispatchEventToListeners(WebInspector.FileSystemMapping.Events.FileMappingRemoved, entry);
    }, addExcludedFolder: function (fileSystemPath, excludedFolderPath) {
        if (!this._excludedFolders[fileSystemPath])
            this._excludedFolders[fileSystemPath] = [];
        var entry = new WebInspector.FileSystemMapping.ExcludedFolderEntry(fileSystemPath, excludedFolderPath);
        this._excludedFolders[fileSystemPath].push(entry);
        this._saveToSettings();
        this.dispatchEventToListeners(WebInspector.FileSystemMapping.Events.ExcludedFolderAdded, entry);
    }, removeExcludedFolder: function (fileSystemPath, path) {
        var entry = this._excludedFolderEntryForPath(fileSystemPath, path);
        if (!entry)
            return;
        this._excludedFolders[fileSystemPath].remove(entry);
        this._saveToSettings();
        this.dispatchEventToListeners(WebInspector.FileSystemMapping.Events.ExcludedFolderRemoved, entry);
    }, fileSystemPaths: function () {
        return Object.keys(this._fileSystemMappings);
    }, _mappingEntryForURL: function (url) {
        for (var i = this._urlPrefixes.length - 1; i >= 0; --i) {
            var urlPrefix = this._urlPrefixes[i];
            if (url.startsWith(urlPrefix))
                return this._mappingForURLPrefix[urlPrefix];
        }
        return null;
    }, _excludedFolderEntryForPath: function (fileSystemPath, path) {
        var entries = this._excludedFolders[fileSystemPath];
        if (!entries)
            return null;
        for (var i = 0; i < entries.length; ++i) {
            if (entries[i].path === path)
                return entries[i];
        }
        return null;
    }, _mappingEntryForPath: function (fileSystemPath, filePath) {
        var entries = this._fileSystemMappings[fileSystemPath];
        if (!entries)
            return null;
        var entry = null;
        for (var i = 0; i < entries.length; ++i) {
            var pathPrefix = entries[i].pathPrefix;
            if (entry && entry.pathPrefix.length > pathPrefix.length)
                continue;
            if (filePath.startsWith(pathPrefix.substr(1)))
                entry = entries[i];
        }
        return entry;
    }, _mappingEntryForPathPrefix: function (fileSystemPath, pathPrefix) {
        var entries = this._fileSystemMappings[fileSystemPath];
        for (var i = 0; i < entries.length; ++i) {
            if (pathPrefix === entries[i].pathPrefix)
                return entries[i];
        }
        return null;
    }, isFileExcluded: function (fileSystemPath, folderPath) {
        var excludedFolders = this._excludedFolders[fileSystemPath] || [];
        for (var i = 0; i < excludedFolders.length; ++i) {
            var entry = excludedFolders[i];
            if (entry.path === folderPath)
                return true;
        }
        var regex = WebInspector.settings.workspaceFolderExcludePattern.asRegExp();
        return regex && regex.test(folderPath);
    }, excludedFolders: function (fileSystemPath) {
        var excludedFolders = this._excludedFolders[fileSystemPath];
        return excludedFolders ? excludedFolders.slice() : [];
    }, mappingEntries: function (fileSystemPath) {
        return this._fileSystemMappings[fileSystemPath].slice();
    }, hasMappingForURL: function (url) {
        return !!this._mappingEntryForURL(url);
    }, fileForURL: function (url) {
        var entry = this._mappingEntryForURL(url);
        if (!entry)
            return null;
        var file = {};
        file.fileSystemPath = entry.fileSystemPath;
        file.filePath = entry.pathPrefix.substr(1) + url.substr(entry.urlPrefix.length);
        return file;
    }, urlForPath: function (fileSystemPath, filePath) {
        var entry = this._mappingEntryForPath(fileSystemPath, filePath);
        if (!entry)
            return "";
        return entry.urlPrefix + filePath.substring(entry.pathPrefix.length - 1);
    }, removeMappingForURL: function (url) {
        var entry = this._mappingEntryForURL(url);
        if (!entry)
            return;
        this._fileSystemMappings[entry.fileSystemPath].remove(entry);
        this._saveToSettings();
    }, addMappingForResource: function (url, fileSystemPath, filePath) {
        var commonPathSuffixLength = 0;
        var normalizedFilePath = "/" + filePath;
        for (var i = 0; i < normalizedFilePath.length; ++i) {
            var filePathCharacter = normalizedFilePath[normalizedFilePath.length - 1 - i];
            var urlCharacter = url[url.length - 1 - i];
            if (filePathCharacter !== urlCharacter)
                break;
            if (filePathCharacter === "/")
                commonPathSuffixLength = i;
        }
        var pathPrefix = normalizedFilePath.substr(0, normalizedFilePath.length - commonPathSuffixLength);
        var urlPrefix = url.substr(0, url.length - commonPathSuffixLength);
        this.addFileMapping(fileSystemPath, urlPrefix, pathPrefix);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.FileSystemMapping.Entry = function (fileSystemPath, urlPrefix, pathPrefix) {
    this.fileSystemPath = fileSystemPath;
    this.urlPrefix = urlPrefix;
    this.pathPrefix = pathPrefix;
}
WebInspector.FileSystemMapping.ExcludedFolderEntry = function (fileSystemPath, path) {
    this.fileSystemPath = fileSystemPath;
    this.path = path;
}
WebInspector.IsolatedFileSystem = function (manager, path, name, rootURL) {
    this._manager = manager;
    this._path = path;
    this._name = name;
    this._rootURL = rootURL;
}
WebInspector.IsolatedFileSystem.errorMessage = function (error) {
    return WebInspector.UIString("File system error: %s", error.message);
}
WebInspector.IsolatedFileSystem.normalizePath = function (fileSystemPath) {
    if (WebInspector.isWin())
        return fileSystemPath.replace(/\\/g, "/");
    return fileSystemPath;
}
WebInspector.IsolatedFileSystem.prototype = {
    path: function () {
        return this._path;
    }, normalizedPath: function () {
        if (this._normalizedPath)
            return this._normalizedPath;
        this._normalizedPath = WebInspector.IsolatedFileSystem.normalizePath(this._path);
        return this._normalizedPath;
    }, name: function () {
        return this._name;
    }, rootURL: function () {
        return this._rootURL;
    }, _requestFileSystem: function (callback) {
        this._manager.requestDOMFileSystem(this._path, callback);
    }, requestFilesRecursive: function (path, fileCallback, finishedCallback) {
        var domFileSystem;
        var pendingRequests = 0;
        this._requestFileSystem(fileSystemLoaded.bind(this));
        function fileSystemLoaded(fs) {
            domFileSystem = (fs);
            console.assert(domFileSystem);
            ++pendingRequests;
            this._requestEntries(domFileSystem, path, innerCallback.bind(this));
        }

        function innerCallback(entries) {
            for (var i = 0; i < entries.length; ++i) {
                var entry = entries[i];
                if (!entry.isDirectory) {
                    if (this._manager.mapping().isFileExcluded(this._path, entry.fullPath))
                        continue;
                    fileCallback(entry.fullPath.substr(1));
                }
                else {
                    if (this._manager.mapping().isFileExcluded(this._path, entry.fullPath + "/"))
                        continue;
                    ++pendingRequests;
                    this._requestEntries(domFileSystem, entry.fullPath, innerCallback.bind(this));
                }
            }
            if (finishedCallback && (--pendingRequests === 0))
                finishedCallback();
        }
    }, createFile: function (path, name, callback) {
        this._requestFileSystem(fileSystemLoaded.bind(this));
        var newFileIndex = 1;
        if (!name)
            name = "NewFile";
        var nameCandidate;

        function fileSystemLoaded(fs) {
            var domFileSystem = (fs);
            console.assert(domFileSystem);
            domFileSystem.root.getDirectory(path, null, dirEntryLoaded.bind(this), errorHandler.bind(this));
        }

        function dirEntryLoaded(dirEntry) {
            var nameCandidate = name;
            if (newFileIndex > 1)
                nameCandidate += newFileIndex;
            ++newFileIndex;
            dirEntry.getFile(nameCandidate, {create: true, exclusive: true}, fileCreated, fileCreationError.bind(this));
            function fileCreated(entry) {
                callback(entry.fullPath.substr(1));
            }

            function fileCreationError(error) {
                if (error.code === FileError.INVALID_MODIFICATION_ERR) {
                    dirEntryLoaded.call(this, dirEntry);
                    return;
                }
                var errorMessage = WebInspector.IsolatedFileSystem.errorMessage(error);
                console.error(errorMessage + " when testing if file exists '" + (this._path + "/" + path + "/" + nameCandidate) + "'");
                callback(null);
            }
        }

        function errorHandler(error) {
            var errorMessage = WebInspector.IsolatedFileSystem.errorMessage(error);
            var filePath = this._path + "/" + path;
            if (nameCandidate)
                filePath += "/" + nameCandidate;
            console.error(errorMessage + " when getting content for file '" + (filePath) + "'");
            callback(null);
        }
    }, deleteFile: function (path) {
        this._requestFileSystem(fileSystemLoaded.bind(this));
        function fileSystemLoaded(fs) {
            var domFileSystem = (fs);
            console.assert(domFileSystem);
            domFileSystem.root.getFile(path, null, fileEntryLoaded.bind(this), errorHandler.bind(this));
        }

        function fileEntryLoaded(fileEntry) {
            fileEntry.remove(fileEntryRemoved, errorHandler.bind(this));
        }

        function fileEntryRemoved() {
        }

        function errorHandler(error) {
            var errorMessage = WebInspector.IsolatedFileSystem.errorMessage(error);
            console.error(errorMessage + " when deleting file '" + (this._path + "/" + path) + "'");
        }
    }, requestMetadata: function (path, callback) {
        this._requestFileSystem(fileSystemLoaded);
        function fileSystemLoaded(fs) {
            var domFileSystem = (fs);
            console.assert(domFileSystem);
            domFileSystem.root.getFile(path, null, fileEntryLoaded, errorHandler);
        }

        function fileEntryLoaded(entry) {
            entry.getMetadata(successHandler, errorHandler);
        }

        function successHandler(metadata) {
            callback(metadata.modificationTime, metadata.size);
        }

        function errorHandler(error) {
            callback(null, null);
        }
    }, requestFileContent: function (path, callback) {
        this._requestFileSystem(fileSystemLoaded.bind(this));
        function fileSystemLoaded(fs) {
            var domFileSystem = (fs);
            console.assert(domFileSystem);
            domFileSystem.root.getFile(path, null, fileEntryLoaded.bind(this), errorHandler.bind(this));
        }

        function fileEntryLoaded(entry) {
            entry.file(fileLoaded, errorHandler.bind(this));
        }

        function fileLoaded(file) {
            var reader = new FileReader();
            reader.onloadend = readerLoadEnd;
            reader.readAsText(file);
        }

        function readerLoadEnd() {
            callback((this.result));
        }

        function errorHandler(error) {
            if (error.code === FileError.NOT_FOUND_ERR) {
                callback(null);
                return;
            }
            var errorMessage = WebInspector.IsolatedFileSystem.errorMessage(error);
            console.error(errorMessage + " when getting content for file '" + (this._path + "/" + path) + "'");
            callback(null);
        }
    }, setFileContent: function (path, content, callback) {
        this._requestFileSystem(fileSystemLoaded.bind(this));
        WebInspector.userMetrics.FileSavedInWorkspace.record();
        function fileSystemLoaded(fs) {
            var domFileSystem = (fs);
            console.assert(domFileSystem);
            domFileSystem.root.getFile(path, {create: true}, fileEntryLoaded.bind(this), errorHandler.bind(this));
        }

        function fileEntryLoaded(entry) {
            entry.createWriter(fileWriterCreated.bind(this), errorHandler.bind(this));
        }

        function fileWriterCreated(fileWriter) {
            fileWriter.onerror = errorHandler.bind(this);
            fileWriter.onwriteend = fileTruncated;
            fileWriter.truncate(0);
            function fileTruncated() {
                fileWriter.onwriteend = writerEnd;
                var blob = new Blob([content], {type: "text/plain"});
                fileWriter.write(blob);
            }
        }

        function writerEnd() {
            callback();
        }

        function errorHandler(error) {
            var errorMessage = WebInspector.IsolatedFileSystem.errorMessage(error);
            console.error(errorMessage + " when setting content for file '" + (this._path + "/" + path) + "'");
            callback();
        }
    }, renameFile: function (path, newName, callback) {
        newName = newName ? newName.trim() : newName;
        if (!newName || newName.indexOf("/") !== -1) {
            callback(false);
            return;
        }
        var fileEntry;
        var dirEntry;
        var newFileEntry;
        this._requestFileSystem(fileSystemLoaded.bind(this));
        function fileSystemLoaded(fs) {
            var domFileSystem = (fs);
            console.assert(domFileSystem);
            domFileSystem.root.getFile(path, null, fileEntryLoaded.bind(this), errorHandler.bind(this));
        }

        function fileEntryLoaded(entry) {
            if (entry.name === newName) {
                callback(false);
                return;
            }
            fileEntry = entry;
            fileEntry.getParent(dirEntryLoaded.bind(this), errorHandler.bind(this));
        }

        function dirEntryLoaded(entry) {
            dirEntry = entry;
            dirEntry.getFile(newName, null, newFileEntryLoaded, newFileEntryLoadErrorHandler.bind(this));
        }

        function newFileEntryLoaded(entry) {
            callback(false);
        }

        function newFileEntryLoadErrorHandler(error) {
            if (error.code !== FileError.NOT_FOUND_ERR) {
                callback(false);
                return;
            }
            fileEntry.moveTo(dirEntry, newName, fileRenamed, errorHandler.bind(this));
        }

        function fileRenamed(entry) {
            callback(true, entry.name);
        }

        function errorHandler(error) {
            var errorMessage = WebInspector.IsolatedFileSystem.errorMessage(error);
            console.error(errorMessage + " when renaming file '" + (this._path + "/" + path) + "' to '" + newName + "'");
            callback(false);
        }
    }, _readDirectory: function (dirEntry, callback) {
        var dirReader = dirEntry.createReader();
        var entries = [];

        function innerCallback(results) {
            if (!results.length)
                callback(entries.sort()); else {
                entries = entries.concat(toArray(results));
                dirReader.readEntries(innerCallback, errorHandler);
            }
        }

        function toArray(list) {
            return Array.prototype.slice.call(list || [], 0);
        }

        dirReader.readEntries(innerCallback, errorHandler);
        function errorHandler(error) {
            var errorMessage = WebInspector.IsolatedFileSystem.errorMessage(error);
            console.error(errorMessage + " when reading directory '" + dirEntry.fullPath + "'");
            callback([]);
        }
    }, _requestEntries: function (domFileSystem, path, callback) {
        domFileSystem.root.getDirectory(path, null, innerCallback.bind(this), errorHandler);
        function innerCallback(dirEntry) {
            this._readDirectory(dirEntry, callback)
        }

        function errorHandler(error) {
            var errorMessage = WebInspector.IsolatedFileSystem.errorMessage(error);
            console.error(errorMessage + " when requesting entry '" + path + "'");
            callback([]);
        }
    }
}
WebInspector.IsolatedFileSystemManager = function () {
    this._fileSystems = {};
    this._pendingFileSystemRequests = {};
    this._fileSystemMapping = new WebInspector.FileSystemMapping();
    this._requestFileSystems();
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemsLoaded, this._onFileSystemsLoaded, this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemRemoved, this._onFileSystemRemoved, this);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.FileSystemAdded, this._onFileSystemAdded, this);
}
WebInspector.IsolatedFileSystemManager.FileSystem;
WebInspector.IsolatedFileSystemManager.Events = {FileSystemAdded: "FileSystemAdded", FileSystemRemoved: "FileSystemRemoved"}
WebInspector.IsolatedFileSystemManager.prototype = {
    mapping: function () {
        return this._fileSystemMapping;
    }, _requestFileSystems: function () {
        console.assert(!this._loaded);
        InspectorFrontendHost.requestFileSystems();
    }, addFileSystem: function () {
        InspectorFrontendHost.addFileSystem();
    }, removeFileSystem: function (fileSystemPath) {
        InspectorFrontendHost.removeFileSystem(fileSystemPath);
    }, _onFileSystemsLoaded: function (event) {
        var fileSystems = (event.data);
        var addedFileSystemPaths = {};
        for (var i = 0; i < fileSystems.length; ++i) {
            this._innerAddFileSystem(fileSystems[i]);
            addedFileSystemPaths[fileSystems[i].fileSystemPath] = true;
        }
        var fileSystemPaths = this._fileSystemMapping.fileSystemPaths();
        for (var i = 0; i < fileSystemPaths.length; ++i) {
            var fileSystemPath = fileSystemPaths[i];
            if (!addedFileSystemPaths[fileSystemPath])
                this._fileSystemRemoved(fileSystemPath);
        }
        this._loaded = true;
        this._processPendingFileSystemRequests();
    }, _innerAddFileSystem: function (fileSystem) {
        var fileSystemPath = fileSystem.fileSystemPath;
        this._fileSystemMapping.addFileSystem(fileSystemPath);
        var isolatedFileSystem = new WebInspector.IsolatedFileSystem(this, fileSystemPath, fileSystem.fileSystemName, fileSystem.rootURL);
        this._fileSystems[fileSystemPath] = isolatedFileSystem;
        this.dispatchEventToListeners(WebInspector.IsolatedFileSystemManager.Events.FileSystemAdded, isolatedFileSystem);
    }, _processPendingFileSystemRequests: function () {
        for (var fileSystemPath in this._pendingFileSystemRequests) {
            var callbacks = this._pendingFileSystemRequests[fileSystemPath];
            for (var i = 0; i < callbacks.length; ++i)
                callbacks[i](this._isolatedFileSystem(fileSystemPath));
        }
        delete this._pendingFileSystemRequests;
    }, _onFileSystemAdded: function (event) {
        var errorMessage = (event.data["errorMessage"]);
        var fileSystem = (event.data["fileSystem"]);
        var fileSystemPath;
        if (errorMessage) {
            WebInspector.console.error(errorMessage, true);
        } else {
            this._innerAddFileSystem(fileSystem);
            fileSystemPath = fileSystem.fileSystemPath;
        }
    }, _onFileSystemRemoved: function (event) {
        this._fileSystemRemoved((event.data));
    }, _fileSystemRemoved: function (fileSystemPath) {
        this._fileSystemMapping.removeFileSystem(fileSystemPath);
        var isolatedFileSystem = this._fileSystems[fileSystemPath];
        delete this._fileSystems[fileSystemPath];
        if (isolatedFileSystem)
            this.dispatchEventToListeners(WebInspector.IsolatedFileSystemManager.Events.FileSystemRemoved, isolatedFileSystem);
    }, _isolatedFileSystem: function (fileSystemPath) {
        var fileSystem = this._fileSystems[fileSystemPath];
        if (!fileSystem)
            return null;
        if (!InspectorFrontendHost.isolatedFileSystem)
            return null;
        return InspectorFrontendHost.isolatedFileSystem(fileSystem.name(), fileSystem.rootURL());
    }, requestDOMFileSystem: function (fileSystemPath, callback) {
        if (!this._loaded) {
            if (!this._pendingFileSystemRequests[fileSystemPath])
                this._pendingFileSystemRequests[fileSystemPath] = this._pendingFileSystemRequests[fileSystemPath] || [];
            this._pendingFileSystemRequests[fileSystemPath].push(callback);
            return;
        }
        callback(this._isolatedFileSystem(fileSystemPath));
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.isolatedFileSystemManager;
WebInspector.ProjectSearchConfig = function () {
}
WebInspector.ProjectSearchConfig.prototype = {
    query: function () {
    }, ignoreCase: function () {
    }, isRegex: function () {
    }, queries: function () {
    }, filePathMatchesFileQuery: function (filePath) {
    }
}
WebInspector.FileDescriptor = function (parentPath, name, originURL, url, contentType) {
    this.parentPath = parentPath;
    this.name = name;
    this.originURL = originURL;
    this.url = url;
    this.contentType = contentType;
}
WebInspector.ProjectDelegate = function () {
}
WebInspector.ProjectDelegate.prototype = {
    type: function () {
    }, displayName: function () {
    }, requestMetadata: function (path, callback) {
    }, requestFileContent: function (path, callback) {
    }, canSetFileContent: function () {
    }, setFileContent: function (path, newContent, callback) {
    }, canRename: function () {
    }, rename: function (path, newName, callback) {
    }, refresh: function (path, callback) {
    }, excludeFolder: function (path) {
    }, createFile: function (path, name, content, callback) {
    }, deleteFile: function (path) {
    }, remove: function () {
    }, searchInFileContent: function (path, query, caseSensitive, isRegex, callback) {
    }, findFilesMatchingSearchRequest: function (searchConfig, filesMathingFileQuery, progress, callback) {
    }, indexContent: function (progress) {
    }
}
WebInspector.ProjectStore = function (project) {
    this._project = project;
}
WebInspector.ProjectStore.prototype = {
    addFile: function (fileDescriptor) {
        this._project._addFile(fileDescriptor);
    }, removeFile: function (path) {
        this._project._removeFile(path);
    }, project: function () {
        return this._project;
    }
}
WebInspector.Project = function (workspace, projectId, projectDelegate) {
    this._uiSourceCodesMap = {};
    this._uiSourceCodesList = [];
    this._workspace = workspace;
    this._projectId = projectId;
    this._projectDelegate = projectDelegate;
    this._displayName = this._projectDelegate.displayName();
}
WebInspector.Project.prototype = {
    id: function () {
        return this._projectId;
    }, type: function () {
        return this._projectDelegate.type();
    }, displayName: function () {
        return this._displayName;
    }, isServiceProject: function () {
        return this._projectDelegate.type() === WebInspector.projectTypes.Debugger || this._projectDelegate.type() === WebInspector.projectTypes.Formatter || this._projectDelegate.type() === WebInspector.projectTypes.LiveEdit;
    }, _addFile: function (fileDescriptor) {
        var path = fileDescriptor.parentPath ? fileDescriptor.parentPath + "/" + fileDescriptor.name : fileDescriptor.name;
        var uiSourceCode = this.uiSourceCode(path);
        if (uiSourceCode) {
            console.log("devtools: script is skipped: " + JSON.stringify(fileDescriptor));
            return;
        }
        uiSourceCode = new WebInspector.UISourceCode(this, fileDescriptor.parentPath, fileDescriptor.name, fileDescriptor.originURL, fileDescriptor.url, fileDescriptor.contentType);
        this._uiSourceCodesMap[path] = {uiSourceCode: uiSourceCode, index: this._uiSourceCodesList.length};
        this._uiSourceCodesList.push(uiSourceCode);
        this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.UISourceCodeAdded, uiSourceCode);
    }, _removeFile: function (path) {
        var uiSourceCode = this.uiSourceCode(path);
        if (!uiSourceCode)
            return;
        var entry = this._uiSourceCodesMap[path];
        var movedUISourceCode = this._uiSourceCodesList[this._uiSourceCodesList.length - 1];
        this._uiSourceCodesList[entry.index] = movedUISourceCode;
        var movedEntry = this._uiSourceCodesMap[movedUISourceCode.path()];
        movedEntry.index = entry.index;
        this._uiSourceCodesList.splice(this._uiSourceCodesList.length - 1, 1);
        delete this._uiSourceCodesMap[path];
        this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.UISourceCodeRemoved, entry.uiSourceCode);
    }, _remove: function () {
        this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.ProjectRemoved, this);
        this._uiSourceCodesMap = {};
        this._uiSourceCodesList = [];
    }, workspace: function () {
        return this._workspace;
    }, uiSourceCode: function (path) {
        var entry = this._uiSourceCodesMap[path];
        return entry ? entry.uiSourceCode : null;
    }, uiSourceCodeForOriginURL: function (originURL) {
        for (var i = 0; i < this._uiSourceCodesList.length; ++i) {
            var uiSourceCode = this._uiSourceCodesList[i];
            if (uiSourceCode.originURL() === originURL)
                return uiSourceCode;
        }
        return null;
    }, uiSourceCodes: function () {
        return this._uiSourceCodesList;
    }, requestMetadata: function (uiSourceCode, callback) {
        this._projectDelegate.requestMetadata(uiSourceCode.path(), callback);
    }, requestFileContent: function (uiSourceCode, callback) {
        this._projectDelegate.requestFileContent(uiSourceCode.path(), callback);
    }, canSetFileContent: function () {
        return this._projectDelegate.canSetFileContent();
    }, setFileContent: function (uiSourceCode, newContent, callback) {
        this._projectDelegate.setFileContent(uiSourceCode.path(), newContent, onSetContent.bind(this));
        function onSetContent(content) {
            this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.UISourceCodeContentCommitted, {uiSourceCode: uiSourceCode, content: newContent});
            callback(content);
        }
    }, canRename: function () {
        return this._projectDelegate.canRename();
    }, rename: function (uiSourceCode, newName, callback) {
        if (newName === uiSourceCode.name()) {
            callback(true, uiSourceCode.name(), uiSourceCode.url, uiSourceCode.originURL(), uiSourceCode.contentType());
            return;
        }
        this._projectDelegate.rename(uiSourceCode.path(), newName, innerCallback.bind(this));
        function innerCallback(success, newName, newURL, newOriginURL, newContentType) {
            if (!success || !newName) {
                callback(false);
                return;
            }
            var oldPath = uiSourceCode.path();
            var newPath = uiSourceCode.parentPath() ? uiSourceCode.parentPath() + "/" + newName : newName;
            this._uiSourceCodesMap[newPath] = this._uiSourceCodesMap[oldPath];
            delete this._uiSourceCodesMap[oldPath];
            callback(true, newName, newURL, newOriginURL, newContentType);
        }
    }, refresh: function (path, callback) {
        this._projectDelegate.refresh(path, callback);
    }, excludeFolder: function (path) {
        this._projectDelegate.excludeFolder(path);
        var uiSourceCodes = this._uiSourceCodesList.slice();
        for (var i = 0; i < uiSourceCodes.length; ++i) {
            var uiSourceCode = uiSourceCodes[i];
            if (uiSourceCode.path().startsWith(path.substr(1)))
                this._removeFile(uiSourceCode.path());
        }
    }, createFile: function (path, name, content, callback) {
        this._projectDelegate.createFile(path, name, content, innerCallback);
        function innerCallback(filePath) {
            callback(filePath);
        }
    }, deleteFile: function (path) {
        this._projectDelegate.deleteFile(path);
    }, remove: function () {
        this._projectDelegate.remove();
    }, searchInFileContent: function (uiSourceCode, query, caseSensitive, isRegex, callback) {
        this._projectDelegate.searchInFileContent(uiSourceCode.path(), query, caseSensitive, isRegex, callback);
    }, findFilesMatchingSearchRequest: function (searchConfig, filesMathingFileQuery, progress, callback) {
        this._projectDelegate.findFilesMatchingSearchRequest(searchConfig, filesMathingFileQuery, progress, callback);
    }, indexContent: function (progress) {
        this._projectDelegate.indexContent(progress);
    }
}
WebInspector.projectTypes = {Debugger: "debugger", Formatter: "formatter", LiveEdit: "liveedit", Network: "network", Snippets: "snippets", FileSystem: "filesystem", ContentScripts: "contentscripts"}
WebInspector.Workspace = function (fileSystemMapping) {
    this._fileSystemMapping = fileSystemMapping;
    this._projects = {};
    this._hasResourceContentTrackingExtensions = false;
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.RevealSourceLine, this._revealSourceLine, this);
}
WebInspector.Workspace.Events = {UISourceCodeAdded: "UISourceCodeAdded", UISourceCodeRemoved: "UISourceCodeRemoved", UISourceCodeContentCommitted: "UISourceCodeContentCommitted", ProjectRemoved: "ProjectRemoved"}
WebInspector.Workspace.prototype = {
    unsavedSourceCodes: function () {
        function filterUnsaved(sourceCode) {
            return sourceCode.isDirty();
        }

        return this.uiSourceCodes().filter(filterUnsaved);
    }, uiSourceCode: function (projectId, path) {
        var project = this._projects[projectId];
        return project ? project.uiSourceCode(path) : null;
    }, uiSourceCodeForOriginURL: function (originURL) {
        var projects = this.projectsForType(WebInspector.projectTypes.Network);
        projects = projects.concat(this.projectsForType(WebInspector.projectTypes.ContentScripts));
        for (var i = 0; i < projects.length; ++i) {
            var project = projects[i];
            var uiSourceCode = project.uiSourceCodeForOriginURL(originURL);
            if (uiSourceCode)
                return uiSourceCode;
        }
        return null;
    }, uiSourceCodesForProjectType: function (type) {
        var result = [];
        for (var projectName in this._projects) {
            var project = this._projects[projectName];
            if (project.type() === type)
                result = result.concat(project.uiSourceCodes());
        }
        return result;
    }, addProject: function (projectId, projectDelegate) {
        var project = new WebInspector.Project(this, projectId, projectDelegate);
        this._projects[projectId] = project;
        var projectStore = new WebInspector.ProjectStore(project);
        return projectStore;
    }, removeProject: function (projectId) {
        var project = this._projects[projectId];
        if (!project)
            return;
        delete this._projects[projectId];
        project._remove();
    }, project: function (projectId) {
        return this._projects[projectId];
    }, projects: function () {
        return Object.values(this._projects);
    }, projectsForType: function (type) {
        function filterByType(project) {
            return project.type() === type;
        }

        return this.projects().filter(filterByType);
    }, uiSourceCodes: function () {
        var result = [];
        for (var projectId in this._projects) {
            var project = this._projects[projectId];
            result = result.concat(project.uiSourceCodes());
        }
        return result;
    }, hasMappingForURL: function (url) {
        return this._fileSystemMapping.hasMappingForURL(url);
    }, _networkUISourceCodeForURL: function (url) {
        var splitURL = WebInspector.ParsedURL.splitURL(url);
        var projectId = splitURL[0];
        var project = this.project(projectId);
        return project ? project.uiSourceCode(splitURL.slice(1).join("/")) : null;
    }, _contentScriptUISourceCodeForURL: function (url) {
        var splitURL = WebInspector.ParsedURL.splitURL(url);
        var projectId = "contentscripts:" + splitURL[0];
        var project = this.project(projectId);
        return project ? project.uiSourceCode(splitURL.slice(1).join("/")) : null;
    }, uiSourceCodeForURL: function (url) {
        var file = this._fileSystemMapping.fileForURL(url);
        if (!file)
            return this._networkUISourceCodeForURL(url) || this._contentScriptUISourceCodeForURL(url);
        var projectId = WebInspector.FileSystemWorkspaceBinding.projectId(file.fileSystemPath);
        var project = this.project(projectId);
        return project ? project.uiSourceCode(file.filePath) : null;
    }, urlForPath: function (fileSystemPath, filePath) {
        return this._fileSystemMapping.urlForPath(fileSystemPath, filePath);
    }, addMapping: function (networkUISourceCode, uiSourceCode, fileSystemWorkspaceBinding) {
        var url = networkUISourceCode.url;
        var path = uiSourceCode.path();
        var fileSystemPath = fileSystemWorkspaceBinding.fileSystemPath(uiSourceCode.project().id());
        this._fileSystemMapping.addMappingForResource(url, fileSystemPath, path);
    }, removeMapping: function (uiSourceCode) {
        this._fileSystemMapping.removeMappingForURL(uiSourceCode.url);
    }, setHasResourceContentTrackingExtensions: function (hasExtensions) {
        this._hasResourceContentTrackingExtensions = hasExtensions;
    }, hasResourceContentTrackingExtensions: function () {
        return this._hasResourceContentTrackingExtensions;
    }, _revealSourceLine: function (event) {
        var url = (event.data["url"]);
        var lineNumber = (event.data["lineNumber"]);
        var columnNumber = (event.data["columnNumber"]);
        var uiSourceCode = this.uiSourceCodeForURL(url);
        if (uiSourceCode) {
            WebInspector.Revealer.reveal(uiSourceCode.uiLocation(lineNumber, columnNumber));
            return;
        }
        function listener(event) {
            var uiSourceCode = (event.data);
            if (uiSourceCode.url === url) {
                WebInspector.Revealer.reveal(uiSourceCode.uiLocation(lineNumber, columnNumber));
                this.removeEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, listener, this);
            }
        }

        this.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, listener, this);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.workspace;
WebInspector.WorkspaceController = function (workspace) {
    this._workspace = workspace;
    window.addEventListener("focus", this._windowFocused.bind(this), false);
    this._fileSystemRefreshThrottler = new WebInspector.Throttler(1000);
}
WebInspector.WorkspaceController.prototype = {
    _windowFocused: function (event) {
        this._fileSystemRefreshThrottler.schedule(refreshFileSystems.bind(this));
        function refreshFileSystems(callback) {
            var barrier = new CallbackBarrier();
            var projects = this._workspace.projects();
            for (var i = 0; i < projects.length; ++i)
                projects[i].refresh("/", barrier.createCallback());
            barrier.callWhenDone(callback);
        }
    }
}
WebInspector.ContentProviderBasedProjectDelegate = function (workspace, id, type) {
    this._type = type;
    this._contentProviders = {};
    this._workspace = workspace;
    this._id = id;
    this._projectStore = workspace.addProject(id, this);
}
WebInspector.ContentProviderBasedProjectDelegate.prototype = {
    type: function () {
        return this._type;
    }, displayName: function () {
        return "";
    }, requestMetadata: function (path, callback) {
        callback(null, null);
    }, requestFileContent: function (path, callback) {
        var contentProvider = this._contentProviders[path];
        contentProvider.requestContent(callback);
        function innerCallback(content, encoded, mimeType) {
            callback(content);
        }
    }, canSetFileContent: function () {
        return false;
    }, setFileContent: function (path, newContent, callback) {
        callback(null);
    }, canRename: function () {
        return false;
    }, rename: function (path, newName, callback) {
        this.performRename(path, newName, innerCallback.bind(this));
        function innerCallback(success, newName) {
            if (success)
                this._updateName(path, (newName));
            callback(success, newName);
        }
    }, refresh: function (path, callback) {
        if (callback)
            callback();
    }, excludeFolder: function (path) {
    }, createFile: function (path, name, content, callback) {
    }, deleteFile: function (path) {
    }, remove: function () {
    }, performRename: function (path, newName, callback) {
        callback(false);
    }, _updateName: function (path, newName) {
        var oldPath = path;
        var copyOfPath = path.split("/");
        copyOfPath[copyOfPath.length - 1] = newName;
        var newPath = copyOfPath.join("/");
        this._contentProviders[newPath] = this._contentProviders[oldPath];
        delete this._contentProviders[oldPath];
    }, searchInFileContent: function (path, query, caseSensitive, isRegex, callback) {
        var contentProvider = this._contentProviders[path];
        contentProvider.searchInContent(query, caseSensitive, isRegex, callback);
    }, findFilesMatchingSearchRequest: function (searchConfig, filesMathingFileQuery, progress, callback) {
        var result = [];
        var paths = filesMathingFileQuery;
        var totalCount = paths.length;
        if (totalCount === 0) {
            setTimeout(doneCallback, 0);
            return;
        }
        var barrier = new CallbackBarrier();
        progress.setTotalWork(paths.length);
        for (var i = 0; i < paths.length; ++i)
            searchInContent.call(this, paths[i], barrier.createCallback(searchInContentCallback.bind(null, paths[i])));
        barrier.callWhenDone(doneCallback);
        function searchInContent(path, callback) {
            var queriesToRun = searchConfig.queries().slice();
            searchNextQuery.call(this);
            function searchNextQuery() {
                if (!queriesToRun.length) {
                    callback(true);
                    return;
                }
                var query = queriesToRun.shift();
                this._contentProviders[path].searchInContent(query, !searchConfig.ignoreCase(), searchConfig.isRegex(), contentCallback.bind(this));
            }

            function contentCallback(searchMatches) {
                if (!searchMatches.length) {
                    callback(false);
                    return;
                }
                searchNextQuery.call(this);
            }
        }

        function searchInContentCallback(path, matches) {
            if (matches)
                result.push(path);
            progress.worked(1);
        }

        function doneCallback() {
            callback(result);
            progress.done();
        }
    }, indexContent: function (progress) {
        setTimeout(progress.done.bind(progress), 0);
    }, addContentProvider: function (parentPath, name, url, contentProvider) {
        var path = parentPath ? parentPath + "/" + name : name;
        if (this._contentProviders[path])
            return path;
        var fileDescriptor = new WebInspector.FileDescriptor(parentPath, name, url, url, contentProvider.contentType());
        this._contentProviders[path] = contentProvider;
        this._projectStore.addFile(fileDescriptor);
        return path;
    }, removeFile: function (path) {
        delete this._contentProviders[path];
        this._projectStore.removeFile(path);
    }, contentProviders: function () {
        return this._contentProviders;
    }, reset: function () {
        this._contentProviders = {};
        this._workspace.removeProject(this._id);
        this._projectStore = this._workspace.addProject(this._id, this);
    }
}
WebInspector.NetworkProjectDelegate = function (workspace, projectId, projectName, projectType) {
    this._name = projectName;
    this._id = projectId;
    WebInspector.ContentProviderBasedProjectDelegate.call(this, workspace, projectId, projectType);
    this._lastUniqueSuffix = 0;
}
WebInspector.NetworkProjectDelegate.prototype = {
    id: function () {
        return this._id;
    }, displayName: function () {
        if (typeof this._displayName !== "undefined")
            return this._displayName;
        if (!this._name) {
            this._displayName = WebInspector.UIString("(no domain)");
            return this._displayName;
        }
        var parsedURL = new WebInspector.ParsedURL(this._name);
        if (parsedURL.isValid) {
            this._displayName = parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "");
            if (!this._displayName)
                this._displayName = this._name;
        }
        else
            this._displayName = this._name;
        return this._displayName;
    }, addFile: function (parentPath, name, url, contentProvider) {
        return this.addContentProvider(parentPath, name, url, contentProvider);
    }, __proto__: WebInspector.ContentProviderBasedProjectDelegate.prototype
}
WebInspector.NetworkWorkspaceBinding = function (workspace) {
    this._workspace = workspace;
    this._projectDelegates = {};
}
WebInspector.NetworkWorkspaceBinding.prototype = {
    _projectDelegate: function (projectName, isContentScripts) {
        var projectId = (isContentScripts ? "contentscripts:" : "") + projectName;
        var projectType = isContentScripts ? WebInspector.projectTypes.ContentScripts : WebInspector.projectTypes.Network;
        if (this._projectDelegates[projectId])
            return this._projectDelegates[projectId];
        var projectDelegate = new WebInspector.NetworkProjectDelegate(this._workspace, projectId, projectName, projectType);
        this._projectDelegates[projectId] = projectDelegate;
        return projectDelegate;
    }, addFileForURL: function (url, contentProvider, isContentScript) {
        var splitURL = WebInspector.ParsedURL.splitURL(url);
        var projectName = splitURL[0];
        var parentPath = splitURL.slice(1, -1).join("/");
        try {
            parentPath = decodeURI(parentPath);
        } catch (e) {
        }
        var name = splitURL.peekLast() || "";
        try {
            name = decodeURI(name);
        } catch (e) {
        }
        var projectDelegate = this._projectDelegate(projectName, isContentScript || false);
        var path = projectDelegate.addFile(parentPath, name, url, contentProvider);
        var uiSourceCode = (this._workspace.uiSourceCode(projectDelegate.id(), path));
        console.assert(uiSourceCode);
        return uiSourceCode;
    }, reset: function () {
        for (var projectId in this._projectDelegates)
            this._projectDelegates[projectId].reset();
        this._projectDelegates = {};
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.BreakpointManager = function (breakpointStorage, workspace, targetManager, debuggerWorkspaceBinding) {
    this._storage = new WebInspector.BreakpointManager.Storage(this, breakpointStorage);
    this._workspace = workspace;
    this._targetManager = targetManager;
    this._debuggerWorkspaceBinding = debuggerWorkspaceBinding;
    this._breakpointsActive = true;
    this._breakpointsForUISourceCode = new Map();
    this._breakpointsForPrimaryUISourceCode = new Map();
    this._provisionalBreakpoints = new StringMultimap();
    this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectRemoved, this._projectRemoved, this);
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this);
}
WebInspector.BreakpointManager.Events = {BreakpointAdded: "breakpoint-added", BreakpointRemoved: "breakpoint-removed", BreakpointsActiveStateChanged: "BreakpointsActiveStateChanged"}
WebInspector.BreakpointManager._sourceFileId = function (uiSourceCode) {
    if (!uiSourceCode.url)
        return "";
    return uiSourceCode.uri();
}
WebInspector.BreakpointManager._breakpointStorageId = function (sourceFileId, lineNumber, columnNumber) {
    if (!sourceFileId)
        return "";
    return sourceFileId + ":" + lineNumber + ":" + columnNumber;
}
WebInspector.BreakpointManager.prototype = {
    targetAdded: function (target) {
        if (!this._breakpointsActive)
            target.debuggerAgent().setBreakpointsActive(this._breakpointsActive);
    }, targetRemoved: function (target) {
    }, _provisionalBreakpointsForSourceFileId: function (sourceFileId) {
        var result = new StringMap();
        var breakpoints = this._provisionalBreakpoints.get(sourceFileId).values();
        for (var i = 0; i < breakpoints.length; ++i)
            result.put(breakpoints[i]._breakpointStorageId(), breakpoints[i]);
        return result;
    }, removeProvisionalBreakpointsForTest: function () {
        var breakpoints = this._provisionalBreakpoints.values();
        for (var i = 0; i < breakpoints.length; ++i)
            breakpoints[i].remove();
        this._provisionalBreakpoints.clear();
    }, _restoreBreakpoints: function (uiSourceCode) {
        var sourceFileId = WebInspector.BreakpointManager._sourceFileId(uiSourceCode);
        if (!sourceFileId)
            return;
        this._storage.mute();
        var breakpointItems = this._storage.breakpointItems(uiSourceCode);
        var provisionalBreakpoints = this._provisionalBreakpointsForSourceFileId(sourceFileId);
        for (var i = 0; i < breakpointItems.length; ++i) {
            var breakpointItem = breakpointItems[i];
            var itemStorageId = WebInspector.BreakpointManager._breakpointStorageId(breakpointItem.sourceFileId, breakpointItem.lineNumber, breakpointItem.columnNumber);
            var provisionalBreakpoint = provisionalBreakpoints.get(itemStorageId);
            if (provisionalBreakpoint) {
                if (!this._breakpointsForPrimaryUISourceCode.get(uiSourceCode))
                    this._breakpointsForPrimaryUISourceCode.put(uiSourceCode, []);
                this._breakpointsForPrimaryUISourceCode.get(uiSourceCode).push(provisionalBreakpoint);
                provisionalBreakpoint._updateBreakpoint();
            } else {
                this._innerSetBreakpoint(uiSourceCode, breakpointItem.lineNumber, breakpointItem.columnNumber, breakpointItem.condition, breakpointItem.enabled);
            }
        }
        this._provisionalBreakpoints.removeAll(sourceFileId);
        this._storage.unmute();
    }, _uiSourceCodeAdded: function (event) {
        var uiSourceCode = (event.data);
        this._restoreBreakpoints(uiSourceCode);
        if (uiSourceCode.contentType() === WebInspector.resourceTypes.Script || uiSourceCode.contentType() === WebInspector.resourceTypes.Document)
            uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.SourceMappingChanged, this._uiSourceCodeMappingChanged, this);
    }, _uiSourceCodeRemoved: function (event) {
        var uiSourceCode = (event.data);
        this._removeUISourceCode(uiSourceCode);
    }, _uiSourceCodeMappingChanged: function (event) {
        var uiSourceCode = (event.target);
        var isIdentity = (event.data.isIdentity);
        var target = (event.data.target);
        if (isIdentity)
            return;
        var breakpoints = this._breakpointsForPrimaryUISourceCode.get(uiSourceCode) || [];
        for (var i = 0; i < breakpoints.length; ++i)
            breakpoints[i]._updateInDebuggerForTarget(target);
    }, _removeUISourceCode: function (uiSourceCode) {
        var breakpoints = this._breakpointsForPrimaryUISourceCode.get(uiSourceCode) || [];
        var sourceFileId = WebInspector.BreakpointManager._sourceFileId(uiSourceCode);
        for (var i = 0; i < breakpoints.length; ++i) {
            breakpoints[i]._resetLocations();
            if (breakpoints[i].enabled())
                this._provisionalBreakpoints.put(sourceFileId, breakpoints[i]);
        }
        uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.SourceMappingChanged, this._uiSourceCodeMappingChanged, this);
        this._breakpointsForPrimaryUISourceCode.remove(uiSourceCode);
    }, setBreakpoint: function (uiSourceCode, lineNumber, columnNumber, condition, enabled) {
        this.setBreakpointsActive(true);
        return this._innerSetBreakpoint(uiSourceCode, lineNumber, columnNumber, condition, enabled);
    }, _innerSetBreakpoint: function (uiSourceCode, lineNumber, columnNumber, condition, enabled) {
        var breakpoint = this.findBreakpoint(uiSourceCode, lineNumber, columnNumber);
        if (breakpoint) {
            breakpoint._updateState(condition, enabled);
            return breakpoint;
        }
        var projectId = uiSourceCode.project().id();
        var path = uiSourceCode.path();
        var sourceFileId = WebInspector.BreakpointManager._sourceFileId(uiSourceCode);
        breakpoint = new WebInspector.BreakpointManager.Breakpoint(this, projectId, path, sourceFileId, lineNumber, columnNumber, condition, enabled);
        if (!this._breakpointsForPrimaryUISourceCode.get(uiSourceCode))
            this._breakpointsForPrimaryUISourceCode.put(uiSourceCode, []);
        this._breakpointsForPrimaryUISourceCode.get(uiSourceCode).push(breakpoint);
        return breakpoint;
    }, findBreakpoint: function (uiSourceCode, lineNumber, columnNumber) {
        var breakpoints = this._breakpointsForUISourceCode.get(uiSourceCode);
        var lineBreakpoints = breakpoints ? breakpoints.get(String(lineNumber)) : null;
        var columnBreakpoints = lineBreakpoints ? lineBreakpoints.get(String(columnNumber)) : null;
        return columnBreakpoints ? columnBreakpoints[0] : null;
    }, findBreakpointOnLine: function (uiSourceCode, lineNumber) {
        var breakpoints = this._breakpointsForUISourceCode.get(uiSourceCode);
        var lineBreakpoints = breakpoints ? breakpoints.get(String(lineNumber)) : null;
        return lineBreakpoints ? lineBreakpoints.values()[0][0] : null;
    }, breakpointsForUISourceCode: function (uiSourceCode) {
        var result = [];
        var uiSourceCodeBreakpoints = this._breakpointsForUISourceCode.get(uiSourceCode);
        var breakpoints = uiSourceCodeBreakpoints ? uiSourceCodeBreakpoints.values() : [];
        for (var i = 0; i < breakpoints.length; ++i) {
            var lineBreakpoints = breakpoints[i];
            var columnBreakpointArrays = lineBreakpoints ? lineBreakpoints.values() : [];
            result = result.concat.apply(result, columnBreakpointArrays);
        }
        return result;
    }, allBreakpoints: function () {
        var result = [];
        var uiSourceCodes = this._breakpointsForUISourceCode.keys();
        for (var i = 0; i < uiSourceCodes.length; ++i)
            result = result.concat(this.breakpointsForUISourceCode(uiSourceCodes[i]));
        return result;
    }, breakpointLocationsForUISourceCode: function (uiSourceCode) {
        var uiSourceCodeBreakpoints = this._breakpointsForUISourceCode.get(uiSourceCode);
        var lineNumbers = uiSourceCodeBreakpoints ? uiSourceCodeBreakpoints.keys() : [];
        var result = [];
        for (var i = 0; i < lineNumbers.length; ++i) {
            var lineBreakpoints = uiSourceCodeBreakpoints.get(lineNumbers[i]);
            var columnNumbers = lineBreakpoints.keys();
            for (var j = 0; j < columnNumbers.length; ++j) {
                var columnBreakpoints = lineBreakpoints.get(columnNumbers[j]);
                var lineNumber = parseInt(lineNumbers[i], 10);
                var columnNumber = parseInt(columnNumbers[j], 10);
                for (var k = 0; k < columnBreakpoints.length; ++k) {
                    var breakpoint = columnBreakpoints[k];
                    var uiLocation = uiSourceCode.uiLocation(lineNumber, columnNumber);
                    result.push({breakpoint: breakpoint, uiLocation: uiLocation});
                }
            }
        }
        return result;
    }, allBreakpointLocations: function () {
        var result = [];
        var uiSourceCodes = this._breakpointsForUISourceCode.keys();
        for (var i = 0; i < uiSourceCodes.length; ++i)
            result = result.concat(this.breakpointLocationsForUISourceCode(uiSourceCodes[i]));
        return result;
    }, toggleAllBreakpoints: function (toggleState) {
        var breakpoints = this.allBreakpoints();
        for (var i = 0; i < breakpoints.length; ++i)
            breakpoints[i].setEnabled(toggleState);
    }, removeAllBreakpoints: function () {
        var breakpoints = this.allBreakpoints();
        for (var i = 0; i < breakpoints.length; ++i)
            breakpoints[i].remove();
    }, _projectRemoved: function (event) {
        var project = (event.data);
        var uiSourceCodes = project.uiSourceCodes();
        for (var i = 0; i < uiSourceCodes.length; ++i)
            this._removeUISourceCode(uiSourceCodes[i]);
    }, _removeBreakpoint: function (breakpoint, removeFromStorage) {
        var uiSourceCode = breakpoint.uiSourceCode();
        var breakpoints = uiSourceCode ? this._breakpointsForPrimaryUISourceCode.get(uiSourceCode) || [] : [];
        breakpoints.remove(breakpoint);
        if (removeFromStorage)
            this._storage._removeBreakpoint(breakpoint);
        this._provisionalBreakpoints.remove(breakpoint._sourceFileId, breakpoint);
    }, _uiLocationAdded: function (breakpoint, uiLocation) {
        var breakpoints = this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode);
        if (!breakpoints) {
            breakpoints = new StringMap();
            this._breakpointsForUISourceCode.put(uiLocation.uiSourceCode, breakpoints);
        }
        var lineBreakpoints = breakpoints.get(String(uiLocation.lineNumber));
        if (!lineBreakpoints) {
            lineBreakpoints = new StringMap();
            breakpoints.put(String(uiLocation.lineNumber), lineBreakpoints);
        }
        var columnBreakpoints = lineBreakpoints.get(String(uiLocation.columnNumber));
        if (!columnBreakpoints) {
            columnBreakpoints = [];
            lineBreakpoints.put(String(uiLocation.columnNumber), columnBreakpoints);
        }
        columnBreakpoints.push(breakpoint);
        this.dispatchEventToListeners(WebInspector.BreakpointManager.Events.BreakpointAdded, {breakpoint: breakpoint, uiLocation: uiLocation});
    }, _uiLocationRemoved: function (breakpoint, uiLocation) {
        var breakpoints = this._breakpointsForUISourceCode.get(uiLocation.uiSourceCode);
        if (!breakpoints)
            return;
        var lineBreakpoints = breakpoints.get(String(uiLocation.lineNumber));
        if (!lineBreakpoints)
            return;
        var columnBreakpoints = lineBreakpoints.get(String(uiLocation.columnNumber));
        if (!columnBreakpoints)
            return;
        columnBreakpoints.remove(breakpoint);
        if (!columnBreakpoints.length)
            lineBreakpoints.remove(String(uiLocation.columnNumber));
        if (!lineBreakpoints.size())
            breakpoints.remove(String(uiLocation.lineNumber));
        if (!breakpoints.size())
            this._breakpointsForUISourceCode.remove(uiLocation.uiSourceCode);
        this.dispatchEventToListeners(WebInspector.BreakpointManager.Events.BreakpointRemoved, {breakpoint: breakpoint, uiLocation: uiLocation});
    }, setBreakpointsActive: function (active) {
        if (this._breakpointsActive === active)
            return;
        this._breakpointsActive = active;
        var targets = WebInspector.targetManager.targets();
        for (var i = 0; i < targets.length; ++i)
            targets[i].debuggerAgent().setBreakpointsActive(active);
        this.dispatchEventToListeners(WebInspector.BreakpointManager.Events.BreakpointsActiveStateChanged, active);
    }, breakpointsActive: function () {
        return this._breakpointsActive;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.BreakpointManager.Breakpoint = function (breakpointManager, projectId, path, sourceFileId, lineNumber, columnNumber, condition, enabled) {
    this._breakpointManager = breakpointManager;
    this._projectId = projectId;
    this._path = path;
    this._lineNumber = lineNumber;
    this._columnNumber = columnNumber;
    this._sourceFileId = sourceFileId;
    this._numberOfDebuggerLocationForUILocation = {};
    this._condition;
    this._enabled;
    this._isRemoved;
    this._fakePrimaryLocation;
    this._currentState = null;
    this._targetBreakpoints = new Map();
    this._updateState(condition, enabled);
    this._breakpointManager._targetManager.observeTargets(this);
}
WebInspector.BreakpointManager.Breakpoint.prototype = {
    targetAdded: function (target) {
        this._targetBreakpoints.put(target, new WebInspector.BreakpointManager.TargetBreakpoint(target, this, this._breakpointManager._debuggerWorkspaceBinding));
    }, targetRemoved: function (target) {
        var targetBreakpoint = this._targetBreakpoints.remove(target);
        targetBreakpoint._cleanUpAfterDebuggerIsGone();
        targetBreakpoint._removeEventListeners();
    }, projectId: function () {
        return this._projectId;
    }, path: function () {
        return this._path;
    }, lineNumber: function () {
        return this._lineNumber;
    }, columnNumber: function () {
        return this._columnNumber;
    }, uiSourceCode: function () {
        return this._breakpointManager._workspace.uiSourceCode(this._projectId, this._path);
    }, _replaceUILocation: function (oldUILocation, newUILocation) {
        if (this._isRemoved)
            return;
        this._removeUILocation(oldUILocation, true);
        this._removeFakeBreakpointAtPrimaryLocation();
        if (!this._numberOfDebuggerLocationForUILocation[newUILocation.id()])
            this._numberOfDebuggerLocationForUILocation[newUILocation.id()] = 0;
        if (++this._numberOfDebuggerLocationForUILocation[newUILocation.id()] === 1)
            this._breakpointManager._uiLocationAdded(this, newUILocation);
    }, _removeUILocation: function (uiLocation, muteCreationFakeBreakpoint) {
        if (!uiLocation || --this._numberOfDebuggerLocationForUILocation[uiLocation.id()] !== 0)
            return;
        delete this._numberOfDebuggerLocationForUILocation[uiLocation.id()];
        this._breakpointManager._uiLocationRemoved(this, uiLocation);
        if (!muteCreationFakeBreakpoint)
            this._fakeBreakpointAtPrimaryLocation();
    }, enabled: function () {
        return this._enabled;
    }, setEnabled: function (enabled) {
        this._updateState(this._condition, enabled);
    }, condition: function () {
        return this._condition;
    }, setCondition: function (condition) {
        this._updateState(condition, this._enabled);
    }, _updateState: function (condition, enabled) {
        if (this._enabled === enabled && this._condition === condition)
            return;
        this._enabled = enabled;
        this._condition = condition;
        this._breakpointManager._storage._updateBreakpoint(this);
        this._updateBreakpoint();
    }, _updateBreakpoint: function () {
        this._removeFakeBreakpointAtPrimaryLocation();
        this._fakeBreakpointAtPrimaryLocation();
        var targetBreakpoints = this._targetBreakpoints.values();
        for (var i = 0; i < targetBreakpoints.length; ++i)
            targetBreakpoints[i]._scheduleUpdateInDebugger();
    }, remove: function (keepInStorage) {
        this._isRemoved = true;
        var removeFromStorage = !keepInStorage;
        this._removeFakeBreakpointAtPrimaryLocation();
        var targetBreakpoints = this._targetBreakpoints.values();
        for (var i = 0; i < targetBreakpoints.length; ++i) {
            targetBreakpoints[i]._scheduleUpdateInDebugger();
            targetBreakpoints[i]._removeEventListeners();
        }
        this._breakpointManager._removeBreakpoint(this, removeFromStorage);
        this._breakpointManager._targetManager.unobserveTargets(this);
    }, _updateInDebuggerForTarget: function (target) {
        this._targetBreakpoints.get(target)._scheduleUpdateInDebugger();
    }, _breakpointStorageId: function () {
        return WebInspector.BreakpointManager._breakpointStorageId(this._sourceFileId, this._lineNumber, this._columnNumber);
    }, _fakeBreakpointAtPrimaryLocation: function () {
        if (this._isRemoved || !Object.isEmpty(this._numberOfDebuggerLocationForUILocation) || this._fakePrimaryLocation)
            return;
        var uiSourceCode = this._breakpointManager._workspace.uiSourceCode(this._projectId, this._path);
        if (!uiSourceCode)
            return;
        this._fakePrimaryLocation = uiSourceCode.uiLocation(this._lineNumber, this._columnNumber);
        this._breakpointManager._uiLocationAdded(this, this._fakePrimaryLocation);
    }, _removeFakeBreakpointAtPrimaryLocation: function () {
        if (this._fakePrimaryLocation) {
            this._breakpointManager._uiLocationRemoved(this, this._fakePrimaryLocation);
            delete this._fakePrimaryLocation;
        }
    }, _resetLocations: function () {
        this._removeFakeBreakpointAtPrimaryLocation();
        var targetBreakpoints = this._targetBreakpoints.values();
        for (var i = 0; i < targetBreakpoints.length; ++i)
            targetBreakpoints[i]._resetLocations();
    }
}
WebInspector.BreakpointManager.TargetBreakpoint = function (target, breakpoint, debuggerWorkspaceBinding) {
    WebInspector.SDKObject.call(this, target);
    this._breakpoint = breakpoint;
    this._debuggerWorkspaceBinding = debuggerWorkspaceBinding;
    this._liveLocations = [];
    this._uiLocations = {};
    target.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasDisabled, this._cleanUpAfterDebuggerIsGone, this);
    target.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasEnabled, this._scheduleUpdateInDebugger, this);
    this._hasPendingUpdate = false;
    this._isUpdating = false;
    this._cancelCallback = false;
    this._currentState = null;
    if (target.debuggerModel.debuggerEnabled())
        this._scheduleUpdateInDebugger();
}
WebInspector.BreakpointManager.TargetBreakpoint.prototype = {
    _debuggerModel: function () {
        return this.target().debuggerModel;
    }, _resetLocations: function () {
        var uiLocations = Object.values(this._uiLocations);
        for (var i = 0; i < uiLocations.length; ++i)
            this._breakpoint._removeUILocation(uiLocations[i]);
        this._uiLocations = {};
        for (var i = 0; i < this._liveLocations.length; ++i)
            this._liveLocations[i].dispose();
        this._liveLocations = [];
    }, _scheduleUpdateInDebugger: function () {
        if (this._isUpdating) {
            this._hasPendingUpdate = true;
            return;
        }
        this._isUpdating = true;
        this._updateInDebugger(this._didUpdateInDebugger.bind(this));
    }, _didUpdateInDebugger: function () {
        this._isUpdating = false;
        if (this._hasPendingUpdate) {
            this._hasPendingUpdate = false;
            this._scheduleUpdateInDebugger();
        }
    }, _scriptDiverged: function () {
        var uiSourceCode = this._breakpoint.uiSourceCode();
        if (!uiSourceCode)
            return false;
        var scriptFile = this._debuggerWorkspaceBinding.scriptFile(uiSourceCode, this.target());
        return !!scriptFile && scriptFile.hasDivergedFromVM();
    }, _updateInDebugger: function (callback) {
        if (this.target().isDetached()) {
            this._cleanUpAfterDebuggerIsGone();
            callback();
            return;
        }
        var uiSourceCode = this._breakpoint.uiSourceCode();
        var lineNumber = this._breakpoint._lineNumber;
        var columnNumber = this._breakpoint._columnNumber;
        var condition = this._breakpoint.condition();
        var debuggerLocation = uiSourceCode ? this._debuggerWorkspaceBinding.uiLocationToRawLocation(this.target(), uiSourceCode, lineNumber, columnNumber) : null;
        var newState;
        if (this._breakpoint._isRemoved || !this._breakpoint.enabled() || this._scriptDiverged())
            newState = null; else if (debuggerLocation) {
            var script = debuggerLocation.script();
            if (script.sourceURL)
                newState = new WebInspector.BreakpointManager.Breakpoint.State(script.sourceURL, null, debuggerLocation.lineNumber, debuggerLocation.columnNumber, condition); else
                newState = new WebInspector.BreakpointManager.Breakpoint.State(null, debuggerLocation.scriptId, debuggerLocation.lineNumber, debuggerLocation.columnNumber, condition)
        } else if (this._breakpoint._currentState && this._breakpoint._currentState.url) {
            var position = this._breakpoint._currentState;
            newState = new WebInspector.BreakpointManager.Breakpoint.State(position.url, null, position.lineNumber, position.columnNumber, condition);
        } else if (uiSourceCode && uiSourceCode.url)
            newState = new WebInspector.BreakpointManager.Breakpoint.State(uiSourceCode.url, null, lineNumber, columnNumber, condition);
        if (this._debuggerId && WebInspector.BreakpointManager.Breakpoint.State.equals(newState, this._currentState)) {
            callback();
            return;
        }
        this._breakpoint._currentState = newState;
        if (this._debuggerId) {
            this._resetLocations();
            this._debuggerModel().removeBreakpoint(this._debuggerId, this._didRemoveFromDebugger.bind(this, callback));
            this._scheduleUpdateInDebugger();
            this._currentState = null;
            return;
        }
        if (!newState) {
            callback();
            return;
        }
        var updateCallback = this._didSetBreakpointInDebugger.bind(this, callback);
        if (newState.url)
            this._debuggerModel().setBreakpointByURL(newState.url, newState.lineNumber, newState.columnNumber, this._breakpoint.condition(), updateCallback); else if (newState.scriptId)
            this._debuggerModel().setBreakpointBySourceId((debuggerLocation), condition, updateCallback);
        this._currentState = newState;
    }, _didSetBreakpointInDebugger: function (callback, breakpointId, locations) {
        if (this._cancelCallback) {
            this._cancelCallback = false;
            callback();
            return;
        }
        if (!breakpointId) {
            this._breakpoint.remove(true);
            callback();
            return;
        }
        this._debuggerId = breakpointId;
        this.target().debuggerModel.addBreakpointListener(this._debuggerId, this._breakpointResolved, this);
        for (var i = 0; i < locations.length; ++i) {
            if (!this._addResolvedLocation(locations[i]))
                break;
        }
        callback();
    }, _didRemoveFromDebugger: function (callback) {
        if (this._cancelCallback) {
            this._cancelCallback = false;
            callback();
            return;
        }
        this._resetLocations();
        this.target().debuggerModel.removeBreakpointListener(this._debuggerId, this._breakpointResolved, this);
        delete this._debuggerId;
        callback();
    }, _breakpointResolved: function (event) {
        this._addResolvedLocation((event.data));
    }, _locationUpdated: function (location, uiLocation) {
        var oldUILocation = this._uiLocations[location.id()] || null;
        this._uiLocations[location.id()] = uiLocation;
        this._breakpoint._replaceUILocation(oldUILocation, uiLocation);
    }, _addResolvedLocation: function (location) {
        var uiLocation = this._debuggerWorkspaceBinding.rawLocationToUILocation(location);
        var breakpoint = this._breakpoint._breakpointManager.findBreakpoint(uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber);
        if (breakpoint && breakpoint !== this._breakpoint) {
            this._breakpoint.remove();
            return false;
        }
        this._liveLocations.push(this._debuggerWorkspaceBinding.createLiveLocation(location, this._locationUpdated.bind(this, location)));
        return true;
    }, _cleanUpAfterDebuggerIsGone: function () {
        if (this._isUpdating)
            this._cancelCallback = true;
        this._resetLocations();
        this._currentState = null;
        if (this._debuggerId)
            this._didRemoveFromDebugger(function () {
            });
    }, _removeEventListeners: function () {
        this.target().debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.DebuggerWasDisabled, this._cleanUpAfterDebuggerIsGone, this);
        this.target().debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.DebuggerWasEnabled, this._scheduleUpdateInDebugger, this);
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.BreakpointManager.Breakpoint.State = function (url, scriptId, lineNumber, columnNumber, condition) {
    this.url = url;
    this.scriptId = scriptId;
    this.lineNumber = lineNumber;
    this.columnNumber = columnNumber;
    this.condition = condition;
}
WebInspector.BreakpointManager.Breakpoint.State.equals = function (stateA, stateB) {
    if (!stateA || !stateB)
        return false;
    if (stateA.scriptId || stateB.scriptId)
        return false;
    return stateA.url === stateB.url && stateA.lineNumber === stateB.lineNumber && stateA.columnNumber === stateB.columnNumber && stateA.condition === stateB.condition;
}
WebInspector.BreakpointManager.Storage = function (breakpointManager, setting) {
    this._breakpointManager = breakpointManager;
    this._setting = setting;
    var breakpoints = this._setting.get();
    this._breakpoints = {};
    for (var i = 0; i < breakpoints.length; ++i) {
        var breakpoint = (breakpoints[i]);
        breakpoint.columnNumber = breakpoint.columnNumber || 0;
        this._breakpoints[breakpoint.sourceFileId + ":" + breakpoint.lineNumber + ":" + breakpoint.columnNumber] = breakpoint;
    }
}
WebInspector.BreakpointManager.Storage.prototype = {
    mute: function () {
        this._muted = true;
    }, unmute: function () {
        delete this._muted;
    }, breakpointItems: function (uiSourceCode) {
        var result = [];
        var sourceFileId = WebInspector.BreakpointManager._sourceFileId(uiSourceCode);
        for (var id in this._breakpoints) {
            var breakpoint = this._breakpoints[id];
            if (breakpoint.sourceFileId === sourceFileId)
                result.push(breakpoint);
        }
        return result;
    }, _updateBreakpoint: function (breakpoint) {
        if (this._muted || !breakpoint._breakpointStorageId())
            return;
        this._breakpoints[breakpoint._breakpointStorageId()] = new WebInspector.BreakpointManager.Storage.Item(breakpoint);
        this._save();
    }, _removeBreakpoint: function (breakpoint) {
        if (this._muted)
            return;
        delete this._breakpoints[breakpoint._breakpointStorageId()];
        this._save();
    }, _save: function () {
        var breakpointsArray = [];
        for (var id in this._breakpoints)
            breakpointsArray.push(this._breakpoints[id]);
        this._setting.set(breakpointsArray);
    }
}
WebInspector.BreakpointManager.Storage.Item = function (breakpoint) {
    this.sourceFileId = breakpoint._sourceFileId;
    this.lineNumber = breakpoint.lineNumber();
    this.columnNumber = breakpoint.columnNumber();
    this.condition = breakpoint.condition();
    this.enabled = breakpoint.enabled();
}
WebInspector.breakpointManager;
WebInspector.ConcatenatedScriptsContentProvider = function (scripts) {
    this._scripts = scripts;
}
WebInspector.ConcatenatedScriptsContentProvider.scriptOpenTag = "<script>";
WebInspector.ConcatenatedScriptsContentProvider.scriptCloseTag = "</script>";
WebInspector.ConcatenatedScriptsContentProvider.prototype = {
    _sortedScripts: function () {
        if (this._sortedScriptsArray)
            return this._sortedScriptsArray;
        this._sortedScriptsArray = [];
        var scripts = this._scripts.slice();
        scripts.sort(function (x, y) {
            return x.lineOffset - y.lineOffset || x.columnOffset - y.columnOffset;
        });
        var scriptOpenTagLength = WebInspector.ConcatenatedScriptsContentProvider.scriptOpenTag.length;
        var scriptCloseTagLength = WebInspector.ConcatenatedScriptsContentProvider.scriptCloseTag.length;
        this._sortedScriptsArray.push(scripts[0]);
        for (var i = 1; i < scripts.length; ++i) {
            var previousScript = this._sortedScriptsArray[this._sortedScriptsArray.length - 1];
            var lineNumber = previousScript.endLine;
            var columnNumber = previousScript.endColumn + scriptCloseTagLength + scriptOpenTagLength;
            if (lineNumber < scripts[i].lineOffset || (lineNumber === scripts[i].lineOffset && columnNumber <= scripts[i].columnOffset))
                this._sortedScriptsArray.push(scripts[i]);
        }
        return this._sortedScriptsArray;
    }, contentURL: function () {
        return "";
    }, contentType: function () {
        return WebInspector.resourceTypes.Document;
    }, requestContent: function (callback) {
        var scripts = this._sortedScripts();
        var sources = [];

        function didRequestSource(content) {
            sources.push(content);
            if (sources.length == scripts.length)
                callback(this._concatenateScriptsContent(scripts, sources));
        }

        for (var i = 0; i < scripts.length; ++i)
            scripts[i].requestContent(didRequestSource.bind(this));
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        var results = {};
        var scripts = this._sortedScripts();
        var scriptsLeft = scripts.length;

        function maybeCallback() {
            if (scriptsLeft)
                return;
            var result = [];
            for (var i = 0; i < scripts.length; ++i)
                result = result.concat(results[scripts[i].scriptId]);
            callback(result);
        }

        function searchCallback(script, searchMatches) {
            results[script.scriptId] = [];
            for (var i = 0; i < searchMatches.length; ++i) {
                var searchMatch = new WebInspector.ContentProvider.SearchMatch(searchMatches[i].lineNumber + script.lineOffset, searchMatches[i].lineContent);
                results[script.scriptId].push(searchMatch);
            }
            scriptsLeft--;
            maybeCallback();
        }

        maybeCallback();
        for (var i = 0; i < scripts.length; ++i)
            scripts[i].searchInContent(query, caseSensitive, isRegex, searchCallback.bind(null, scripts[i]));
    }, _concatenateScriptsContent: function (scripts, sources) {
        var content = "";
        var lineNumber = 0;
        var columnNumber = 0;
        var scriptOpenTag = WebInspector.ConcatenatedScriptsContentProvider.scriptOpenTag;
        var scriptCloseTag = WebInspector.ConcatenatedScriptsContentProvider.scriptCloseTag;
        for (var i = 0; i < scripts.length; ++i) {
            for (var newLinesCount = scripts[i].lineOffset - lineNumber; newLinesCount > 0; --newLinesCount) {
                columnNumber = 0;
                content += "\n";
            }
            for (var spacesCount = scripts[i].columnOffset - columnNumber - scriptOpenTag.length; spacesCount > 0; --spacesCount)
                content += " ";
            content += scriptOpenTag;
            content += sources[i];
            content += scriptCloseTag;
            lineNumber = scripts[i].endLine;
            columnNumber = scripts[i].endColumn + scriptCloseTag.length;
        }
        return content;
    }
}
WebInspector.CompilerSourceMappingContentProvider = function (sourceURL, contentType) {
    this._sourceURL = sourceURL;
    this._contentType = contentType;
}
WebInspector.CompilerSourceMappingContentProvider.prototype = {
    contentURL: function () {
        return this._sourceURL;
    }, contentType: function () {
        return this._contentType;
    }, requestContent: function (callback) {
        NetworkAgent.loadResourceForFrontend(WebInspector.resourceTreeModel.mainFrame.id, this._sourceURL, undefined, contentLoaded.bind(this));
        function contentLoaded(error, statusCode, headers, content) {
            if (error || statusCode >= 400) {
                console.error("Could not load content for " + this._sourceURL + " : " + (error || ("HTTP status code: " + statusCode)));
                callback(null);
                return;
            }
            callback(content);
        }
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        this.requestContent(contentLoaded);
        function contentLoaded(content) {
            if (typeof content !== "string") {
                callback([]);
                return;
            }
            callback(WebInspector.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex));
        }
    }
}
WebInspector.DefaultScriptMapping = function (debuggerModel, workspace, debuggerWorkspaceBinding) {
    this._debuggerModel = debuggerModel;
    this._debuggerWorkspaceBinding = debuggerWorkspaceBinding;
    this._workspace = workspace;
    this._projectId = WebInspector.DefaultScriptMapping.projectIdForTarget(debuggerModel.target());
    this._projectDelegate = new WebInspector.DebuggerProjectDelegate(this._workspace, this._projectId, WebInspector.projectTypes.Debugger);
    debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
    this._debuggerReset();
}
WebInspector.DefaultScriptMapping.prototype = {
    rawLocationToUILocation: function (rawLocation) {
        var debuggerModelLocation = (rawLocation);
        var script = debuggerModelLocation.script();
        var uiSourceCode = this._uiSourceCodeForScriptId[script.scriptId];
        var lineNumber = debuggerModelLocation.lineNumber;
        var columnNumber = debuggerModelLocation.columnNumber || 0;
        return uiSourceCode.uiLocation(lineNumber, columnNumber);
    }, uiLocationToRawLocation: function (uiSourceCode, lineNumber, columnNumber) {
        var scriptId = this._scriptIdForUISourceCode.get(uiSourceCode);
        var script = this._debuggerModel.scriptForId(scriptId);
        return this._debuggerModel.createRawLocation(script, lineNumber, columnNumber);
    }, addScript: function (script) {
        var path = this._projectDelegate.addScript(script);
        var uiSourceCode = this._workspace.uiSourceCode(this._projectId, path);
        if (!uiSourceCode) {
            console.assert(uiSourceCode);
            return;
        }
        this._uiSourceCodeForScriptId[script.scriptId] = uiSourceCode;
        this._scriptIdForUISourceCode.put(uiSourceCode, script.scriptId);
        this._debuggerWorkspaceBinding.setSourceMapping(this._debuggerModel.target(), uiSourceCode, this);
        this._debuggerWorkspaceBinding.pushSourceMapping(script, this);
        script.addEventListener(WebInspector.Script.Events.ScriptEdited, this._scriptEdited.bind(this, script.scriptId));
    }, isIdentity: function () {
        return true;
    }, uiLineHasMapping: function (uiSourceCode, lineNumber) {
        return true;
    }, _scriptEdited: function (scriptId, event) {
        var content = (event.data);
        this._uiSourceCodeForScriptId[scriptId].addRevision(content);
    }, _debuggerReset: function () {
        this._uiSourceCodeForScriptId = {};
        this._scriptIdForUISourceCode = new Map();
        this._projectDelegate.reset();
    }, dispose: function () {
        this._workspace.removeProject(this._projectId);
    }
}
WebInspector.DefaultScriptMapping.projectIdForTarget = function (target) {
    return "debugger:" + target.id();
}
WebInspector.DebuggerProjectDelegate = function (workspace, id, type) {
    WebInspector.ContentProviderBasedProjectDelegate.call(this, workspace, id, type);
}
WebInspector.DebuggerProjectDelegate.prototype = {
    displayName: function () {
        return "";
    }, addScript: function (script) {
        var contentProvider = script.isInlineScript() ? new WebInspector.ConcatenatedScriptsContentProvider([script]) : script;
        var splitURL = WebInspector.ParsedURL.splitURL(script.sourceURL);
        var name = splitURL[splitURL.length - 1];
        name = "VM" + script.scriptId + (name ? " " + name : "");
        return this.addContentProvider("", name, script.sourceURL, contentProvider);
    }, __proto__: WebInspector.ContentProviderBasedProjectDelegate.prototype
}
WebInspector.ResourceScriptMapping = function (debuggerModel, workspace, debuggerWorkspaceBinding) {
    this._target = debuggerModel.target();
    this._debuggerModel = debuggerModel;
    this._workspace = workspace;
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this);
    this._debuggerWorkspaceBinding = debuggerWorkspaceBinding;
    this._boundURLs = new StringSet();
    this._uiSourceCodeToScriptFile = new Map();
    debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
}
WebInspector.ResourceScriptMapping.prototype = {
    rawLocationToUILocation: function (rawLocation) {
        var debuggerModelLocation = (rawLocation);
        var script = debuggerModelLocation.script();
        var uiSourceCode = this._workspaceUISourceCodeForScript(script);
        if (!uiSourceCode)
            return null;
        var scriptFile = this.scriptFile(uiSourceCode);
        if (scriptFile && ((scriptFile.hasDivergedFromVM() && !scriptFile.isMergingToVM()) || scriptFile.isDivergingFromVM()))
            return null;
        return uiSourceCode.uiLocation(debuggerModelLocation.lineNumber, debuggerModelLocation.columnNumber || 0);
    }, uiLocationToRawLocation: function (uiSourceCode, lineNumber, columnNumber) {
        var scripts = this._scriptsForUISourceCode(uiSourceCode);
        console.assert(scripts.length);
        return this._debuggerModel.createRawLocation(scripts[0], lineNumber, columnNumber);
    }, addScript: function (script) {
        if (script.isAnonymousScript())
            return;
        this._debuggerWorkspaceBinding.pushSourceMapping(script, this);
        var uiSourceCode = this._workspaceUISourceCodeForScript(script);
        if (!uiSourceCode)
            return;
        this._bindUISourceCodeToScripts(uiSourceCode, [script]);
    }, isIdentity: function () {
        return true;
    }, uiLineHasMapping: function (uiSourceCode, lineNumber) {
        return true;
    }, scriptFile: function (uiSourceCode) {
        return this._uiSourceCodeToScriptFile.get(uiSourceCode) || null;
    }, _setScriptFile: function (uiSourceCode, scriptFile) {
        if (scriptFile)
            this._uiSourceCodeToScriptFile.put(uiSourceCode, scriptFile); else
            this._uiSourceCodeToScriptFile.remove(uiSourceCode);
    }, _uiSourceCodeAdded: function (event) {
        var uiSourceCode = (event.data);
        if (!uiSourceCode.url)
            return;
        if (uiSourceCode.project().isServiceProject())
            return;
        var scripts = this._scriptsForUISourceCode(uiSourceCode);
        if (!scripts.length)
            return;
        this._bindUISourceCodeToScripts(uiSourceCode, scripts);
    }, _uiSourceCodeRemoved: function (event) {
        var uiSourceCode = (event.data);
        if (!uiSourceCode.url)
            return;
        if (uiSourceCode.project().isServiceProject())
            return;
        this._unbindUISourceCode(uiSourceCode);
    }, _hasMergedToVM: function (uiSourceCode) {
        var scripts = this._scriptsForUISourceCode(uiSourceCode);
        if (!scripts.length)
            return;
        for (var i = 0; i < scripts.length; ++i)
            this._debuggerWorkspaceBinding.updateLocations(scripts[i]);
    }, _hasDivergedFromVM: function (uiSourceCode) {
        var scripts = this._scriptsForUISourceCode(uiSourceCode);
        if (!scripts.length)
            return;
        for (var i = 0; i < scripts.length; ++i)
            this._debuggerWorkspaceBinding.updateLocations(scripts[i]);
    }, _workspaceUISourceCodeForScript: function (script) {
        if (script.isAnonymousScript())
            return null;
        return this._workspace.uiSourceCodeForURL(script.sourceURL);
    }, _scriptsForUISourceCode: function (uiSourceCode) {
        if (!uiSourceCode.url)
            return [];
        return this._debuggerModel.scriptsForSourceURL(uiSourceCode.url);
    }, _bindUISourceCodeToScripts: function (uiSourceCode, scripts) {
        console.assert(scripts.length);
        var scriptFile = new WebInspector.ResourceScriptFile(this, uiSourceCode, scripts);
        this._setScriptFile(uiSourceCode, scriptFile);
        for (var i = 0; i < scripts.length; ++i)
            this._debuggerWorkspaceBinding.updateLocations(scripts[i]);
        this._debuggerWorkspaceBinding.setSourceMapping(this._target, uiSourceCode, this);
        this._boundURLs.add(uiSourceCode.url);
    }, _unbindUISourceCode: function (uiSourceCode) {
        var scriptFile = this.scriptFile(uiSourceCode);
        if (scriptFile) {
            scriptFile.dispose();
            this._setScriptFile(uiSourceCode, null);
        }
        this._debuggerWorkspaceBinding.setSourceMapping(this._target, uiSourceCode, null);
    }, _debuggerReset: function () {
        var boundURLs = this._boundURLs.values();
        for (var i = 0; i < boundURLs.length; ++i) {
            var uiSourceCode = this._workspace.uiSourceCodeForURL(boundURLs[i]);
            if (!uiSourceCode)
                continue;
            this._unbindUISourceCode(uiSourceCode);
        }
        this._boundURLs.clear();
    }, dispose: function () {
        this._debuggerReset();
        this._workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
        this._workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this);
    }
}
WebInspector.ResourceScriptFile = function (resourceScriptMapping, uiSourceCode, scripts) {
    console.assert(scripts.length);
    this._resourceScriptMapping = resourceScriptMapping;
    this._uiSourceCode = uiSourceCode;
    if (this._uiSourceCode.contentType() === WebInspector.resourceTypes.Script)
        this._script = scripts[0];
    this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this);
    this._update();
}
WebInspector.ResourceScriptFile.Events = {DidMergeToVM: "DidMergeToVM", DidDivergeFromVM: "DidDivergeFromVM",}
WebInspector.ResourceScriptFile.prototype = {
    commitLiveEdit: function (callback) {
        var target = this._resourceScriptMapping._target;

        function innerCallback(error, errorData) {
            if (!error)
                this._scriptSource = source;
            this._update();
            if (callback)
                callback(error, errorData, this._script);
        }

        if (!this._script)
            return;
        var source = this._uiSourceCode.workingCopy();
        target.debuggerModel.setScriptSource(this._script.scriptId, source, innerCallback.bind(this));
    }, _isDiverged: function () {
        if (this._uiSourceCode.isDirty())
            return true;
        if (!this._script)
            return false;
        if (typeof this._scriptSource === "undefined")
            return false;
        if (!this._uiSourceCode.workingCopy().startsWith(this._scriptSource))
            return true;
        var suffix = this._uiSourceCode.workingCopy().substr(this._scriptSource.length);
        return !!suffix.length && !suffix.match(WebInspector.Script.sourceURLRegex);
    }, _workingCopyChanged: function (event) {
        this._update();
    }, _update: function () {
        if (this._isDiverged() && !this._hasDivergedFromVM)
            this._divergeFromVM(); else if (!this._isDiverged() && this._hasDivergedFromVM)
            this._mergeToVM();
    }, _divergeFromVM: function () {
        this._isDivergingFromVM = true;
        this._resourceScriptMapping._hasDivergedFromVM(this._uiSourceCode);
        delete this._isDivergingFromVM;
        this._hasDivergedFromVM = true;
        this.dispatchEventToListeners(WebInspector.ResourceScriptFile.Events.DidDivergeFromVM, this._uiSourceCode);
    }, _mergeToVM: function () {
        delete this._hasDivergedFromVM;
        this._isMergingToVM = true;
        this._resourceScriptMapping._hasMergedToVM(this._uiSourceCode);
        delete this._isMergingToVM;
        this.dispatchEventToListeners(WebInspector.ResourceScriptFile.Events.DidMergeToVM, this._uiSourceCode);
    }, hasDivergedFromVM: function () {
        return this._hasDivergedFromVM;
    }, isDivergingFromVM: function () {
        return this._isDivergingFromVM;
    }, isMergingToVM: function () {
        return this._isMergingToVM;
    }, checkMapping: function () {
        if (!this._script)
            return;
        if (typeof this._scriptSource !== "undefined")
            return;
        this._script.requestContent(callback.bind(this));
        function callback(source) {
            this._scriptSource = source;
            this._update();
        }
    }, target: function () {
        if (!this._script)
            return null;
        return this._script.target();
    }, dispose: function () {
        this._uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this);
    }, addSourceMapURL: function (sourceMapURL) {
        if (!this._script)
            return;
        this._script.addSourceMapURL(sourceMapURL);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.CompilerScriptMapping = function (debuggerModel, workspace, networkWorkspaceBinding, debuggerWorkspaceBinding) {
    this._target = debuggerModel.target();
    this._debuggerModel = debuggerModel;
    this._workspace = workspace;
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAddedToWorkspace, this);
    this._networkWorkspaceBinding = networkWorkspaceBinding;
    this._debuggerWorkspaceBinding = debuggerWorkspaceBinding;
    this._sourceMapForSourceMapURL = {};
    this._pendingSourceMapLoadingCallbacks = {};
    this._sourceMapForScriptId = {};
    this._scriptForSourceMap = new Map();
    this._sourceMapForURL = new StringMap();
    debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
}
WebInspector.CompilerScriptMapping.prototype = {
    rawLocationToUILocation: function (rawLocation) {
        var debuggerModelLocation = (rawLocation);
        var sourceMap = this._sourceMapForScriptId[debuggerModelLocation.scriptId];
        if (!sourceMap)
            return null;
        var lineNumber = debuggerModelLocation.lineNumber;
        var columnNumber = debuggerModelLocation.columnNumber || 0;
        var entry = sourceMap.findEntry(lineNumber, columnNumber);
        if (!entry || entry.length === 2)
            return null;
        var url = (entry[2]);
        var uiSourceCode = this._workspace.uiSourceCodeForURL(url);
        if (!uiSourceCode)
            return null;
        return uiSourceCode.uiLocation((entry[3]), (entry[4]));
    }, uiLocationToRawLocation: function (uiSourceCode, lineNumber, columnNumber) {
        if (!uiSourceCode.url)
            return null;
        var sourceMap = this._sourceMapForURL.get(uiSourceCode.url);
        if (!sourceMap)
            return null;
        var script = (this._scriptForSourceMap.get(sourceMap));
        console.assert(script);
        var mappingSearchLinesCount = 5;
        var entry = sourceMap.findEntryReversed(uiSourceCode.url, lineNumber, mappingSearchLinesCount);
        if (!entry)
            return null;
        return this._debuggerModel.createRawLocation(script, (entry[0]), (entry[1]));
    }, addScript: function (script) {
        this._debuggerWorkspaceBinding.pushSourceMapping(script, this);
        script.addEventListener(WebInspector.Script.Events.SourceMapURLAdded, this._sourceMapURLAdded.bind(this));
        this._processScript(script);
    }, _sourceMapURLAdded: function (event) {
        var script = (event.target);
        this._processScript(script);
    }, _processScript: function (script) {
        this.loadSourceMapForScript(script, sourceMapLoaded.bind(this));
        function sourceMapLoaded(sourceMap) {
            if (!sourceMap)
                return;
            if (this._scriptForSourceMap.get(sourceMap)) {
                this._sourceMapForScriptId[script.scriptId] = sourceMap;
                this._debuggerWorkspaceBinding.updateLocations(script);
                return;
            }
            this._sourceMapForScriptId[script.scriptId] = sourceMap;
            this._scriptForSourceMap.put(sourceMap, script);
            var sourceURLs = sourceMap.sources();
            for (var i = 0; i < sourceURLs.length; ++i) {
                var sourceURL = sourceURLs[i];
                if (this._sourceMapForURL.get(sourceURL))
                    continue;
                this._sourceMapForURL.put(sourceURL, sourceMap);
                if (!this._workspace.hasMappingForURL(sourceURL) && !this._workspace.uiSourceCodeForURL(sourceURL)) {
                    var contentProvider = sourceMap.sourceContentProvider(sourceURL, WebInspector.resourceTypes.Script);
                    this._networkWorkspaceBinding.addFileForURL(sourceURL, contentProvider, script.isContentScript());
                }
                var uiSourceCode = this._workspace.uiSourceCodeForURL(sourceURL);
                if (uiSourceCode)
                    this._bindUISourceCode(uiSourceCode); else
                    WebInspector.console.error(WebInspector.UIString("Failed to locate workspace file mapped to URL %s from source map %s", sourceURL, sourceMap.url()));
            }
            this._debuggerWorkspaceBinding.updateLocations(script);
        }
    }, isIdentity: function () {
        return false;
    }, uiLineHasMapping: function (uiSourceCode, lineNumber) {
        if (!uiSourceCode.url)
            return true;
        var sourceMap = this._sourceMapForURL.get(uiSourceCode.url);
        if (!sourceMap)
            return true;
        return !!sourceMap.findEntryReversed(uiSourceCode.url, lineNumber, 0);
    }, _bindUISourceCode: function (uiSourceCode) {
        this._debuggerWorkspaceBinding.setSourceMapping(this._target, uiSourceCode, this);
    }, _unbindUISourceCode: function (uiSourceCode) {
        this._debuggerWorkspaceBinding.setSourceMapping(this._target, uiSourceCode, null);
    }, _uiSourceCodeAddedToWorkspace: function (event) {
        var uiSourceCode = (event.data);
        if (!uiSourceCode.url || !this._sourceMapForURL.get(uiSourceCode.url))
            return;
        this._bindUISourceCode(uiSourceCode);
    }, loadSourceMapForScript: function (script, callback) {
        if (!script.sourceMapURL) {
            callback(null);
            return;
        }
        var scriptURL = WebInspector.ParsedURL.completeURL(script.target().resourceTreeModel.inspectedPageURL(), script.sourceURL);
        if (!scriptURL) {
            callback(null);
            return;
        }
        var sourceMapURL = WebInspector.ParsedURL.completeURL(scriptURL, script.sourceMapURL);
        if (!sourceMapURL) {
            callback(null);
            return;
        }
        var sourceMap = this._sourceMapForSourceMapURL[sourceMapURL];
        if (sourceMap) {
            callback(sourceMap);
            return;
        }
        var pendingCallbacks = this._pendingSourceMapLoadingCallbacks[sourceMapURL];
        if (pendingCallbacks) {
            pendingCallbacks.push(callback);
            return;
        }
        pendingCallbacks = [callback];
        this._pendingSourceMapLoadingCallbacks[sourceMapURL] = pendingCallbacks;
        WebInspector.SourceMap.load(sourceMapURL, scriptURL, sourceMapLoaded.bind(this));
        function sourceMapLoaded(sourceMap) {
            var url = (sourceMapURL);
            var callbacks = this._pendingSourceMapLoadingCallbacks[url];
            delete this._pendingSourceMapLoadingCallbacks[url];
            if (!callbacks)
                return;
            if (sourceMap)
                this._sourceMapForSourceMapURL[url] = sourceMap;
            for (var i = 0; i < callbacks.length; ++i)
                callbacks[i](sourceMap);
        }
    }, _debuggerReset: function () {
        function unbindUISourceCodeForURL(sourceURL) {
            var uiSourceCode = this._workspace.uiSourceCodeForURL(sourceURL);
            if (!uiSourceCode)
                return;
            this._unbindUISourceCode(uiSourceCode);
        }

        this._sourceMapForURL.keys().forEach(unbindUISourceCodeForURL.bind(this));
        this._sourceMapForSourceMapURL = {};
        this._pendingSourceMapLoadingCallbacks = {};
        this._sourceMapForScriptId = {};
        this._scriptForSourceMap.clear();
        this._sourceMapForURL.clear();
    }, dispose: function () {
        this._workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAddedToWorkspace, this);
    }
}
WebInspector.LiveEditSupport = function (target, workspace, debuggerWorkspaceBinding) {
    WebInspector.SDKObject.call(this, target);
    this._workspace = workspace;
    this._debuggerWorkspaceBinding = debuggerWorkspaceBinding;
    this._projectId = "liveedit:" + target.id();
    this._projectDelegate = new WebInspector.DebuggerProjectDelegate(workspace, this._projectId, WebInspector.projectTypes.LiveEdit);
    target.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);
    this._debuggerReset();
}
WebInspector.LiveEditSupport.prototype = {
    uiSourceCodeForLiveEdit: function (uiSourceCode) {
        var debuggerModelLocation = this._debuggerWorkspaceBinding.uiLocationToRawLocation(this.target(), uiSourceCode, 0, 0);
        if (!debuggerModelLocation)
            return null;
        var uiLocation = this._debuggerWorkspaceBinding.rawLocationToUILocation(debuggerModelLocation);
        if (uiLocation.uiSourceCode !== uiSourceCode)
            return uiLocation.uiSourceCode;
        var script = debuggerModelLocation.script();
        if (this._uiSourceCodeForScriptId[script.scriptId])
            return this._uiSourceCodeForScriptId[script.scriptId];
        console.assert(!script.isInlineScript());
        var path = this._projectDelegate.addScript(script);
        var liveEditUISourceCode = this._workspace.uiSourceCode(this._projectId, path);
        liveEditUISourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this);
        this._uiSourceCodeForScriptId[script.scriptId] = liveEditUISourceCode;
        this._scriptIdForUISourceCode.put(liveEditUISourceCode, script.scriptId);
        return liveEditUISourceCode;
    }, _debuggerReset: function () {
        this._uiSourceCodeForScriptId = {};
        this._scriptIdForUISourceCode = new Map();
        this._projectDelegate.reset();
    }, _workingCopyCommitted: function (event) {
        var uiSourceCode = (event.target);
        var scriptId = (this._scriptIdForUISourceCode.get(uiSourceCode));
        this.target().debuggerModel.setScriptSource(scriptId, uiSourceCode.workingCopy(), innerCallback.bind(this));
        function innerCallback(error, errorData) {
            if (error) {
                var script = this.target().debuggerModel.scriptForId(scriptId);
                WebInspector.LiveEditSupport.logDetailedError(error, errorData, script);
                return;
            }
            WebInspector.LiveEditSupport.logSuccess();
        }
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.LiveEditSupport.liveEditSupportForUISourceCode = function (uiSourceCode) {
    var projectId = uiSourceCode.project().id();
    var target = null;
    var targets = WebInspector.targetManager.targets();
    for (var i = 0; i < targets.length; ++i) {
        if (projectId === WebInspector.DefaultScriptMapping.projectIdForTarget(targets[i])) {
            target = targets[i];
            break;
        }
    }
    return target ? WebInspector.debuggerWorkspaceBinding.liveEditSupport(target) : null;
}
WebInspector.LiveEditSupport.logDetailedError = function (error, errorData, contextScript) {
    var warningLevel = WebInspector.Console.MessageLevel.Warning;
    if (!errorData) {
        if (error)
            WebInspector.console.addMessage(WebInspector.UIString("LiveEdit failed: %s", error), warningLevel);
        return;
    }
    var compileError = errorData.compileError;
    if (compileError) {
        var location = contextScript ? WebInspector.UIString(" at %s:%d:%d", contextScript.sourceURL, compileError.lineNumber, compileError.columnNumber) : "";
        var message = WebInspector.UIString("LiveEdit compile failed: %s%s", compileError.message, location);
        WebInspector.console.error(message);
    } else {
        WebInspector.console.addMessage(WebInspector.UIString("Unknown LiveEdit error: %s; %s", JSON.stringify(errorData), error), warningLevel);
    }
}
WebInspector.LiveEditSupport.logSuccess = function () {
    WebInspector.console.log(WebInspector.UIString("Recompilation and update succeeded."));
}
WebInspector.SASSSourceMapping = function (cssModel, workspace, networkWorkspaceBinding) {
    this.pollPeriodMs = 5000;
    this.pollIntervalMs = 200;
    this._cssModel = cssModel;
    this._workspace = workspace;
    this._networkWorkspaceBinding = networkWorkspaceBinding;
    this._addingRevisionCounter = 0;
    this._reset();
    WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.SavedURL, this._fileSaveFinished, this);
    WebInspector.settings.cssSourceMapsEnabled.addChangeListener(this._toggleSourceMapSupport, this)
    this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._styleSheetChanged, this);
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this);
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeContentCommitted, this._uiSourceCodeContentCommitted, this);
    this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectRemoved, this._reset, this);
}
WebInspector.SASSSourceMapping.prototype = {
    _styleSheetChanged: function (event) {
        var id = (event.data.styleSheetId);
        if (this._addingRevisionCounter) {
            --this._addingRevisionCounter;
            return;
        }
        var header = this._cssModel.styleSheetHeaderForId(id);
        if (!header)
            return;
        this.removeHeader(header);
    }, _toggleSourceMapSupport: function (event) {
        var enabled = (event.data);
        var headers = this._cssModel.styleSheetHeaders();
        for (var i = 0; i < headers.length; ++i) {
            if (enabled)
                this.addHeader(headers[i]); else
                this.removeHeader(headers[i]);
        }
    }, _fileSaveFinished: function (event) {
        var sassURL = (event.data);
        this._sassFileSaved(sassURL, false);
    }, _headerValue: function (headerName, headers) {
        headerName = headerName.toLowerCase();
        var value = null;
        for (var name in headers) {
            if (name.toLowerCase() === headerName) {
                value = headers[name];
                break;
            }
        }
        return value;
    }, _lastModified: function (headers) {
        var lastModifiedHeader = this._headerValue("last-modified", headers);
        if (!lastModifiedHeader)
            return null;
        var lastModified = new Date(lastModifiedHeader);
        if (isNaN(lastModified.getTime()))
            return null;
        return lastModified;
    }, _checkLastModified: function (headers, url) {
        var lastModified = this._lastModified(headers);
        if (lastModified)
            return lastModified;
        var etagMessage = this._headerValue("etag", headers) ? ", \"ETag\" response header found instead" : "";
        var message = String.sprintf("The \"Last-Modified\" response header is missing or invalid for %s%s. The CSS auto-reload functionality will not work correctly.", url, etagMessage);
        WebInspector.console.log(message);
        return null;
    }, _sassFileSaved: function (sassURL, wasLoadedFromFileSystem) {
        var cssURLs = this._cssURLsForSASSURL[sassURL];
        if (!cssURLs)
            return;
        if (!WebInspector.settings.cssReloadEnabled.get())
            return;
        var sassFile = this._workspace.uiSourceCodeForURL(sassURL);
        console.assert(sassFile);
        if (wasLoadedFromFileSystem)
            sassFile.requestMetadata(metadataReceived.bind(this)); else
            NetworkAgent.loadResourceForFrontend(WebInspector.resourceTreeModel.mainFrame.id, sassURL, undefined, sassLoadedViaNetwork.bind(this));
        function sassLoadedViaNetwork(error, statusCode, headers, content) {
            if (error || statusCode >= 400) {
                console.error("Could not load content for " + sassURL + " : " + (error || ("HTTP status code: " + statusCode)));
                return;
            }
            var lastModified = this._checkLastModified(headers, sassURL);
            if (!lastModified)
                return;
            metadataReceived.call(this, lastModified);
        }

        function metadataReceived(timestamp) {
            if (!timestamp)
                return;
            var now = Date.now();
            var deadlineMs = now + this.pollPeriodMs;
            var pollData = this._pollDataForSASSURL[sassURL];
            if (pollData) {
                var dataByURL = pollData.dataByURL;
                for (var url in dataByURL)
                    clearTimeout(dataByURL[url].timer);
            }
            pollData = {dataByURL: {}, deadlineMs: deadlineMs, sassTimestamp: timestamp};
            this._pollDataForSASSURL[sassURL] = pollData;
            for (var i = 0; i < cssURLs.length; ++i) {
                pollData.dataByURL[cssURLs[i]] = {previousPoll: now};
                this._pollCallback(cssURLs[i], sassURL, false);
            }
        }
    }, _pollCallback: function (cssURL, sassURL, stopPolling) {
        var now;
        var pollData = this._pollDataForSASSURL[sassURL];
        if (!pollData)
            return;
        if (stopPolling || (now = new Date().getTime()) > pollData.deadlineMs) {
            delete pollData.dataByURL[cssURL];
            if (!Object.keys(pollData.dataByURL).length)
                delete this._pollDataForSASSURL[sassURL];
            return;
        }
        var nextPoll = this.pollIntervalMs + pollData.dataByURL[cssURL].previousPoll;
        var remainingTimeoutMs = Math.max(0, nextPoll - now);
        pollData.dataByURL[cssURL].previousPoll = now + remainingTimeoutMs;
        pollData.dataByURL[cssURL].timer = setTimeout(this._reloadCSS.bind(this, cssURL, sassURL, this._pollCallback.bind(this)), remainingTimeoutMs);
    }, _reloadCSS: function (cssURL, sassURL, callback) {
        var cssUISourceCode = this._workspace.uiSourceCodeForURL(cssURL);
        if (!cssUISourceCode) {
            WebInspector.console.warn(WebInspector.UIString("%s resource missing. Please reload the page.", cssURL));
            callback(cssURL, sassURL, true);
            return;
        }
        if (this._workspace.hasMappingForURL(sassURL))
            this._reloadCSSFromFileSystem(cssUISourceCode, sassURL, callback); else
            this._reloadCSSFromNetwork(cssUISourceCode, sassURL, callback);
    }, _reloadCSSFromNetwork: function (cssUISourceCode, sassURL, callback) {
        var cssURL = cssUISourceCode.url;
        var data = this._pollDataForSASSURL[sassURL];
        if (!data) {
            callback(cssURL, sassURL, true);
            return;
        }
        var headers = {"if-modified-since": new Date(data.sassTimestamp.getTime() - 1000).toUTCString()};
        NetworkAgent.loadResourceForFrontend(WebInspector.resourceTreeModel.mainFrame.id, cssURL, headers, contentLoaded.bind(this));
        function contentLoaded(error, statusCode, headers, content) {
            if (error || statusCode >= 400) {
                console.error("Could not load content for " + cssURL + " : " + (error || ("HTTP status code: " + statusCode)));
                callback(cssURL, sassURL, true);
                return;
            }
            if (!this._pollDataForSASSURL[sassURL]) {
                callback(cssURL, sassURL, true);
                return;
            }
            if (statusCode === 304) {
                callback(cssURL, sassURL, false);
                return;
            }
            var lastModified = this._checkLastModified(headers, cssURL);
            if (!lastModified) {
                callback(cssURL, sassURL, true);
                return;
            }
            if (lastModified.getTime() < data.sassTimestamp.getTime()) {
                callback(cssURL, sassURL, false);
                return;
            }
            this._updateCSSRevision(cssUISourceCode, content, sassURL, callback);
        }
    }, _updateCSSRevision: function (cssUISourceCode, content, sassURL, callback) {
        ++this._addingRevisionCounter;
        cssUISourceCode.addRevision(content);
        this._cssUISourceCodeUpdated(cssUISourceCode.url, sassURL, callback);
    }, _reloadCSSFromFileSystem: function (cssUISourceCode, sassURL, callback) {
        cssUISourceCode.requestMetadata(metadataCallback.bind(this));
        function metadataCallback(timestamp) {
            var cssURL = cssUISourceCode.url;
            if (!timestamp) {
                callback(cssURL, sassURL, false);
                return;
            }
            var cssTimestamp = timestamp.getTime();
            var pollData = this._pollDataForSASSURL[sassURL];
            if (!pollData) {
                callback(cssURL, sassURL, true);
                return;
            }
            if (cssTimestamp < pollData.sassTimestamp.getTime()) {
                callback(cssURL, sassURL, false);
                return;
            }
            cssUISourceCode.requestOriginalContent(contentCallback.bind(this));
            function contentCallback(content) {
                if (content === null)
                    return;
                this._updateCSSRevision(cssUISourceCode, content, sassURL, callback);
            }
        }
    }, _cssUISourceCodeUpdated: function (cssURL, sassURL, callback) {
        var completeSourceMapURL = this._completeSourceMapURLForCSSURL[cssURL];
        if (!completeSourceMapURL)
            return;
        var ids = this._cssModel.styleSheetIdsForURL(cssURL);
        if (!ids)
            return;
        var headers = [];
        for (var i = 0; i < ids.length; ++i)
            headers.push(this._cssModel.styleSheetHeaderForId(ids[i]));
        for (var i = 0; i < ids.length; ++i)
            this._loadSourceMapAndBindUISourceCode(headers, true, completeSourceMapURL);
        callback(cssURL, sassURL, true);
    }, addHeader: function (header) {
        if (!header.sourceMapURL || !header.sourceURL || header.isInline || !WebInspector.settings.cssSourceMapsEnabled.get())
            return;
        var completeSourceMapURL = WebInspector.ParsedURL.completeURL(header.sourceURL, header.sourceMapURL);
        if (!completeSourceMapURL)
            return;
        this._completeSourceMapURLForCSSURL[header.sourceURL] = completeSourceMapURL;
        this._loadSourceMapAndBindUISourceCode([header], false, completeSourceMapURL);
    }, removeHeader: function (header) {
        var sourceURL = header.sourceURL;
        if (!sourceURL || !header.sourceMapURL || header.isInline || !this._completeSourceMapURLForCSSURL[sourceURL])
            return;
        delete this._sourceMapByStyleSheetURL[sourceURL];
        delete this._completeSourceMapURLForCSSURL[sourceURL];
        for (var sassURL in this._cssURLsForSASSURL) {
            var urls = this._cssURLsForSASSURL[sassURL];
            urls.remove(sourceURL);
            if (!urls.length)
                delete this._cssURLsForSASSURL[sassURL];
        }
        var completeSourceMapURL = WebInspector.ParsedURL.completeURL(sourceURL, header.sourceMapURL);
        if (completeSourceMapURL)
            delete this._sourceMapByURL[completeSourceMapURL];
        WebInspector.cssWorkspaceBinding.updateLocations(header);
    }, _loadSourceMapAndBindUISourceCode: function (headersWithSameSourceURL, forceRebind, completeSourceMapURL) {
        console.assert(headersWithSameSourceURL.length);
        var sourceURL = headersWithSameSourceURL[0].sourceURL;
        this._loadSourceMapForStyleSheet(completeSourceMapURL, sourceURL, forceRebind, sourceMapLoaded.bind(this));
        function sourceMapLoaded(sourceMap) {
            if (!sourceMap)
                return;
            this._sourceMapByStyleSheetURL[sourceURL] = sourceMap;
            for (var i = 0; i < headersWithSameSourceURL.length; ++i) {
                if (forceRebind)
                    WebInspector.cssWorkspaceBinding.updateLocations(headersWithSameSourceURL[i]); else
                    this._bindUISourceCode(headersWithSameSourceURL[i], sourceMap);
            }
        }
    }, _addCSSURLforSASSURL: function (cssURL, sassURL) {
        var cssURLs;
        if (this._cssURLsForSASSURL.hasOwnProperty(sassURL))
            cssURLs = this._cssURLsForSASSURL[sassURL]; else {
            cssURLs = [];
            this._cssURLsForSASSURL[sassURL] = cssURLs;
        }
        if (cssURLs.indexOf(cssURL) === -1)
            cssURLs.push(cssURL);
    }, _loadSourceMapForStyleSheet: function (completeSourceMapURL, completeStyleSheetURL, forceReload, callback) {
        var sourceMap = this._sourceMapByURL[completeSourceMapURL];
        if (sourceMap && !forceReload) {
            callback(sourceMap);
            return;
        }
        var pendingCallbacks = this._pendingSourceMapLoadingCallbacks[completeSourceMapURL];
        if (pendingCallbacks) {
            pendingCallbacks.push(callback);
            return;
        }
        pendingCallbacks = [callback];
        this._pendingSourceMapLoadingCallbacks[completeSourceMapURL] = pendingCallbacks;
        WebInspector.SourceMap.load(completeSourceMapURL, completeStyleSheetURL, sourceMapLoaded.bind(this));
        function sourceMapLoaded(sourceMap) {
            var callbacks = this._pendingSourceMapLoadingCallbacks[completeSourceMapURL];
            delete this._pendingSourceMapLoadingCallbacks[completeSourceMapURL];
            if (!callbacks)
                return;
            if (sourceMap)
                this._sourceMapByURL[completeSourceMapURL] = sourceMap; else
                delete this._sourceMapByURL[completeSourceMapURL];
            for (var i = 0; i < callbacks.length; ++i)
                callbacks[i](sourceMap);
        }
    }, _bindUISourceCode: function (header, sourceMap) {
        WebInspector.cssWorkspaceBinding.pushSourceMapping(header, this);
        var rawURL = header.sourceURL;
        var sources = sourceMap.sources();
        for (var i = 0; i < sources.length; ++i) {
            var url = sources[i];
            this._addCSSURLforSASSURL(rawURL, url);
            if (!this._workspace.hasMappingForURL(url) && !this._workspace.uiSourceCodeForURL(url)) {
                var contentProvider = sourceMap.sourceContentProvider(url, WebInspector.resourceTypes.Stylesheet);
                this._networkWorkspaceBinding.addFileForURL(url, contentProvider);
            }
        }
    }, rawLocationToUILocation: function (rawLocation) {
        var entry;
        var sourceMap = this._sourceMapByStyleSheetURL[rawLocation.url];
        if (!sourceMap)
            return null;
        entry = sourceMap.findEntry(rawLocation.lineNumber, rawLocation.columnNumber);
        if (!entry || entry.length === 2)
            return null;
        var uiSourceCode = this._workspace.uiSourceCodeForURL(entry[2]);
        if (!uiSourceCode)
            return null;
        return uiSourceCode.uiLocation(entry[3], entry[4]);
    }, uiLocationToRawLocation: function (uiSourceCode, lineNumber, columnNumber) {
        return new WebInspector.CSSLocation(this._cssModel.target(), null, uiSourceCode.url || "", lineNumber, columnNumber);
    }, isIdentity: function () {
        return false;
    }, uiLineHasMapping: function (uiSourceCode, lineNumber) {
        return true;
    }, target: function () {
        return this._cssModel.target();
    }, _uiSourceCodeAdded: function (event) {
        var uiSourceCode = (event.data);
        var cssURLs = this._cssURLsForSASSURL[uiSourceCode.url];
        if (!cssURLs)
            return;
        for (var i = 0; i < cssURLs.length; ++i) {
            var ids = this._cssModel.styleSheetIdsForURL(cssURLs[i]);
            for (var j = 0; j < ids.length; ++j) {
                var header = this._cssModel.styleSheetHeaderForId(ids[j]);
                console.assert(header);
                WebInspector.cssWorkspaceBinding.updateLocations((header));
            }
        }
    }, _uiSourceCodeContentCommitted: function (event) {
        var uiSourceCode = (event.data.uiSourceCode);
        if (uiSourceCode.project().type() === WebInspector.projectTypes.FileSystem)
            this._sassFileSaved(uiSourceCode.url, true);
    }, _reset: function () {
        this._addingRevisionCounter = 0;
        this._completeSourceMapURLForCSSURL = {};
        this._cssURLsForSASSURL = {};
        this._pendingSourceMapLoadingCallbacks = {};
        this._pollDataForSASSURL = {};
        this._sourceMapByURL = {};
        this._sourceMapByStyleSheetURL = {};
    }
}
WebInspector.DOMNode = function (domModel, doc, isInShadowTree, payload) {
    WebInspector.SDKObject.call(this, domModel.target());
    this._domModel = domModel;
    this._agent = domModel._agent;
    this.ownerDocument = doc;
    this._isInShadowTree = isInShadowTree;
    this.id = payload.nodeId;
    domModel._idToDOMNode[this.id] = this;
    this._nodeType = payload.nodeType;
    this._nodeName = payload.nodeName;
    this._localName = payload.localName;
    this._nodeValue = payload.nodeValue;
    this._pseudoType = payload.pseudoType;
    this._shadowRootType = payload.shadowRootType;
    this._frameId = payload.frameId || null;
    this._shadowRoots = [];
    this._attributes = [];
    this._attributesMap = {};
    if (payload.attributes)
        this._setAttributesPayload(payload.attributes);
    this._userProperties = {};
    this._descendantUserPropertyCounters = {};
    this._childNodeCount = payload.childNodeCount || 0;
    this._children = null;
    this.nextSibling = null;
    this.previousSibling = null;
    this.firstChild = null;
    this.lastChild = null;
    this.parentNode = null;
    if (payload.shadowRoots) {
        for (var i = 0; i < payload.shadowRoots.length; ++i) {
            var root = payload.shadowRoots[i];
            var node = new WebInspector.DOMNode(this._domModel, this.ownerDocument, true, root);
            this._shadowRoots.push(node);
            node.parentNode = this;
        }
    }
    if (payload.templateContent) {
        this._templateContent = new WebInspector.DOMNode(this._domModel, this.ownerDocument, true, payload.templateContent);
        this._templateContent.parentNode = this;
    }
    if (payload.importedDocument) {
        this._importedDocument = new WebInspector.DOMNode(this._domModel, this.ownerDocument, true, payload.importedDocument);
        this._importedDocument.parentNode = this;
    }
    if (payload.children)
        this._setChildrenPayload(payload.children);
    this._setPseudoElements(payload.pseudoElements);
    if (payload.contentDocument) {
        this._contentDocument = new WebInspector.DOMDocument(domModel, payload.contentDocument);
        this._children = [this._contentDocument];
        this._renumber();
    }
    if (this._nodeType === Node.ELEMENT_NODE) {
        if (this.ownerDocument && !this.ownerDocument.documentElement && this._nodeName === "HTML")
            this.ownerDocument.documentElement = this;
        if (this.ownerDocument && !this.ownerDocument.body && this._nodeName === "BODY")
            this.ownerDocument.body = this;
    } else if (this._nodeType === Node.DOCUMENT_TYPE_NODE) {
        this.publicId = payload.publicId;
        this.systemId = payload.systemId;
        this.internalSubset = payload.internalSubset;
    } else if (this._nodeType === Node.ATTRIBUTE_NODE) {
        this.name = payload.name;
        this.value = payload.value;
    }
}
WebInspector.DOMNode.PseudoElementNames = {Before: "before", After: "after"}
WebInspector.DOMNode.ShadowRootTypes = {UserAgent: "user-agent", Author: "author"}
WebInspector.DOMNode.prototype = {
    domModel: function () {
        return this._domModel;
    }, children: function () {
        return this._children ? this._children.slice() : null;
    }, hasAttributes: function () {
        return this._attributes.length > 0;
    }, childNodeCount: function () {
        return this._childNodeCount;
    }, hasShadowRoots: function () {
        return !!this._shadowRoots.length;
    }, shadowRoots: function () {
        return this._shadowRoots.slice();
    }, templateContent: function () {
        return this._templateContent;
    }, importedDocument: function () {
        return this._importedDocument;
    }, nodeType: function () {
        return this._nodeType;
    }, nodeName: function () {
        return this._nodeName;
    }, pseudoType: function () {
        return this._pseudoType;
    }, hasPseudoElements: function () {
        return Object.keys(this._pseudoElements).length !== 0;
    }, pseudoElements: function () {
        return this._pseudoElements;
    }, isInShadowTree: function () {
        return this._isInShadowTree;
    }, ancestorUserAgentShadowRoot: function () {
        if (!this._isInShadowTree)
            return null;
        var current = this;
        while (!current.isShadowRoot())
            current = current.parentNode;
        return current.shadowRootType() === WebInspector.DOMNode.ShadowRootTypes.UserAgent ? current : null;
    }, isShadowRoot: function () {
        return !!this._shadowRootType;
    }, shadowRootType: function () {
        return this._shadowRootType || null;
    }, nodeNameInCorrectCase: function () {
        var shadowRootType = this.shadowRootType();
        if (shadowRootType)
            return "#shadow-root" + (shadowRootType === WebInspector.DOMNode.ShadowRootTypes.UserAgent ? " (user-agent)" : "");
        return this.isXMLNode() ? this.nodeName() : this.nodeName().toLowerCase();
    }, setNodeName: function (name, callback) {
        this._agent.setNodeName(this.id, name, this._domModel._markRevision(this, callback));
    }, localName: function () {
        return this._localName;
    }, nodeValue: function () {
        return this._nodeValue;
    }, setNodeValue: function (value, callback) {
        this._agent.setNodeValue(this.id, value, this._domModel._markRevision(this, callback));
    }, getAttribute: function (name) {
        var attr = this._attributesMap[name];
        return attr ? attr.value : undefined;
    }, setAttribute: function (name, text, callback) {
        this._agent.setAttributesAsText(this.id, text, name, this._domModel._markRevision(this, callback));
    }, setAttributeValue: function (name, value, callback) {
        this._agent.setAttributeValue(this.id, name, value, this._domModel._markRevision(this, callback));
    }, attributes: function () {
        return this._attributes;
    }, removeAttribute: function (name, callback) {
        function mycallback(error) {
            if (!error) {
                delete this._attributesMap[name];
                for (var i = 0; i < this._attributes.length; ++i) {
                    if (this._attributes[i].name === name) {
                        this._attributes.splice(i, 1);
                        break;
                    }
                }
            }
            this._domModel._markRevision(this, callback)(error);
        }

        this._agent.removeAttribute(this.id, name, mycallback.bind(this));
    }, getChildNodes: function (callback) {
        if (this._children) {
            if (callback)
                callback(this.children());
            return;
        }
        function mycallback(error) {
            if (callback)
                callback(error ? null : this.children());
        }

        this._agent.requestChildNodes(this.id, undefined, mycallback.bind(this));
    }, getSubtree: function (depth, callback) {
        function mycallback(error) {
            if (callback)
                callback(error ? null : this._children);
        }

        this._agent.requestChildNodes(this.id, depth, mycallback.bind(this));
    }, getOuterHTML: function (callback) {
        this._agent.getOuterHTML(this.id, callback);
    }, setOuterHTML: function (html, callback) {
        this._agent.setOuterHTML(this.id, html, this._domModel._markRevision(this, callback));
    }, removeNode: function (callback) {
        this._agent.removeNode(this.id, this._domModel._markRevision(this, callback));
    }, copyNode: function (callback) {
        function copy(error, text) {
            if (!error)
                InspectorFrontendHost.copyText(text);
            if (callback)
                callback(error ? null : text);
        }

        this._agent.getOuterHTML(this.id, copy);
    }, eventListeners: function (objectGroupId, callback) {
        var target = this.target();

        function mycallback(error, payloads) {
            if (error) {
                callback(null);
                return;
            }
            callback(payloads.map(function (payload) {
                return new WebInspector.DOMModel.EventListener(target, payload);
            }));
        }

        this._agent.getEventListenersForNode(this.id, objectGroupId, mycallback);
    }, path: function () {
        function canPush(node) {
            return node && ("index"in node || (node.isShadowRoot() && node.parentNode)) && node._nodeName.length;
        }

        var path = [];
        var node = this;
        while (canPush(node)) {
            var index = typeof node.index === "number" ? node.index : (node.shadowRootType() === WebInspector.DOMNode.ShadowRootTypes.UserAgent ? "u" : "a");
            path.push([index, node._nodeName]);
            node = node.parentNode;
        }
        path.reverse();
        return path.join(",");
    }, isAncestor: function (node) {
        if (!node)
            return false;
        var currentNode = node.parentNode;
        while (currentNode) {
            if (this === currentNode)
                return true;
            currentNode = currentNode.parentNode;
        }
        return false;
    }, isDescendant: function (descendant) {
        return descendant !== null && descendant.isAncestor(this);
    }, frameId: function () {
        var node = this;
        while (!node._frameId && node.parentNode)
            node = node.parentNode;
        return node._frameId;
    }, _setAttributesPayload: function (attrs) {
        var attributesChanged = !this._attributes || attrs.length !== this._attributes.length * 2;
        var oldAttributesMap = this._attributesMap || {};
        this._attributes = [];
        this._attributesMap = {};
        for (var i = 0; i < attrs.length; i += 2) {
            var name = attrs[i];
            var value = attrs[i + 1];
            this._addAttribute(name, value);
            if (attributesChanged)
                continue;
            if (!oldAttributesMap[name] || oldAttributesMap[name].value !== value)
                attributesChanged = true;
        }
        return attributesChanged;
    }, _insertChild: function (prev, payload) {
        var node = new WebInspector.DOMNode(this._domModel, this.ownerDocument, this._isInShadowTree, payload);
        this._children.splice(this._children.indexOf(prev) + 1, 0, node);
        this._renumber();
        return node;
    }, _removeChild: function (node) {
        if (node.pseudoType()) {
            delete this._pseudoElements[node.pseudoType()];
        } else {
            var shadowRootIndex = this._shadowRoots.indexOf(node);
            if (shadowRootIndex !== -1)
                this._shadowRoots.splice(shadowRootIndex, 1); else
                this._children.splice(this._children.indexOf(node), 1);
        }
        node.parentNode = null;
        node._updateChildUserPropertyCountsOnRemoval(this);
        this._renumber();
    }, _setChildrenPayload: function (payloads) {
        if (this._contentDocument)
            return;
        this._children = [];
        for (var i = 0; i < payloads.length; ++i) {
            var payload = payloads[i];
            var node = new WebInspector.DOMNode(this._domModel, this.ownerDocument, this._isInShadowTree, payload);
            this._children.push(node);
        }
        this._renumber();
    }, _setPseudoElements: function (payloads) {
        this._pseudoElements = {};
        if (!payloads)
            return;
        for (var i = 0; i < payloads.length; ++i) {
            var node = new WebInspector.DOMNode(this._domModel, this.ownerDocument, this._isInShadowTree, payloads[i]);
            node.parentNode = this;
            this._pseudoElements[node.pseudoType()] = node;
        }
    }, _renumber: function () {
        this._childNodeCount = this._children.length;
        if (this._childNodeCount == 0) {
            this.firstChild = null;
            this.lastChild = null;
            return;
        }
        this.firstChild = this._children[0];
        this.lastChild = this._children[this._childNodeCount - 1];
        for (var i = 0; i < this._childNodeCount; ++i) {
            var child = this._children[i];
            child.index = i;
            child.nextSibling = i + 1 < this._childNodeCount ? this._children[i + 1] : null;
            child.previousSibling = i - 1 >= 0 ? this._children[i - 1] : null;
            child.parentNode = this;
        }
    }, _addAttribute: function (name, value) {
        var attr = {name: name, value: value, _node: this};
        this._attributesMap[name] = attr;
        this._attributes.push(attr);
    }, _setAttribute: function (name, value) {
        var attr = this._attributesMap[name];
        if (attr)
            attr.value = value; else
            this._addAttribute(name, value);
    }, _removeAttribute: function (name) {
        var attr = this._attributesMap[name];
        if (attr) {
            this._attributes.remove(attr);
            delete this._attributesMap[name];
        }
    }, copyTo: function (targetNode, anchorNode, callback) {
        this._agent.copyTo(this.id, targetNode.id, anchorNode ? anchorNode.id : undefined, this._domModel._markRevision(this, callback));
    }, moveTo: function (targetNode, anchorNode, callback) {
        this._agent.moveTo(this.id, targetNode.id, anchorNode ? anchorNode.id : undefined, this._domModel._markRevision(this, callback));
    }, isXMLNode: function () {
        return !!this.ownerDocument && !!this.ownerDocument.xmlVersion;
    }, _updateChildUserPropertyCountsOnRemoval: function (parentNode) {
        var result = {};
        if (this._userProperties) {
            for (var name in this._userProperties)
                result[name] = (result[name] || 0) + 1;
        }
        if (this._descendantUserPropertyCounters) {
            for (var name in this._descendantUserPropertyCounters) {
                var counter = this._descendantUserPropertyCounters[name];
                result[name] = (result[name] || 0) + counter;
            }
        }
        for (var name in result)
            parentNode._updateDescendantUserPropertyCount(name, -result[name]);
    }, _updateDescendantUserPropertyCount: function (name, delta) {
        if (!this._descendantUserPropertyCounters.hasOwnProperty(name))
            this._descendantUserPropertyCounters[name] = 0;
        this._descendantUserPropertyCounters[name] += delta;
        if (!this._descendantUserPropertyCounters[name])
            delete this._descendantUserPropertyCounters[name];
        if (this.parentNode)
            this.parentNode._updateDescendantUserPropertyCount(name, delta);
    }, setUserProperty: function (name, value) {
        if (value === null) {
            this.removeUserProperty(name);
            return;
        }
        if (this.parentNode && !this._userProperties.hasOwnProperty(name))
            this.parentNode._updateDescendantUserPropertyCount(name, 1);
        this._userProperties[name] = value;
    }, removeUserProperty: function (name) {
        if (!this._userProperties.hasOwnProperty(name))
            return;
        delete this._userProperties[name];
        if (this.parentNode)
            this.parentNode._updateDescendantUserPropertyCount(name, -1);
    }, getUserProperty: function (name) {
        return (this._userProperties && this._userProperties[name]) || null;
    }, descendantUserPropertyCount: function (name) {
        return this._descendantUserPropertyCounters && this._descendantUserPropertyCounters[name] ? this._descendantUserPropertyCounters[name] : 0;
    }, resolveURL: function (url) {
        if (!url)
            return url;
        for (var frameOwnerCandidate = this; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
            if (frameOwnerCandidate.baseURL)
                return WebInspector.ParsedURL.completeURL(frameOwnerCandidate.baseURL, url);
        }
        return null;
    }, highlight: function (mode, objectId) {
        this._domModel.highlightDOMNode(this.id, mode, objectId);
    }, highlightForTwoSeconds: function () {
        this._domModel.highlightDOMNodeForTwoSeconds(this.id);
    }, resolveToObject: function (objectGroup, callback) {
        this._agent.resolveNode(this.id, objectGroup, mycallback.bind(this));
        function mycallback(error, object) {
            if (!callback)
                return;
            if (error || !object)
                callback(null); else
                callback(this.target().runtimeModel.createRemoteObject(object));
        }
    }, boxModel: function (callback) {
        this._agent.getBoxModel(this.id, this._domModel._wrapClientCallback(callback));
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.DeferredDOMNode = function (target, backendNodeId) {
    this._target = target;
    this._backendNodeId = backendNodeId;
}
WebInspector.DeferredDOMNode.prototype = {
    resolve: function (callback) {
        this._target.domModel.pushNodesByBackendIdsToFrontend([this._backendNodeId], onGotNode.bind(this));
        function onGotNode(nodeIds) {
            if (!nodeIds || !nodeIds[0]) {
                callback(null);
                return;
            }
            callback(this._target.domModel.nodeForId(nodeIds[0]));
        }
    }
}
WebInspector.DOMDocument = function (domModel, payload) {
    WebInspector.DOMNode.call(this, domModel, this, false, payload);
    this.documentURL = payload.documentURL || "";
    this.baseURL = payload.baseURL || "";
    this.xmlVersion = payload.xmlVersion;
    this._listeners = {};
}
WebInspector.DOMDocument.prototype = {__proto__: WebInspector.DOMNode.prototype}
WebInspector.DOMModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.DOMModel, target);
    this._agent = target.domAgent();
    this._idToDOMNode = {};
    this._document = null;
    this._attributeLoadNodeIds = {};
    target.registerDOMDispatcher(new WebInspector.DOMDispatcher(this));
    this._defaultHighlighter = new WebInspector.DefaultDOMNodeHighlighter(this._agent);
    this._highlighter = this._defaultHighlighter;
    if (WebInspector.experimentsSettings.disableAgentsWhenProfile.isEnabled())
        WebInspector.profilingLock().addEventListener(WebInspector.Lock.Events.StateChanged, this._profilingStateChanged, this);
    this._agent.enable();
}
WebInspector.DOMModel.Events = {
    AttrModified: "AttrModified",
    AttrRemoved: "AttrRemoved",
    CharacterDataModified: "CharacterDataModified",
    NodeInserted: "NodeInserted",
    NodeInspected: "NodeInspected",
    NodeRemoved: "NodeRemoved",
    DocumentUpdated: "DocumentUpdated",
    ChildNodeCountUpdated: "ChildNodeCountUpdated",
    UndoRedoRequested: "UndoRedoRequested",
    UndoRedoCompleted: "UndoRedoCompleted",
}
WebInspector.DOMModel.prototype = {
    _profilingStateChanged: function () {
        if (WebInspector.profilingLock().isAcquired())
            this._agent.disable(); else
            this._agent.enable();
    }, requestDocument: function (callback) {
        if (this._document) {
            if (callback)
                callback(this._document);
            return;
        }
        if (this._pendingDocumentRequestCallbacks) {
            this._pendingDocumentRequestCallbacks.push(callback);
            return;
        }
        this._pendingDocumentRequestCallbacks = [callback];
        function onDocumentAvailable(error, root) {
            if (!error)
                this._setDocument(root);
            for (var i = 0; i < this._pendingDocumentRequestCallbacks.length; ++i) {
                var callback = this._pendingDocumentRequestCallbacks[i];
                if (callback)
                    callback(this._document);
            }
            delete this._pendingDocumentRequestCallbacks;
        }

        this._agent.getDocument(onDocumentAvailable.bind(this));
    }, existingDocument: function () {
        return this._document;
    }, pushNodeToFrontend: function (objectId, callback) {
        function mycallback(nodeId) {
            callback(nodeId ? this.nodeForId(nodeId) : null);
        }

        this._dispatchWhenDocumentAvailable(this._agent.requestNode.bind(this._agent, objectId), mycallback.bind(this));
    }, pushNodeByPathToFrontend: function (path, callback) {
        this._dispatchWhenDocumentAvailable(this._agent.pushNodeByPathToFrontend.bind(this._agent, path), callback);
    }, pushNodesByBackendIdsToFrontend: function (backendNodeIds, callback) {
        this._dispatchWhenDocumentAvailable(this._agent.pushNodesByBackendIdsToFrontend.bind(this._agent, backendNodeIds), callback);
    }, _wrapClientCallback: function (callback) {
        if (!callback)
            return;
        var wrapper = function (error, result) {
            callback(error ? null : result);
        };
        return wrapper;
    }, _dispatchWhenDocumentAvailable: function (func, callback) {
        var callbackWrapper = this._wrapClientCallback(callback);

        function onDocumentAvailable() {
            if (this._document)
                func(callbackWrapper); else {
                if (callbackWrapper)
                    callbackWrapper("No document");
            }
        }

        this.requestDocument(onDocumentAvailable.bind(this));
    }, _attributeModified: function (nodeId, name, value) {
        var node = this._idToDOMNode[nodeId];
        if (!node)
            return;
        node._setAttribute(name, value);
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.AttrModified, {node: node, name: name});
    }, _attributeRemoved: function (nodeId, name) {
        var node = this._idToDOMNode[nodeId];
        if (!node)
            return;
        node._removeAttribute(name);
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.AttrRemoved, {node: node, name: name});
    }, _inlineStyleInvalidated: function (nodeIds) {
        for (var i = 0; i < nodeIds.length; ++i)
            this._attributeLoadNodeIds[nodeIds[i]] = true;
        if ("_loadNodeAttributesTimeout"in this)
            return;
        this._loadNodeAttributesTimeout = setTimeout(this._loadNodeAttributes.bind(this), 20);
    }, _loadNodeAttributes: function () {
        function callback(nodeId, error, attributes) {
            if (error) {
                return;
            }
            var node = this._idToDOMNode[nodeId];
            if (node) {
                if (node._setAttributesPayload(attributes))
                    this.dispatchEventToListeners(WebInspector.DOMModel.Events.AttrModified, {node: node, name: "style"});
            }
        }

        delete this._loadNodeAttributesTimeout;
        for (var nodeId in this._attributeLoadNodeIds) {
            var nodeIdAsNumber = parseInt(nodeId, 10);
            this._agent.getAttributes(nodeIdAsNumber, callback.bind(this, nodeIdAsNumber));
        }
        this._attributeLoadNodeIds = {};
    }, _characterDataModified: function (nodeId, newValue) {
        var node = this._idToDOMNode[nodeId];
        node._nodeValue = newValue;
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.CharacterDataModified, node);
    }, nodeForId: function (nodeId) {
        return this._idToDOMNode[nodeId] || null;
    }, _documentUpdated: function () {
        this._setDocument(null);
    }, _setDocument: function (payload) {
        this._idToDOMNode = {};
        if (payload && "nodeId"in payload)
            this._document = new WebInspector.DOMDocument(this, payload); else
            this._document = null;
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.DocumentUpdated, this._document);
    }, _setDetachedRoot: function (payload) {
        if (payload.nodeName === "#document")
            new WebInspector.DOMDocument(this, payload); else
            new WebInspector.DOMNode(this, null, false, payload);
    }, _setChildNodes: function (parentId, payloads) {
        if (!parentId && payloads.length) {
            this._setDetachedRoot(payloads[0]);
            return;
        }
        var parent = this._idToDOMNode[parentId];
        parent._setChildrenPayload(payloads);
    }, _childNodeCountUpdated: function (nodeId, newValue) {
        var node = this._idToDOMNode[nodeId];
        node._childNodeCount = newValue;
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.ChildNodeCountUpdated, node);
    }, _childNodeInserted: function (parentId, prevId, payload) {
        var parent = this._idToDOMNode[parentId];
        var prev = this._idToDOMNode[prevId];
        var node = parent._insertChild(prev, payload);
        this._idToDOMNode[node.id] = node;
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInserted, node);
    }, _childNodeRemoved: function (parentId, nodeId) {
        var parent = this._idToDOMNode[parentId];
        var node = this._idToDOMNode[nodeId];
        parent._removeChild(node);
        this._unbind(node);
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeRemoved, {node: node, parent: parent});
    }, _shadowRootPushed: function (hostId, root) {
        var host = this._idToDOMNode[hostId];
        if (!host)
            return;
        var node = new WebInspector.DOMNode(this, host.ownerDocument, true, root);
        node.parentNode = host;
        this._idToDOMNode[node.id] = node;
        host._shadowRoots.push(node);
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInserted, node);
    }, _shadowRootPopped: function (hostId, rootId) {
        var host = this._idToDOMNode[hostId];
        if (!host)
            return;
        var root = this._idToDOMNode[rootId];
        if (!root)
            return;
        host._removeChild(root);
        this._unbind(root);
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeRemoved, {node: root, parent: host});
    }, _pseudoElementAdded: function (parentId, pseudoElement) {
        var parent = this._idToDOMNode[parentId];
        if (!parent)
            return;
        var node = new WebInspector.DOMNode(this, parent.ownerDocument, false, pseudoElement);
        node.parentNode = parent;
        this._idToDOMNode[node.id] = node;
        console.assert(!parent._pseudoElements[node.pseudoType()]);
        parent._pseudoElements[node.pseudoType()] = node;
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInserted, node);
    }, _pseudoElementRemoved: function (parentId, pseudoElementId) {
        var parent = this._idToDOMNode[parentId];
        if (!parent)
            return;
        var pseudoElement = this._idToDOMNode[pseudoElementId];
        if (!pseudoElement)
            return;
        parent._removeChild(pseudoElement);
        this._unbind(pseudoElement);
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeRemoved, {node: pseudoElement, parent: parent});
    }, _unbind: function (node) {
        delete this._idToDOMNode[node.id];
        for (var i = 0; node._children && i < node._children.length; ++i)
            this._unbind(node._children[i]);
        for (var i = 0; i < node._shadowRoots.length; ++i)
            this._unbind(node._shadowRoots[i]);
        var pseudoElements = node.pseudoElements();
        for (var id in pseudoElements)
            this._unbind(pseudoElements[id]);
        if (node._templateContent)
            this._unbind(node._templateContent);
    }, _inspectNodeRequested: function (nodeId) {
        this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInspected, this.nodeForId(nodeId));
    }, performSearch: function (query, includeUserAgentShadowDOM, searchCallback) {
        this.cancelSearch();
        function callback(error, searchId, resultsCount) {
            this._searchId = searchId;
            searchCallback(resultsCount);
        }

        this._agent.performSearch(query, includeUserAgentShadowDOM, callback.bind(this));
    }, performSearchPromise: function (query, includeUserAgentShadowDOM) {
        return new Promise(performSearch.bind(this));
        function performSearch(resolve) {
            this._agent.performSearch(query, includeUserAgentShadowDOM, callback.bind(this));
            function callback(error, searchId, resultsCount) {
                if (!error)
                    this._searchId = searchId;
                resolve(error ? 0 : resultsCount);
            }
        }
    }, searchResult: function (index, callback) {
        if (this._searchId)
            this._agent.getSearchResults(this._searchId, index, index + 1, searchResultsCallback.bind(this)); else
            callback(null);
        function searchResultsCallback(error, nodeIds) {
            if (error) {
                console.error(error);
                callback(null);
                return;
            }
            if (nodeIds.length != 1)
                return;
            callback(this.nodeForId(nodeIds[0]));
        }
    }, cancelSearch: function () {
        if (this._searchId) {
            this._agent.discardSearchResults(this._searchId);
            delete this._searchId;
        }
    }, querySelector: function (nodeId, selectors, callback) {
        this._agent.querySelector(nodeId, selectors, this._wrapClientCallback(callback));
    }, querySelectorAll: function (nodeId, selectors, callback) {
        this._agent.querySelectorAll(nodeId, selectors, this._wrapClientCallback(callback));
    }, highlightDOMNode: function (nodeId, mode, objectId) {
        this.highlightDOMNodeWithConfig(nodeId, {mode: mode}, objectId);
    }, highlightDOMNodeWithConfig: function (nodeId, config, objectId) {
        config = config || {mode: "all", showInfo: undefined};
        if (this._hideDOMNodeHighlightTimeout) {
            clearTimeout(this._hideDOMNodeHighlightTimeout);
            delete this._hideDOMNodeHighlightTimeout;
        }
        var highlightConfig = this._buildHighlightConfig(config.mode);
        if (typeof config.showInfo !== "undefined")
            highlightConfig.showInfo = config.showInfo;
        this._highlighter.highlightDOMNode(this.nodeForId(nodeId || 0), highlightConfig, objectId);
    }, hideDOMNodeHighlight: function () {
        this.highlightDOMNode(0);
    }, highlightDOMNodeForTwoSeconds: function (nodeId) {
        this.highlightDOMNode(nodeId);
        this._hideDOMNodeHighlightTimeout = setTimeout(this.hideDOMNodeHighlight.bind(this), 2000);
    }, setInspectModeEnabled: function (enabled, inspectUAShadowDOM, callback) {
        function onDocumentAvailable() {
            this._highlighter.setInspectModeEnabled(enabled, inspectUAShadowDOM, this._buildHighlightConfig(), callback);
        }

        this.requestDocument(onDocumentAvailable.bind(this));
    }, _buildHighlightConfig: function (mode) {
        mode = mode || "all";
        var highlightConfig = {showInfo: mode === "all", showRulers: WebInspector.overridesSupport.showMetricsRulers(), showExtensionLines: WebInspector.overridesSupport.showExtensionLines()};
        if (mode === "all" || mode === "content")
            highlightConfig.contentColor = WebInspector.Color.PageHighlight.Content.toProtocolRGBA();
        if (mode === "all" || mode === "padding")
            highlightConfig.paddingColor = WebInspector.Color.PageHighlight.Padding.toProtocolRGBA();
        if (mode === "all" || mode === "border")
            highlightConfig.borderColor = WebInspector.Color.PageHighlight.Border.toProtocolRGBA();
        if (mode === "all" || mode === "margin")
            highlightConfig.marginColor = WebInspector.Color.PageHighlight.Margin.toProtocolRGBA();
        if (mode === "all") {
            highlightConfig.eventTargetColor = WebInspector.Color.PageHighlight.EventTarget.toProtocolRGBA();
            highlightConfig.shapeColor = WebInspector.Color.PageHighlight.Shape.toProtocolRGBA();
            highlightConfig.shapeMarginColor = WebInspector.Color.PageHighlight.ShapeMargin.toProtocolRGBA();
        }
        return highlightConfig;
    }, _markRevision: function (node, callback) {
        function wrapperFunction(error) {
            if (!error)
                this.markUndoableState();
            if (callback)
                callback.apply(this, arguments);
        }

        return wrapperFunction.bind(this);
    }, emulateTouchEventObjects: function (emulationEnabled) {
        const injectedFunction = function () {
            const touchEvents = ["ontouchstart", "ontouchend", "ontouchmove", "ontouchcancel"];
            var recepients = [window.__proto__, document.__proto__];
            for (var i = 0; i < touchEvents.length; ++i) {
                for (var j = 0; j < recepients.length; ++j) {
                    if (!(touchEvents[i]in recepients[j]))
                        Object.defineProperty(recepients[j], touchEvents[i], {value: null, writable: true, configurable: true, enumerable: true});
                }
            }
        }
        if (emulationEnabled && !this._addTouchEventsScriptInjecting) {
            this._addTouchEventsScriptInjecting = true;
            PageAgent.addScriptToEvaluateOnLoad("(" + injectedFunction.toString() + ")()", scriptAddedCallback.bind(this));
        } else {
            if (typeof this._addTouchEventsScriptId !== "undefined") {
                PageAgent.removeScriptToEvaluateOnLoad(this._addTouchEventsScriptId);
                delete this._addTouchEventsScriptId;
            }
        }
        function scriptAddedCallback(error, scriptId) {
            delete this._addTouchEventsScriptInjecting;
            if (error)
                return;
            this._addTouchEventsScriptId = scriptId;
        }

        PageAgent.setTouchEmulationEnabled(emulationEnabled);
    }, markUndoableState: function () {
        this._agent.markUndoableState();
    }, undo: function (callback) {
        function mycallback(error) {
            this.dispatchEventToListeners(WebInspector.DOMModel.Events.UndoRedoCompleted);
            callback(error);
        }

        this.dispatchEventToListeners(WebInspector.DOMModel.Events.UndoRedoRequested);
        this._agent.undo(callback);
    }, redo: function (callback) {
        function mycallback(error) {
            this.dispatchEventToListeners(WebInspector.DOMModel.Events.UndoRedoCompleted);
            callback(error);
        }

        this.dispatchEventToListeners(WebInspector.DOMModel.Events.UndoRedoRequested);
        this._agent.redo(callback);
    }, setHighlighter: function (highlighter) {
        this._highlighter = highlighter || this._defaultHighlighter;
    }, nodeForLocation: function (x, y, callback) {
        this._agent.getNodeForLocation(x, y, mycallback.bind(this));
        function mycallback(error, nodeId) {
            if (error) {
                callback(null);
                return;
            }
            callback(this.nodeForId(nodeId));
        }
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.DOMDispatcher = function (domModel) {
    this._domModel = domModel;
}
WebInspector.DOMDispatcher.prototype = {
    documentUpdated: function () {
        this._domModel._documentUpdated();
    }, inspectNodeRequested: function (nodeId) {
        this._domModel._inspectNodeRequested(nodeId);
    }, attributeModified: function (nodeId, name, value) {
        this._domModel._attributeModified(nodeId, name, value);
    }, attributeRemoved: function (nodeId, name) {
        this._domModel._attributeRemoved(nodeId, name);
    }, inlineStyleInvalidated: function (nodeIds) {
        this._domModel._inlineStyleInvalidated(nodeIds);
    }, characterDataModified: function (nodeId, characterData) {
        this._domModel._characterDataModified(nodeId, characterData);
    }, setChildNodes: function (parentId, payloads) {
        this._domModel._setChildNodes(parentId, payloads);
    }, childNodeCountUpdated: function (nodeId, childNodeCount) {
        this._domModel._childNodeCountUpdated(nodeId, childNodeCount);
    }, childNodeInserted: function (parentNodeId, previousNodeId, payload) {
        this._domModel._childNodeInserted(parentNodeId, previousNodeId, payload);
    }, childNodeRemoved: function (parentNodeId, nodeId) {
        this._domModel._childNodeRemoved(parentNodeId, nodeId);
    }, shadowRootPushed: function (hostId, root) {
        this._domModel._shadowRootPushed(hostId, root);
    }, shadowRootPopped: function (hostId, rootId) {
        this._domModel._shadowRootPopped(hostId, rootId);
    }, pseudoElementAdded: function (parentId, pseudoElement) {
        this._domModel._pseudoElementAdded(parentId, pseudoElement);
    }, pseudoElementRemoved: function (parentId, pseudoElementId) {
        this._domModel._pseudoElementRemoved(parentId, pseudoElementId);
    }
}
WebInspector.DOMModel.EventListener = function (target, payload) {
    WebInspector.SDKObject.call(this, target);
    this._payload = payload;
    var sourceName = this._payload.sourceName;
    if (!sourceName) {
        var script = target.debuggerModel.scriptForId(payload.location.scriptId);
        sourceName = script ? script.contentURL() : "";
    }
    this._sourceName = sourceName;
}
WebInspector.DOMModel.EventListener.prototype = {
    payload: function () {
        return this._payload;
    }, node: function () {
        return this.target().domModel.nodeForId(this._payload.nodeId);
    }, location: function () {
        return WebInspector.DebuggerModel.Location.fromPayload(this.target(), this._payload.location);
    }, handler: function () {
        return this._payload.handler ? this.target().runtimeModel.createRemoteObject(this._payload.handler) : null;
    }, sourceName: function () {
        return this._sourceName;
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.DOMNodeHighlighter = function () {
}
WebInspector.DOMNodeHighlighter.prototype = {
    highlightDOMNode: function (node, config, objectId) {
    }, setInspectModeEnabled: function (enabled, inspectUAShadowDOM, config, callback) {
    }
}
WebInspector.DefaultDOMNodeHighlighter = function (agent) {
    this._agent = agent;
}
WebInspector.DefaultDOMNodeHighlighter.prototype = {
    highlightDOMNode: function (node, config, objectId) {
        if (objectId || node)
            this._agent.highlightNode(config, objectId ? undefined : node.id, objectId); else
            this._agent.hideHighlight();
    }, setInspectModeEnabled: function (enabled, inspectUAShadowDOM, config, callback) {
        WebInspector.overridesSupport.setTouchEmulationSuspended(enabled);
        this._agent.setInspectModeEnabled(enabled, inspectUAShadowDOM, config, callback);
    }
}
WebInspector.ForwardedInputEventHandler = function () {
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.KeyEventUnhandled, this._onKeyEventUnhandled, this);
}
WebInspector.ForwardedInputEventHandler.prototype = {
    _onKeyEventUnhandled: function (event) {
        var data = event.data;
        var type = (data.type);
        var keyIdentifier = (data.keyIdentifier);
        var keyCode = (data.keyCode);
        var modifiers = (data.modifiers);
        if (type !== "keydown")
            return;
        WebInspector.context.setFlavor(WebInspector.ShortcutRegistry.ForwardedShortcut, WebInspector.ShortcutRegistry.ForwardedShortcut.instance)
        WebInspector.shortcutRegistry.handleKey(WebInspector.KeyboardShortcut.makeKey(keyCode, modifiers), keyIdentifier);
        WebInspector.context.setFlavor(WebInspector.ShortcutRegistry.ForwardedShortcut, null);
    }
}
WebInspector.forwardedEventHandler = new WebInspector.ForwardedInputEventHandler();
WebInspector.evaluateForTestInFrontend = function (callId, script) {
    if (!InspectorFrontendHost.isUnderTest())
        return;
    function invokeMethod() {
        var message;
        try {
            script = script + "//# sourceURL=evaluateInWebInspector" + callId + ".js";
            var result = window.eval(script);
            message = typeof result === "undefined" ? "\"<undefined>\"" : JSON.stringify(result);
        } catch (e) {
            message = e.toString();
        }
        RuntimeAgent.evaluate("didEvaluateForTestInFrontend(" + callId + ", " + message + ")", "test");
    }

    InspectorBackend.connection().runAfterPendingDispatches(invokeMethod);
}
WebInspector.Dialog = function (relativeToElement, delegate) {
    this._delegate = delegate;
    this._relativeToElement = relativeToElement;
    this._glassPane = new WebInspector.GlassPane();
    WebInspector.GlassPane.DefaultFocusedViewStack.push(this);
    this._glassPane.element.tabIndex = 0;
    this._glassPane.element.addEventListener("focus", this._onGlassPaneFocus.bind(this), false);
    this._element = this._glassPane.element.createChild("div");
    this._element.tabIndex = 0;
    this._element.addEventListener("focus", this._onFocus.bind(this), false);
    this._element.addEventListener("keydown", this._onKeyDown.bind(this), false);
    this._closeKeys = [WebInspector.KeyboardShortcut.Keys.Enter.code, WebInspector.KeyboardShortcut.Keys.Esc.code,];
    delegate.show(this._element);
    this._position();
    this._delegate.focus();
}
WebInspector.Dialog.currentInstance = function () {
    return WebInspector.Dialog._instance;
}
WebInspector.Dialog.show = function (relativeToElement, delegate) {
    if (WebInspector.Dialog._instance)
        return;
    WebInspector.Dialog._instance = new WebInspector.Dialog(relativeToElement, delegate);
}
WebInspector.Dialog.hide = function () {
    if (!WebInspector.Dialog._instance)
        return;
    WebInspector.Dialog._instance._hide();
}
WebInspector.Dialog.prototype = {
    focus: function () {
        this._element.focus();
    }, _hide: function () {
        if (this._isHiding)
            return;
        this._isHiding = true;
        this._delegate.willHide();
        delete WebInspector.Dialog._instance;
        WebInspector.GlassPane.DefaultFocusedViewStack.pop();
        this._glassPane.dispose();
    }, _onGlassPaneFocus: function (event) {
        this._hide();
    }, _onFocus: function (event) {
        this._delegate.focus();
    }, _position: function () {
        this._delegate.position(this._element, this._relativeToElement);
    }, _onKeyDown: function (event) {
        if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Tab.code) {
            event.preventDefault();
            return;
        }
        if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Enter.code)
            this._delegate.onEnter(event);
        if (!event.handled && this._closeKeys.indexOf(event.keyCode) >= 0) {
            this._hide();
            event.consume(true);
        }
    }
};
WebInspector.DialogDelegate = function () {
    this.element;
}
WebInspector.DialogDelegate.prototype = {
    show: function (element) {
        element.appendChild(this.element);
        this.element.classList.add("dialog-contents");
        element.classList.add("dialog", "toolbar-colors");
    }, position: function (element, relativeToElement) {
        var container = WebInspector.Dialog._modalHostView.element;
        var box = relativeToElement.boxInWindow(window).relativeToElement(container);
        var positionX = box.x + (relativeToElement.offsetWidth - element.offsetWidth) / 2;
        positionX = Number.constrain(positionX, 0, container.offsetWidth - element.offsetWidth);
        var positionY = box.y + (relativeToElement.offsetHeight - element.offsetHeight) / 2;
        positionY = Number.constrain(positionY, 0, container.offsetHeight - element.offsetHeight);
        element.style.position = "absolute";
        element.positionAt(positionX, positionY, container);
    }, focus: function () {
    }, onEnter: function (event) {
    }, willHide: function () {
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.Dialog._modalHostView = null;
WebInspector.Dialog.setModalHostView = function (view) {
    WebInspector.Dialog._modalHostView = view;
};
WebInspector.Dialog.modalHostView = function () {
    return WebInspector.Dialog._modalHostView;
};
WebInspector.Dialog.modalHostRepositioned = function () {
    if (WebInspector.Dialog._instance)
        WebInspector.Dialog._instance._position();
};
WebInspector.ShortcutsScreen = function () {
    this._sections = {};
}
WebInspector.ShortcutsScreen.prototype = {
    section: function (name) {
        var section = this._sections[name];
        if (!section)
            this._sections[name] = section = new WebInspector.ShortcutsSection(name);
        return section;
    }, createShortcutsTabView: function () {
        var orderedSections = [];
        for (var section in this._sections)
            orderedSections.push(this._sections[section]);
        function compareSections(a, b) {
            return a.order - b.order;
        }

        orderedSections.sort(compareSections);
        var view = new WebInspector.View();
        view.element.className = "settings-tab-container";
        view.element.createChild("header").createChild("h3").appendChild(document.createTextNode(WebInspector.UIString("Shortcuts")));
        var scrollPane = view.element.createChild("div", "help-container-wrapper");
        var container = scrollPane.createChild("div");
        container.className = "help-content help-container";
        for (var i = 0; i < orderedSections.length; ++i)
            orderedSections[i].renderSection(container);
        var note = scrollPane.createChild("p", "help-footnote");
        var noteLink = note.createChild("a");
        noteLink.href = "https://developers.google.com/chrome-developer-tools/docs/shortcuts";
        noteLink.target = "_blank";
        noteLink.createTextChild(WebInspector.UIString("Full list of keyboard shortcuts and gestures"));
        return view;
    }
}
WebInspector.shortcutsScreen;
WebInspector.ShortcutsSection = function (name) {
    this.name = name;
    this._lines = ([]);
    this.order = ++WebInspector.ShortcutsSection._sequenceNumber;
};
WebInspector.ShortcutsSection._sequenceNumber = 0;
WebInspector.ShortcutsSection.prototype = {
    addKey: function (key, description) {
        this._addLine(this._renderKey(key), description);
    }, addRelatedKeys: function (keys, description) {
        this._addLine(this._renderSequence(keys, "/"), description);
    }, addAlternateKeys: function (keys, description) {
        this._addLine(this._renderSequence(keys, WebInspector.UIString("or")), description);
    }, _addLine: function (keyElement, description) {
        this._lines.push({key: keyElement, text: description})
    }, renderSection: function (container) {
        var parent = container.createChild("div", "help-block");
        var headLine = parent.createChild("div", "help-line");
        headLine.createChild("div", "help-key-cell");
        headLine.createChild("div", "help-section-title help-cell").textContent = this.name;
        for (var i = 0; i < this._lines.length; ++i) {
            var line = parent.createChild("div", "help-line");
            var keyCell = line.createChild("div", "help-key-cell");
            keyCell.appendChild(this._lines[i].key);
            keyCell.appendChild(this._createSpan("help-key-delimiter", ":"));
            line.createChild("div", "help-cell").textContent = this._lines[i].text;
        }
    }, _renderSequence: function (sequence, delimiter) {
        var delimiterSpan = this._createSpan("help-key-delimiter", delimiter);
        return this._joinNodes(sequence.map(this._renderKey.bind(this)), delimiterSpan);
    }, _renderKey: function (key) {
        var keyName = key.name;
        var plus = this._createSpan("help-combine-keys", "+");
        return this._joinNodes(keyName.split(" + ").map(this._createSpan.bind(this, "help-key")), plus);
    }, _createSpan: function (className, textContent) {
        var node = document.createElement("span");
        node.className = className;
        node.textContent = textContent;
        return node;
    }, _joinNodes: function (nodes, delimiter) {
        var result = document.createDocumentFragment();
        for (var i = 0; i < nodes.length; ++i) {
            if (i > 0)
                result.appendChild(delimiter.cloneNode(true));
            result.appendChild(nodes[i]);
        }
        return result;
    }
}
WebInspector.ShortcutsScreen.registerShortcuts = function () {
    var elementsSection = WebInspector.shortcutsScreen.section(WebInspector.UIString("Elements Panel"));
    var navigate = WebInspector.ShortcutsScreen.ElementsPanelShortcuts.NavigateUp.concat(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.NavigateDown);
    elementsSection.addRelatedKeys(navigate, WebInspector.UIString("Navigate elements"));
    var expandCollapse = WebInspector.ShortcutsScreen.ElementsPanelShortcuts.Expand.concat(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.Collapse);
    elementsSection.addRelatedKeys(expandCollapse, WebInspector.UIString("Expand/collapse"));
    elementsSection.addAlternateKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.EditAttribute, WebInspector.UIString("Edit attribute"));
    elementsSection.addAlternateKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.HideElement, WebInspector.UIString("Hide element"));
    elementsSection.addAlternateKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.ToggleEditAsHTML, WebInspector.UIString("Toggle edit as HTML"));
    var stylesPaneSection = WebInspector.shortcutsScreen.section(WebInspector.UIString("Styles Pane"));
    var nextPreviousProperty = WebInspector.ShortcutsScreen.ElementsPanelShortcuts.NextProperty.concat(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.PreviousProperty);
    stylesPaneSection.addRelatedKeys(nextPreviousProperty, WebInspector.UIString("Next/previous property"));
    stylesPaneSection.addRelatedKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.IncrementValue, WebInspector.UIString("Increment value"));
    stylesPaneSection.addRelatedKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.DecrementValue, WebInspector.UIString("Decrement value"));
    stylesPaneSection.addAlternateKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy10, WebInspector.UIString("Increment by %f", 10));
    stylesPaneSection.addAlternateKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy10, WebInspector.UIString("Decrement by %f", 10));
    stylesPaneSection.addAlternateKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy100, WebInspector.UIString("Increment by %f", 100));
    stylesPaneSection.addAlternateKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy100, WebInspector.UIString("Decrement by %f", 100));
    stylesPaneSection.addAlternateKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.IncrementBy01, WebInspector.UIString("Increment by %f", 0.1));
    stylesPaneSection.addAlternateKeys(WebInspector.ShortcutsScreen.ElementsPanelShortcuts.DecrementBy01, WebInspector.UIString("Decrement by %f", 0.1));
    var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Debugger"));
    section.addAlternateKeys(WebInspector.shortcutRegistry.shortcutDescriptorsForAction("debugger.toggle-pause"), WebInspector.UIString("Pause/Continue"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.StepOver, WebInspector.UIString("Step over"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.StepInto, WebInspector.UIString("Step into"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.StepOut, WebInspector.UIString("Step out"));
    var nextAndPrevFrameKeys = WebInspector.ShortcutsScreen.SourcesPanelShortcuts.NextCallFrame.concat(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.PrevCallFrame);
    section.addRelatedKeys(nextAndPrevFrameKeys, WebInspector.UIString("Next/previous call frame"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.EvaluateSelectionInConsole, WebInspector.UIString("Evaluate selection in console"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.AddSelectionToWatch, WebInspector.UIString("Add selection to watch"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.ToggleBreakpoint, WebInspector.UIString("Toggle breakpoint"));
    section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Text Editor"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.GoToMember, WebInspector.UIString("Go to member"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.ToggleAutocompletion, WebInspector.UIString("Autocompletion"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.GoToLine, WebInspector.UIString("Go to line"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.JumpToPreviousLocation, WebInspector.UIString("Jump to previous editing location"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.JumpToNextLocation, WebInspector.UIString("Jump to next editing location"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.ToggleComment, WebInspector.UIString("Toggle comment"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.IncreaseCSSUnitByOne, WebInspector.UIString("Increment CSS unit by 1"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.DecreaseCSSUnitByOne, WebInspector.UIString("Decrement CSS unit by 1"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.IncreaseCSSUnitByTen, WebInspector.UIString("Increment CSS unit by 10"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.DecreaseCSSUnitByTen, WebInspector.UIString("Decrement CSS unit by 10"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.SelectNextOccurrence, WebInspector.UIString("Select next occurrence"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.SoftUndo, WebInspector.UIString("Soft undo"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.GotoMatchingBracket, WebInspector.UIString("Go to matching bracket"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.SourcesPanelShortcuts.CloseEditorTab, WebInspector.UIString("Close editor tab"));
    section.addAlternateKeys(WebInspector.shortcutRegistry.shortcutDescriptorsForAction("sources.switch-file"), WebInspector.UIString("Switch between files with the same name and different extensions."));
    section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Timeline Panel"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.TimelinePanelShortcuts.StartStopRecording, WebInspector.UIString("Start/stop recording"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.TimelinePanelShortcuts.SaveToFile, WebInspector.UIString("Save timeline data"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.TimelinePanelShortcuts.LoadFromFile, WebInspector.UIString("Load timeline data"));
    section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Profiles Panel"));
    section.addAlternateKeys(WebInspector.ShortcutsScreen.ProfilesPanelShortcuts.StartStopRecording, WebInspector.UIString("Start/stop recording"));
    if (WebInspector.experimentsSettings.isEnabled("layersPanel")) {
        section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Layers Panel"));
        section.addAlternateKeys(WebInspector.ShortcutsScreen.LayersPanelShortcuts.ResetView, WebInspector.UIString("Reset view"));
        section.addAlternateKeys(WebInspector.ShortcutsScreen.LayersPanelShortcuts.ZoomIn, WebInspector.UIString("Zoom in"));
        section.addAlternateKeys(WebInspector.ShortcutsScreen.LayersPanelShortcuts.ZoomOut, WebInspector.UIString("Zoom out"));
        var PanUpDown = WebInspector.ShortcutsScreen.LayersPanelShortcuts.PanUp.concat(WebInspector.ShortcutsScreen.LayersPanelShortcuts.PanDown);
        section.addRelatedKeys(PanUpDown, WebInspector.UIString("Pan up/down"));
        var PanLeftRight = WebInspector.ShortcutsScreen.LayersPanelShortcuts.PanLeft.concat(WebInspector.ShortcutsScreen.LayersPanelShortcuts.PanRight);
        section.addRelatedKeys(PanLeftRight, WebInspector.UIString("Pan left/right"));
        var rotate = WebInspector.ShortcutsScreen.LayersPanelShortcuts.RotateCWX.concat(WebInspector.ShortcutsScreen.LayersPanelShortcuts.RotateCCWX).concat(WebInspector.ShortcutsScreen.LayersPanelShortcuts.RotateCWY).concat(WebInspector.ShortcutsScreen.LayersPanelShortcuts.RotateCCWY);
        section.addRelatedKeys(rotate, WebInspector.UIString("Rotate"));
    }
}
WebInspector.ShortcutsScreen.ElementsPanelShortcuts = {
    NavigateUp: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up)],
    NavigateDown: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down)],
    Expand: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Right)],
    Collapse: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Left)],
    EditAttribute: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Enter)],
    HideElement: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.H)],
    ToggleEditAsHTML: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F2)],
    NextProperty: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Tab)],
    PreviousProperty: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Tab, WebInspector.KeyboardShortcut.Modifiers.Shift)],
    IncrementValue: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up)],
    DecrementValue: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down)],
    IncrementBy10: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageUp), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up, WebInspector.KeyboardShortcut.Modifiers.Shift)],
    DecrementBy10: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageDown), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down, WebInspector.KeyboardShortcut.Modifiers.Shift)],
    IncrementBy100: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageUp, WebInspector.KeyboardShortcut.Modifiers.Shift)],
    DecrementBy100: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageDown, WebInspector.KeyboardShortcut.Modifiers.Shift)],
    IncrementBy01: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up, WebInspector.KeyboardShortcut.Modifiers.Alt)],
    DecrementBy01: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down, WebInspector.KeyboardShortcut.Modifiers.Alt)]
};
WebInspector.ShortcutsScreen.SourcesPanelShortcuts = {
    SelectNextOccurrence: [WebInspector.KeyboardShortcut.makeDescriptor("d", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    SoftUndo: [WebInspector.KeyboardShortcut.makeDescriptor("u", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    GotoMatchingBracket: [WebInspector.KeyboardShortcut.makeDescriptor("m", WebInspector.KeyboardShortcut.Modifiers.Ctrl)],
    ToggleAutocompletion: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Space, WebInspector.KeyboardShortcut.Modifiers.Ctrl)],
    IncreaseCSSUnitByOne: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up, WebInspector.KeyboardShortcut.Modifiers.Alt)],
    DecreaseCSSUnitByOne: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down, WebInspector.KeyboardShortcut.Modifiers.Alt)],
    IncreaseCSSUnitByTen: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageUp, WebInspector.KeyboardShortcut.Modifiers.Alt)],
    DecreaseCSSUnitByTen: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.PageDown, WebInspector.KeyboardShortcut.Modifiers.Alt)],
    RunSnippet: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Enter, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    StepOver: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F10), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.SingleQuote, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    StepInto: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    StepOut: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11, WebInspector.KeyboardShortcut.Modifiers.Shift), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, WebInspector.KeyboardShortcut.Modifiers.Shift | WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    EvaluateSelectionInConsole: [WebInspector.KeyboardShortcut.makeDescriptor("e", WebInspector.KeyboardShortcut.Modifiers.Shift | WebInspector.KeyboardShortcut.Modifiers.Ctrl)],
    AddSelectionToWatch: [WebInspector.KeyboardShortcut.makeDescriptor("a", WebInspector.KeyboardShortcut.Modifiers.Shift | WebInspector.KeyboardShortcut.Modifiers.Ctrl)],
    GoToMember: [WebInspector.KeyboardShortcut.makeDescriptor("p", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta | WebInspector.KeyboardShortcut.Modifiers.Shift)],
    GoToLine: [WebInspector.KeyboardShortcut.makeDescriptor("g", WebInspector.KeyboardShortcut.Modifiers.Ctrl)],
    ToggleBreakpoint: [WebInspector.KeyboardShortcut.makeDescriptor("b", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    NextCallFrame: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Period, WebInspector.KeyboardShortcut.Modifiers.Ctrl)],
    PrevCallFrame: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Comma, WebInspector.KeyboardShortcut.Modifiers.Ctrl)],
    ToggleComment: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Slash, WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    JumpToPreviousLocation: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Minus, WebInspector.KeyboardShortcut.Modifiers.Alt)],
    JumpToNextLocation: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Plus, WebInspector.KeyboardShortcut.Modifiers.Alt)],
    CloseEditorTab: [WebInspector.KeyboardShortcut.makeDescriptor("w", WebInspector.KeyboardShortcut.Modifiers.Alt)],
    Save: [WebInspector.KeyboardShortcut.makeDescriptor("s", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    SaveAll: [WebInspector.KeyboardShortcut.makeDescriptor("s", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta | WebInspector.KeyboardShortcut.Modifiers.ShiftOrOption)],
};
WebInspector.ShortcutsScreen.TimelinePanelShortcuts = {
    StartStopRecording: [WebInspector.KeyboardShortcut.makeDescriptor("e", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    SaveToFile: [WebInspector.KeyboardShortcut.makeDescriptor("s", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)],
    LoadFromFile: [WebInspector.KeyboardShortcut.makeDescriptor("o", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)]
};
WebInspector.ShortcutsScreen.ProfilesPanelShortcuts = {StartStopRecording: [WebInspector.KeyboardShortcut.makeDescriptor("e", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)]};
WebInspector.ShortcutsScreen.LayersPanelShortcuts = {
    ResetView: [WebInspector.KeyboardShortcut.makeDescriptor("0")],
    ZoomIn: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Plus, WebInspector.KeyboardShortcut.Modifiers.Shift), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.NumpadPlus)],
    ZoomOut: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Minus, WebInspector.KeyboardShortcut.Modifiers.Shift), WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.NumpadMinus)],
    PanUp: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up), WebInspector.KeyboardShortcut.makeDescriptor("w")],
    PanDown: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down), WebInspector.KeyboardShortcut.makeDescriptor("s")],
    PanLeft: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Left), WebInspector.KeyboardShortcut.makeDescriptor("a")],
    PanRight: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Right), WebInspector.KeyboardShortcut.makeDescriptor("d")],
    RotateCWX: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up, WebInspector.KeyboardShortcut.Modifiers.Shift), WebInspector.KeyboardShortcut.makeDescriptor("w", WebInspector.KeyboardShortcut.Modifiers.Shift)],
    RotateCCWX: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down, WebInspector.KeyboardShortcut.Modifiers.Shift), WebInspector.KeyboardShortcut.makeDescriptor("s", WebInspector.KeyboardShortcut.Modifiers.Shift)],
    RotateCWY: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Left, WebInspector.KeyboardShortcut.Modifiers.Shift), WebInspector.KeyboardShortcut.makeDescriptor("a", WebInspector.KeyboardShortcut.Modifiers.Shift)],
    RotateCCWY: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Right, WebInspector.KeyboardShortcut.Modifiers.Shift), WebInspector.KeyboardShortcut.makeDescriptor("d", WebInspector.KeyboardShortcut.Modifiers.Shift)]
}
WebInspector.CookieParser = function () {
}
WebInspector.CookieParser.KeyValue = function (key, value, position) {
    this.key = key;
    this.value = value;
    this.position = position;
}
WebInspector.CookieParser.prototype = {
    cookies: function () {
        return this._cookies;
    }, parseCookie: function (cookieHeader) {
        if (!this._initialize(cookieHeader))
            return null;
        for (var kv = this._extractKeyValue(); kv; kv = this._extractKeyValue()) {
            if (kv.key.charAt(0) === "$" && this._lastCookie)
                this._lastCookie.addAttribute(kv.key.slice(1), kv.value); else if (kv.key.toLowerCase() !== "$version" && typeof kv.value === "string")
                this._addCookie(kv, WebInspector.Cookie.Type.Request);
            this._advanceAndCheckCookieDelimiter();
        }
        this._flushCookie();
        return this._cookies;
    }, parseSetCookie: function (setCookieHeader) {
        if (!this._initialize(setCookieHeader))
            return null;
        for (var kv = this._extractKeyValue(); kv; kv = this._extractKeyValue()) {
            if (this._lastCookie)
                this._lastCookie.addAttribute(kv.key, kv.value); else
                this._addCookie(kv, WebInspector.Cookie.Type.Response);
            if (this._advanceAndCheckCookieDelimiter())
                this._flushCookie();
        }
        this._flushCookie();
        return this._cookies;
    }, _initialize: function (headerValue) {
        this._input = headerValue;
        if (typeof headerValue !== "string")
            return false;
        this._cookies = [];
        this._lastCookie = null;
        this._originalInputLength = this._input.length;
        return true;
    }, _flushCookie: function () {
        if (this._lastCookie)
            this._lastCookie.setSize(this._originalInputLength - this._input.length - this._lastCookiePosition);
        this._lastCookie = null;
    }, _extractKeyValue: function () {
        if (!this._input || !this._input.length)
            return null;
        var keyValueMatch = /^[ \t]*([^\s=;]+)[ \t]*(?:=[ \t]*([^;\n]*))?/.exec(this._input);
        if (!keyValueMatch) {
            console.log("Failed parsing cookie header before: " + this._input);
            return null;
        }
        var result = new WebInspector.CookieParser.KeyValue(keyValueMatch[1], keyValueMatch[2] && keyValueMatch[2].trim(), this._originalInputLength - this._input.length);
        this._input = this._input.slice(keyValueMatch[0].length);
        return result;
    }, _advanceAndCheckCookieDelimiter: function () {
        var match = /^\s*[\n;]\s*/.exec(this._input);
        if (!match)
            return false;
        this._input = this._input.slice(match[0].length);
        return match[0].match("\n") !== null;
    }, _addCookie: function (keyValue, type) {
        if (this._lastCookie)
            this._lastCookie.setSize(keyValue.position - this._lastCookiePosition);
        this._lastCookie = typeof keyValue.value === "string" ? new WebInspector.Cookie(keyValue.key, keyValue.value, type) : new WebInspector.Cookie("", keyValue.key, type);
        this._lastCookiePosition = keyValue.position;
        this._cookies.push(this._lastCookie);
    }
};
WebInspector.CookieParser.parseCookie = function (header) {
    return (new WebInspector.CookieParser()).parseCookie(header);
}
WebInspector.CookieParser.parseSetCookie = function (header) {
    return (new WebInspector.CookieParser()).parseSetCookie(header);
}
WebInspector.Cookie = function (name, value, type) {
    this._name = name;
    this._value = value;
    this._type = type;
    this._attributes = {};
}
WebInspector.Cookie.prototype = {
    name: function () {
        return this._name;
    }, value: function () {
        return this._value;
    }, type: function () {
        return this._type;
    }, httpOnly: function () {
        return "httponly"in this._attributes;
    }, secure: function () {
        return "secure"in this._attributes;
    }, session: function () {
        return !("expires"in this._attributes || "max-age"in this._attributes);
    }, path: function () {
        return this._attributes["path"];
    }, port: function () {
        return this._attributes["port"];
    }, domain: function () {
        return this._attributes["domain"];
    }, expires: function () {
        return this._attributes["expires"];
    }, maxAge: function () {
        return this._attributes["max-age"];
    }, size: function () {
        return this._size;
    }, setSize: function (size) {
        this._size = size;
    }, expiresDate: function (requestDate) {
        if (this.maxAge()) {
            var targetDate = requestDate === null ? new Date() : requestDate;
            return new Date(targetDate.getTime() + 1000 * this.maxAge());
        }
        if (this.expires())
            return new Date(this.expires());
        return null;
    }, attributes: function () {
        return this._attributes;
    }, addAttribute: function (key, value) {
        this._attributes[key.toLowerCase()] = value;
    }, remove: function (callback) {
        PageAgent.deleteCookie(this.name(), (this.secure() ? "https://" : "http://") + this.domain() + this.path(), callback);
    }
}
WebInspector.Cookie.Type = {Request: 0, Response: 1};
WebInspector.Cookies = {}
WebInspector.Cookies.getCookiesAsync = function (callback) {
    function mycallback(error, cookies) {
        if (error)
            return;
        callback(cookies.map(WebInspector.Cookies.buildCookieProtocolObject));
    }

    PageAgent.getCookies(mycallback);
}
WebInspector.Cookies.buildCookieProtocolObject = function (protocolCookie) {
    var cookie = new WebInspector.Cookie(protocolCookie.name, protocolCookie.value, null);
    cookie.addAttribute("domain", protocolCookie["domain"]);
    cookie.addAttribute("path", protocolCookie["path"]);
    cookie.addAttribute("port", protocolCookie["port"]);
    if (protocolCookie["expires"])
        cookie.addAttribute("expires", protocolCookie["expires"]);
    if (protocolCookie["httpOnly"])
        cookie.addAttribute("httpOnly");
    if (protocolCookie["secure"])
        cookie.addAttribute("secure");
    cookie.setSize(protocolCookie["size"]);
    return cookie;
}
WebInspector.Cookies.cookieMatchesResourceURL = function (cookie, resourceURL) {
    var url = resourceURL.asParsedURL();
    if (!url || !WebInspector.Cookies.cookieDomainMatchesResourceDomain(cookie.domain(), url.host))
        return false;
    return (url.path.startsWith(cookie.path()) && (!cookie.port() || url.port == cookie.port()) && (!cookie.secure() || url.scheme === "https"));
}
WebInspector.Cookies.cookieDomainMatchesResourceDomain = function (cookieDomain, resourceDomain) {
    if (cookieDomain.charAt(0) !== '.')
        return resourceDomain === cookieDomain;
    return !!resourceDomain.match(new RegExp("^([^\\.]+\\.)*" + cookieDomain.substring(1).escapeForRegExp() + "$", "i"));
}
WebInspector.SearchableView = function (searchable) {
    WebInspector.VBox.call(this);
    this._searchProvider = searchable;
    this.element.addEventListener("keydown", this._onKeyDown.bind(this), false);
    this._footerElementContainer = this.element.createChild("div", "search-bar status-bar hidden");
    this._footerElementContainer.style.order = 100;
    this._footerElement = this._footerElementContainer.createChild("table", "toolbar-search");
    this._footerElement.cellSpacing = 0;
    this._firstRowElement = this._footerElement.createChild("tr");
    this._secondRowElement = this._footerElement.createChild("tr", "hidden");
    var searchControlElementColumn = this._firstRowElement.createChild("td");
    this._searchControlElement = searchControlElementColumn.createChild("span", "toolbar-search-control");
    this._searchInputElement = this._searchControlElement.createChild("input", "search-replace");
    this._searchInputElement.id = "search-input-field";
    this._searchInputElement.placeholder = WebInspector.UIString("Find");
    this._matchesElement = this._searchControlElement.createChild("label", "search-results-matches");
    this._matchesElement.setAttribute("for", "search-input-field");
    this._searchNavigationElement = this._searchControlElement.createChild("div", "toolbar-search-navigation-controls");
    this._searchNavigationPrevElement = this._searchNavigationElement.createChild("div", "toolbar-search-navigation toolbar-search-navigation-prev");
    this._searchNavigationPrevElement.addEventListener("click", this._onPrevButtonSearch.bind(this), false);
    this._searchNavigationPrevElement.title = WebInspector.UIString("Search Previous");
    this._searchNavigationNextElement = this._searchNavigationElement.createChild("div", "toolbar-search-navigation toolbar-search-navigation-next");
    this._searchNavigationNextElement.addEventListener("click", this._onNextButtonSearch.bind(this), false);
    this._searchNavigationNextElement.title = WebInspector.UIString("Search Next");
    this._searchInputElement.addEventListener("mousedown", this._onSearchFieldManualFocus.bind(this), false);
    this._searchInputElement.addEventListener("keydown", this._onSearchKeyDown.bind(this), true);
    this._searchInputElement.addEventListener("input", this._onInput.bind(this), false);
    this._replaceInputElement = this._secondRowElement.createChild("td").createChild("input", "search-replace toolbar-replace-control");
    this._replaceInputElement.addEventListener("keydown", this._onReplaceKeyDown.bind(this), true);
    this._replaceInputElement.placeholder = WebInspector.UIString("Replace");
    this._findButtonElement = this._firstRowElement.createChild("td").createChild("button", "hidden");
    this._findButtonElement.textContent = WebInspector.UIString("Find");
    this._findButtonElement.tabIndex = -1;
    this._findButtonElement.addEventListener("click", this._onFindClick.bind(this), false);
    this._replaceButtonElement = this._secondRowElement.createChild("td").createChild("button");
    this._replaceButtonElement.textContent = WebInspector.UIString("Replace");
    this._replaceButtonElement.disabled = true;
    this._replaceButtonElement.tabIndex = -1;
    this._replaceButtonElement.addEventListener("click", this._replace.bind(this), false);
    this._prevButtonElement = this._firstRowElement.createChild("td").createChild("button", "hidden");
    this._prevButtonElement.textContent = WebInspector.UIString("Previous");
    this._prevButtonElement.tabIndex = -1;
    this._prevButtonElement.addEventListener("click", this._onPreviousClick.bind(this), false);
    this._replaceAllButtonElement = this._secondRowElement.createChild("td").createChild("button");
    this._replaceAllButtonElement.textContent = WebInspector.UIString("Replace All");
    this._replaceAllButtonElement.addEventListener("click", this._replaceAll.bind(this), false);
    this._replaceElement = this._firstRowElement.createChild("td").createChild("span");
    this._replaceCheckboxElement = this._replaceElement.createChild("input");
    this._replaceCheckboxElement.type = "checkbox";
    this._uniqueId = ++WebInspector.SearchableView._lastUniqueId;
    var replaceCheckboxId = "search-replace-trigger" + this._uniqueId;
    this._replaceCheckboxElement.id = replaceCheckboxId;
    this._replaceCheckboxElement.addEventListener("change", this._updateSecondRowVisibility.bind(this), false);
    this._replaceLabelElement = this._replaceElement.createChild("label");
    this._replaceLabelElement.textContent = WebInspector.UIString("Replace");
    this._replaceLabelElement.setAttribute("for", replaceCheckboxId);
    var cancelButtonElement = this._firstRowElement.createChild("td").createChild("button");
    cancelButtonElement.textContent = WebInspector.UIString("Cancel");
    cancelButtonElement.tabIndex = -1;
    cancelButtonElement.addEventListener("click", this.closeSearch.bind(this), false);
    this._minimalSearchQuerySize = 3;
    this._registerShortcuts();
}
WebInspector.SearchableView._lastUniqueId = 0;
WebInspector.SearchableView.findShortcuts = function () {
    if (WebInspector.SearchableView._findShortcuts)
        return WebInspector.SearchableView._findShortcuts;
    WebInspector.SearchableView._findShortcuts = [WebInspector.KeyboardShortcut.makeDescriptor("f", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)];
    if (!WebInspector.isMac())
        WebInspector.SearchableView._findShortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F3));
    return WebInspector.SearchableView._findShortcuts;
}
WebInspector.SearchableView.cancelSearchShortcuts = function () {
    if (WebInspector.SearchableView._cancelSearchShortcuts)
        return WebInspector.SearchableView._cancelSearchShortcuts;
    WebInspector.SearchableView._cancelSearchShortcuts = [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Esc)];
    return WebInspector.SearchableView._cancelSearchShortcuts;
}
WebInspector.SearchableView.findNextShortcut = function () {
    if (WebInspector.SearchableView._findNextShortcut)
        return WebInspector.SearchableView._findNextShortcut;
    WebInspector.SearchableView._findNextShortcut = [];
    if (WebInspector.isMac())
        WebInspector.SearchableView._findNextShortcut.push(WebInspector.KeyboardShortcut.makeDescriptor("g", WebInspector.KeyboardShortcut.Modifiers.Meta));
    return WebInspector.SearchableView._findNextShortcut;
}
WebInspector.SearchableView.findPreviousShortcuts = function () {
    if (WebInspector.SearchableView._findPreviousShortcuts)
        return WebInspector.SearchableView._findPreviousShortcuts;
    WebInspector.SearchableView._findPreviousShortcuts = [];
    if (WebInspector.isMac())
        WebInspector.SearchableView._findPreviousShortcuts.push(WebInspector.KeyboardShortcut.makeDescriptor("g", WebInspector.KeyboardShortcut.Modifiers.Meta | WebInspector.KeyboardShortcut.Modifiers.Shift));
    return WebInspector.SearchableView._findPreviousShortcuts;
}
WebInspector.SearchableView.prototype = {
    defaultFocusedElement: function () {
        var children = this.children();
        for (var i = 0; i < children.length; ++i) {
            var element = children[i].defaultFocusedElement();
            if (element)
                return element;
        }
        return WebInspector.View.prototype.defaultFocusedElement.call(this);
    }, _onKeyDown: function (event) {
        var shortcutKey = WebInspector.KeyboardShortcut.makeKeyFromEvent((event));
        var handler = this._shortcuts[shortcutKey];
        if (handler && handler(event))
            event.consume(true);
    }, _registerShortcuts: function () {
        this._shortcuts = {};
        function register(shortcuts, handler) {
            for (var i = 0; i < shortcuts.length; ++i)
                this._shortcuts[shortcuts[i].key] = handler;
        }

        register.call(this, WebInspector.SearchableView.findShortcuts(), this.handleFindShortcut.bind(this));
        register.call(this, WebInspector.SearchableView.cancelSearchShortcuts(), this.handleCancelSearchShortcut.bind(this));
        register.call(this, WebInspector.SearchableView.findNextShortcut(), this.handleFindNextShortcut.bind(this));
        register.call(this, WebInspector.SearchableView.findPreviousShortcuts(), this.handleFindPreviousShortcut.bind(this));
    }, setMinimalSearchQuerySize: function (minimalSearchQuerySize) {
        this._minimalSearchQuerySize = minimalSearchQuerySize;
    }, setReplaceable: function (replaceable) {
        this._replaceable = replaceable;
    }, updateSearchMatchesCount: function (matches) {
        this._searchProvider.currentSearchMatches = matches;
        this._updateSearchMatchesCountAndCurrentMatchIndex(this._searchProvider.currentQuery ? matches : 0, -1);
    }, updateCurrentMatchIndex: function (currentMatchIndex) {
        this._updateSearchMatchesCountAndCurrentMatchIndex(this._searchProvider.currentSearchMatches, currentMatchIndex);
    }, isSearchVisible: function () {
        return this._searchIsVisible;
    }, closeSearch: function () {
        this.cancelSearch();
        if (WebInspector.currentFocusElement().isDescendant(this._footerElementContainer))
            this.focus();
    }, _toggleSearchBar: function (toggled) {
        this._footerElementContainer.classList.toggle("hidden", !toggled);
        this.doResize();
    }, cancelSearch: function () {
        if (!this._searchIsVisible)
            return;
        this.resetSearch();
        delete this._searchIsVisible;
        this._toggleSearchBar(false);
    }, resetSearch: function () {
        this._clearSearch();
        this._updateReplaceVisibility();
        this._matchesElement.textContent = "";
    }, handleFindNextShortcut: function () {
        if (!this._searchIsVisible)
            return false;
        this._searchProvider.jumpToNextSearchResult();
        return true;
    }, handleFindPreviousShortcut: function () {
        if (!this._searchIsVisible)
            return false;
        this._searchProvider.jumpToPreviousSearchResult();
        return true;
    }, handleFindShortcut: function () {
        this.showSearchField();
        return true;
    }, handleCancelSearchShortcut: function () {
        if (!this._searchIsVisible)
            return false;
        this.closeSearch();
        return true;
    }, _updateSearchNavigationButtonState: function (enabled) {
        this._replaceButtonElement.disabled = !enabled;
        if (enabled) {
            this._searchNavigationPrevElement.classList.add("enabled");
            this._searchNavigationNextElement.classList.add("enabled");
        } else {
            this._searchNavigationPrevElement.classList.remove("enabled");
            this._searchNavigationNextElement.classList.remove("enabled");
        }
    }, _updateSearchMatchesCountAndCurrentMatchIndex: function (matches, currentMatchIndex) {
        if (!this._currentQuery)
            this._matchesElement.textContent = ""; else if (matches === 0 || currentMatchIndex >= 0)
            this._matchesElement.textContent = WebInspector.UIString("%d of %d", currentMatchIndex + 1, matches); else if (matches === 1)
            this._matchesElement.textContent = WebInspector.UIString("1 match"); else
            this._matchesElement.textContent = WebInspector.UIString("%d matches", matches);
        this._updateSearchNavigationButtonState(matches > 0);
    }, showSearchField: function () {
        if (this._searchIsVisible)
            this.cancelSearch();
        var queryCandidate;
        if (WebInspector.currentFocusElement() !== this._searchInputElement) {
            var selection = window.getSelection();
            if (selection.rangeCount)
                queryCandidate = selection.toString().replace(/\r?\n.*/, "");
        }
        this._toggleSearchBar(true);
        this._updateReplaceVisibility();
        if (queryCandidate)
            this._searchInputElement.value = queryCandidate;
        this._performSearch(false, false);
        this._searchInputElement.focus();
        this._searchInputElement.select();
        this._searchIsVisible = true;
    }, _updateReplaceVisibility: function () {
        this._replaceElement.classList.toggle("hidden", !this._replaceable);
        if (!this._replaceable) {
            this._replaceCheckboxElement.checked = false;
            this._updateSecondRowVisibility();
        }
    }, _onSearchFieldManualFocus: function (event) {
        WebInspector.setCurrentFocusElement(event.target);
    }, _onSearchKeyDown: function (event) {
        if (!isEnterKey(event))
            return;
        if (!this._currentQuery)
            this._performSearch(true, true, event.shiftKey); else
            this._jumpToNextSearchResult(event.shiftKey);
    }, _onReplaceKeyDown: function (event) {
        if (isEnterKey(event))
            this._replace();
    }, _jumpToNextSearchResult: function (isBackwardSearch) {
        if (!this._currentQuery || !this._searchNavigationPrevElement.classList.contains("enabled"))
            return;
        if (isBackwardSearch)
            this._searchProvider.jumpToPreviousSearchResult(); else
            this._searchProvider.jumpToNextSearchResult();
    }, _onNextButtonSearch: function (event) {
        if (!this._searchNavigationNextElement.classList.contains("enabled"))
            return;
        this._jumpToNextSearchResult();
        this._searchInputElement.focus();
    }, _onPrevButtonSearch: function (event) {
        if (!this._searchNavigationPrevElement.classList.contains("enabled"))
            return;
        this._jumpToNextSearchResult(true);
        this._searchInputElement.focus();
    }, _onFindClick: function (event) {
        if (!this._currentQuery)
            this._performSearch(true, true); else
            this._jumpToNextSearchResult();
        this._searchInputElement.focus();
    }, _onPreviousClick: function (event) {
        if (!this._currentQuery)
            this._performSearch(true, true, true); else
            this._jumpToNextSearchResult(true);
        this._searchInputElement.focus();
    }, _clearSearch: function () {
        delete this._currentQuery;
        if (!!this._searchProvider.currentQuery) {
            delete this._searchProvider.currentQuery;
            this._searchProvider.searchCanceled();
        }
        this._updateSearchMatchesCountAndCurrentMatchIndex(0, -1);
    }, _performSearch: function (forceSearch, shouldJump, jumpBackwards) {
        var query = this._searchInputElement.value;
        if (!query || (!forceSearch && query.length < this._minimalSearchQuerySize && !this._currentQuery)) {
            this._clearSearch();
            return;
        }
        this._currentQuery = query;
        this._searchProvider.currentQuery = query;
        this._searchProvider.performSearch(query, shouldJump, jumpBackwards);
    }, _updateSecondRowVisibility: function () {
        var secondRowVisible = this._replaceCheckboxElement.checked;
        this._footerElementContainer.classList.toggle("replaceable", secondRowVisible);
        this._footerElement.classList.toggle("toolbar-search-replace", secondRowVisible);
        this._secondRowElement.classList.toggle("hidden", !secondRowVisible);
        this._prevButtonElement.classList.toggle("hidden", !secondRowVisible);
        this._findButtonElement.classList.toggle("hidden", !secondRowVisible);
        this._replaceCheckboxElement.tabIndex = secondRowVisible ? -1 : 0;
        if (secondRowVisible)
            this._replaceInputElement.focus(); else
            this._searchInputElement.focus();
        this.doResize();
    }, _replace: function () {
        (this._searchProvider).replaceSelectionWith(this._replaceInputElement.value);
        delete this._currentQuery;
        this._performSearch(true, true);
    }, _replaceAll: function () {
        (this._searchProvider).replaceAllWith(this._searchInputElement.value, this._replaceInputElement.value);
    }, _onInput: function (event) {
        this._onValueChanged();
    }, _onValueChanged: function () {
        this._performSearch(false, true);
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.Searchable = function () {
}
WebInspector.Searchable.prototype = {
    searchCanceled: function () {
    }, performSearch: function (query, shouldJump, jumpBackwards) {
    }, jumpToNextSearchResult: function () {
    }, jumpToPreviousSearchResult: function () {
    }
}
WebInspector.Replaceable = function () {
}
WebInspector.Replaceable.prototype = {
    replaceSelectionWith: function (text) {
    }, replaceAllWith: function (query, replacement) {
    }
}
WebInspector.FilterBar = function () {
    this._filtersShown = false;
    this._element = document.createElement("div");
    this._element.className = "hbox";
    this._filterButton = new WebInspector.StatusBarButton(WebInspector.UIString("Filter"), "filters-toggle", 3);
    this._filterButton.element.addEventListener("click", this._handleFilterButtonClick.bind(this), false);
    this._filters = [];
}
WebInspector.FilterBar.Events = {FiltersToggled: "FiltersToggled"}
WebInspector.FilterBar.FilterBarState = {Inactive: "inactive", Active: "active", Shown: "shown"};
WebInspector.FilterBar.prototype = {
    setName: function (name) {
        this._stateSetting = WebInspector.settings.createSetting("filterBar-" + name + "-toggled", false);
        this._setState(this._stateSetting.get());
    }, filterButton: function () {
        return this._filterButton;
    }, filtersElement: function () {
        return this._element;
    }, filtersToggled: function () {
        return this._filtersShown;
    }, addFilter: function (filter) {
        this._filters.push(filter);
        this._element.appendChild(filter.element());
        filter.addEventListener(WebInspector.FilterUI.Events.FilterChanged, this._filterChanged, this);
        this._updateFilterButton();
    }, _filterChanged: function (event) {
        this._updateFilterButton();
    }, _filterBarState: function () {
        if (this._filtersShown)
            return WebInspector.FilterBar.FilterBarState.Shown;
        var isActive = false;
        for (var i = 0; i < this._filters.length; ++i) {
            if (this._filters[i].isActive())
                return WebInspector.FilterBar.FilterBarState.Active;
        }
        return WebInspector.FilterBar.FilterBarState.Inactive;
    }, _updateFilterButton: function () {
        this._filterButton.state = this._filterBarState();
    }, _handleFilterButtonClick: function (event) {
        this._setState(!this._filtersShown);
    }, _setState: function (filtersShown) {
        if (this._filtersShown === filtersShown)
            return;
        this._filtersShown = filtersShown;
        if (this._stateSetting)
            this._stateSetting.set(filtersShown);
        this._updateFilterButton();
        this.dispatchEventToListeners(WebInspector.FilterBar.Events.FiltersToggled, this._filtersShown);
        if (this._filtersShown) {
            for (var i = 0; i < this._filters.length; ++i) {
                if (this._filters[i]instanceof WebInspector.TextFilterUI) {
                    var textFilterUI = (this._filters[i]);
                    textFilterUI.focus();
                }
            }
        }
    }, clear: function () {
        this._element.removeChildren();
        this._filters = [];
        this._updateFilterButton();
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.FilterUI = function () {
}
WebInspector.FilterUI.Events = {FilterChanged: "FilterChanged"}
WebInspector.FilterUI.prototype = {
    isActive: function () {
    }, element: function () {
    }
}
WebInspector.TextFilterUI = function (supportRegex) {
    this._supportRegex = !!supportRegex;
    this._regex = null;
    this._filterElement = document.createElement("div");
    this._filterElement.className = "filter-text-filter";
    this._filterInputElement = (this._filterElement.createChild("input", "search-replace toolbar-replace-control"));
    this._filterInputElement.placeholder = WebInspector.UIString("Filter");
    this._filterInputElement.id = "filter-input-field";
    this._filterInputElement.addEventListener("mousedown", this._onFilterFieldManualFocus.bind(this), false);
    this._filterInputElement.addEventListener("input", this._onInput.bind(this), false);
    this._filterInputElement.addEventListener("change", this._onChange.bind(this), false);
    this._filterInputElement.addEventListener("keydown", this._onInputKeyDown.bind(this), true);
    this._filterInputElement.addEventListener("blur", this._onBlur.bind(this), true);
    this._suggestionBuilder = null;
    this._suggestBox = new WebInspector.SuggestBox(this);
    if (this._supportRegex) {
        this._filterElement.classList.add("supports-regex");
        this._regexCheckBox = this._filterElement.createChild("input");
        this._regexCheckBox.type = "checkbox";
        this._regexCheckBox.id = "text-filter-regex";
        this._regexCheckBox.addEventListener("change", this._onInput.bind(this), false);
        this._regexLabel = this._filterElement.createChild("label");
        this._regexLabel.htmlFor = "text-filter-regex";
        this._regexLabel.textContent = WebInspector.UIString("Regex");
    }
}
WebInspector.TextFilterUI.prototype = {
    isActive: function () {
        return !!this._filterInputElement.value;
    }, element: function () {
        return this._filterElement;
    }, value: function () {
        return this._filterInputElement.value;
    }, setValue: function (value) {
        this._filterInputElement.value = value;
        this._valueChanged(false);
    }, regex: function () {
        return this._regex;
    }, _onFilterFieldManualFocus: function (event) {
        WebInspector.setCurrentFocusElement(event.target);
    }, _onBlur: function (event) {
        this._cancelSuggestion();
    }, _cancelSuggestion: function () {
        if (this._suggestionBuilder && this._suggestBox.visible) {
            this._suggestionBuilder.unapplySuggestion(this._filterInputElement);
            this._suggestBox.hide();
        }
    }, _onInput: function () {
        this._valueChanged(true);
    }, _onChange: function () {
        this._valueChanged(false);
    }, focus: function () {
        this._filterInputElement.focus();
    }, setSuggestionBuilder: function (suggestionBuilder) {
        this._cancelSuggestion();
        this._suggestionBuilder = suggestionBuilder;
    }, _updateSuggestions: function () {
        if (!this._suggestionBuilder)
            return;
        var suggestions = this._suggestionBuilder.buildSuggestions(this._filterInputElement);
        if (suggestions && suggestions.length) {
            if (this._suppressSuggestion)
                delete this._suppressSuggestion; else
                this._suggestionBuilder.applySuggestion(this._filterInputElement, suggestions[0], true);
            var anchorBox = this._filterInputElement.boxInWindow().relativeTo(new AnchorBox(-3, 0));
            this._suggestBox.updateSuggestions(anchorBox, suggestions, 0, true, "");
        } else {
            this._suggestBox.hide();
        }
    }, _valueChanged: function (showSuggestions) {
        if (showSuggestions)
            this._updateSuggestions(); else
            this._suggestBox.hide();
        var filterQuery = this.value();
        this._regex = null;
        this._filterInputElement.classList.remove("filter-text-invalid");
        if (filterQuery) {
            if (this._supportRegex && this._regexCheckBox.checked) {
                try {
                    this._regex = new RegExp(filterQuery, "i");
                } catch (e) {
                    this._filterInputElement.classList.add("filter-text-invalid");
                }
            } else {
                this._regex = createPlainTextSearchRegex(filterQuery, "i");
            }
        }
        this._dispatchFilterChanged();
    }, _dispatchFilterChanged: function () {
        this.dispatchEventToListeners(WebInspector.FilterUI.Events.FilterChanged, null);
    }, _onInputKeyDown: function (event) {
        var handled = false;
        if (event.keyIdentifier === "U+0008") {
            this._suppressSuggestion = true;
        } else if (this._suggestBox.visible()) {
            if (event.keyIdentifier === "U+001B") {
                this._cancelSuggestion();
                handled = true;
            } else if (event.keyIdentifier === "U+0009") {
                this._suggestBox.acceptSuggestion();
                this._valueChanged(true);
                handled = true;
            } else {
                handled = this._suggestBox.keyPressed((event));
            }
        }
        if (handled)
            event.consume(true);
        return handled;
    }, applySuggestion: function (suggestion, isIntermediateSuggestion) {
        if (!this._suggestionBuilder)
            return;
        this._suggestionBuilder.applySuggestion(this._filterInputElement, suggestion, !!isIntermediateSuggestion);
        if (isIntermediateSuggestion)
            this._dispatchFilterChanged();
    }, acceptSuggestion: function () {
        this._filterInputElement.scrollLeft = this._filterInputElement.scrollWidth;
        this._valueChanged(true);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.TextFilterUI.SuggestionBuilder = function () {
}
WebInspector.TextFilterUI.SuggestionBuilder.prototype = {
    buildSuggestions: function (input) {
    }, applySuggestion: function (input, suggestion, isIntermediate) {
    }, unapplySuggestion: function (input) {
    }
}
WebInspector.NamedBitSetFilterUI = function (items, setting) {
    this._filtersElement = document.createElement("div");
    this._filtersElement.className = "filter-bitset-filter status-bar-item";
    this._filtersElement.title = WebInspector.UIString("Use %s Click to select multiple types.", WebInspector.KeyboardShortcut.shortcutToString("", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta));
    this._allowedTypes = {};
    this._typeFilterElements = {};
    this._addBit(WebInspector.NamedBitSetFilterUI.ALL_TYPES, WebInspector.UIString("All"));
    this._filtersElement.createChild("div", "filter-bitset-filter-divider");
    for (var i = 0; i < items.length; ++i)
        this._addBit(items[i].name, items[i].label);
    if (setting) {
        this._setting = setting;
        setting.addChangeListener(this._settingChanged.bind(this));
        this._settingChanged();
    } else {
        this._toggleTypeFilter(WebInspector.NamedBitSetFilterUI.ALL_TYPES, false);
    }
}
WebInspector.NamedBitSetFilterUI.Item;
WebInspector.NamedBitSetFilterUI.ALL_TYPES = "all";
WebInspector.NamedBitSetFilterUI.prototype = {
    isActive: function () {
        return !this._allowedTypes[WebInspector.NamedBitSetFilterUI.ALL_TYPES];
    }, element: function () {
        return this._filtersElement;
    }, accept: function (typeName) {
        return !!this._allowedTypes[WebInspector.NamedBitSetFilterUI.ALL_TYPES] || !!this._allowedTypes[typeName];
    }, _settingChanged: function () {
        var allowedTypes = this._setting.get();
        this._allowedTypes = {};
        for (var typeName in this._typeFilterElements) {
            if (allowedTypes[typeName])
                this._allowedTypes[typeName] = true;
        }
        this._update();
    }, _update: function () {
        if ((Object.keys(this._allowedTypes).length === 0) || this._allowedTypes[WebInspector.NamedBitSetFilterUI.ALL_TYPES]) {
            this._allowedTypes = {};
            this._allowedTypes[WebInspector.NamedBitSetFilterUI.ALL_TYPES] = true;
        }
        for (var typeName in this._typeFilterElements)
            this._typeFilterElements[typeName].classList.toggle("selected", this._allowedTypes[typeName]);
        this.dispatchEventToListeners(WebInspector.FilterUI.Events.FilterChanged, null);
    }, _addBit: function (name, label) {
        var typeFilterElement = this._filtersElement.createChild("li", name);
        typeFilterElement.typeName = name;
        typeFilterElement.createTextChild(label);
        typeFilterElement.addEventListener("click", this._onTypeFilterClicked.bind(this), false);
        this._typeFilterElements[name] = typeFilterElement;
    }, _onTypeFilterClicked: function (e) {
        var toggle;
        if (WebInspector.isMac())
            toggle = e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey; else
            toggle = e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey;
        this._toggleTypeFilter(e.target.typeName, toggle);
    }, _toggleTypeFilter: function (typeName, allowMultiSelect) {
        if (allowMultiSelect && typeName !== WebInspector.NamedBitSetFilterUI.ALL_TYPES)
            this._allowedTypes[WebInspector.NamedBitSetFilterUI.ALL_TYPES] = false; else
            this._allowedTypes = {};
        this._allowedTypes[typeName] = !this._allowedTypes[typeName];
        if (this._setting)
            this._setting.set(this._allowedTypes); else
            this._update();
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.ComboBoxFilterUI = function (options) {
    this._filterElement = document.createElement("div");
    this._filterElement.className = "filter-combobox-filter";
    this._options = options;
    this._filterComboBox = new WebInspector.StatusBarComboBox(this._filterChanged.bind(this));
    for (var i = 0; i < options.length; ++i) {
        var filterOption = options[i];
        var option = document.createElement("option");
        option.text = filterOption.label;
        option.title = filterOption.title;
        this._filterComboBox.addOption(option);
        this._filterComboBox.element.title = this._filterComboBox.selectedOption().title;
    }
    this._filterElement.appendChild(this._filterComboBox.element);
}
WebInspector.ComboBoxFilterUI.prototype = {
    isActive: function () {
        return this._filterComboBox.selectedIndex() !== 0;
    }, element: function () {
        return this._filterElement;
    }, value: function (typeName) {
        var option = this._options[this._filterComboBox.selectedIndex()];
        return option.value;
    }, setSelectedIndex: function (index) {
        this._filterComboBox.setSelectedIndex(index);
    }, selectedIndex: function (index) {
        return this._filterComboBox.selectedIndex();
    }, _filterChanged: function (event) {
        var option = this._options[this._filterComboBox.selectedIndex()];
        this._filterComboBox.element.title = option.title;
        this.dispatchEventToListeners(WebInspector.FilterUI.Events.FilterChanged, null);
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.CheckboxFilterUI = function (className, title, activeWhenChecked, setting) {
    this._filterElement = document.createElement("div");
    this._filterElement.classList.add("filter-checkbox-filter", "filter-checkbox-filter-" + className);
    this._activeWhenChecked = !!activeWhenChecked;
    this._createCheckbox(title);
    if (setting) {
        this._setting = setting;
        setting.addChangeListener(this._settingChanged.bind(this));
        this._settingChanged();
    } else {
        this._checked = !this._activeWhenChecked;
        this._update();
    }
}
WebInspector.CheckboxFilterUI.prototype = {
    isActive: function () {
        return this._activeWhenChecked === this._checked;
    }, element: function () {
        return this._filterElement;
    }, checked: function () {
        return this._checked;
    }, setState: function (state) {
        this._checked = state;
        this._update();
    }, _update: function () {
        this._checkElement.classList.toggle("checkbox-filter-checkbox-checked", this._checked);
        this.dispatchEventToListeners(WebInspector.FilterUI.Events.FilterChanged, null);
    }, _settingChanged: function () {
        this._checked = this._setting.get();
        this._update();
    }, _onClick: function (event) {
        this._checked = !this._checked;
        if (this._setting)
            this._setting.set(this._checked); else
            this._update();
    }, _createCheckbox: function (title) {
        var label = this._filterElement.createChild("label");
        var checkBorder = label.createChild("div", "checkbox-filter-checkbox");
        this._checkElement = checkBorder.createChild("div", "checkbox-filter-checkbox-check");
        this._filterElement.addEventListener("click", this._onClick.bind(this), false);
        var typeElement = label.createChild("span", "type");
        typeElement.textContent = title;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.FilterSuggestionBuilder = function (keys) {
    this._keys = keys;
    this._valueSets = {};
    this._valueLists = {};
}
WebInspector.FilterSuggestionBuilder.prototype = {
    buildSuggestions: function (input) {
        var text = input.value;
        var end = input.selectionEnd;
        if (end != text.length)
            return null;
        var start = input.selectionStart;
        text = text.substring(0, start);
        var prefixIndex = text.lastIndexOf(" ") + 1;
        var prefix = text.substring(prefixIndex);
        if (!prefix)
            return [];
        var valueDelimiterIndex = prefix.indexOf(":");
        var suggestions = [];
        if (valueDelimiterIndex === -1) {
            for (var j = 0; j < this._keys.length; ++j) {
                if (this._keys[j].startsWith(prefix))
                    suggestions.push(this._keys[j] + ":");
            }
        } else {
            var key = prefix.substring(0, valueDelimiterIndex);
            var value = prefix.substring(valueDelimiterIndex + 1);
            var items = this._values(key);
            for (var i = 0; i < items.length; ++i) {
                if (items[i].startsWith(value) && (items[i] !== value))
                    suggestions.push(key + ":" + items[i]);
            }
        }
        return suggestions;
    }, applySuggestion: function (input, suggestion, isIntermediate) {
        var text = input.value;
        var start = input.selectionStart;
        text = text.substring(0, start);
        var prefixIndex = text.lastIndexOf(" ") + 1;
        text = text.substring(0, prefixIndex) + suggestion;
        input.value = text;
        if (!isIntermediate)
            start = text.length;
        input.setSelectionRange(start, text.length);
    }, unapplySuggestion: function (input) {
        var start = input.selectionStart;
        var end = input.selectionEnd;
        var text = input.value;
        if (start !== end && end === text.length)
            input.value = text.substring(0, start);
    }, _values: function (key) {
        var result = this._valueLists[key];
        if (!result)
            return [];
        result.sort();
        return result;
    }, addItem: function (key, value) {
        if (!value)
            return;
        var set = this._valueSets[key];
        var list = this._valueLists[key];
        if (!set) {
            set = {};
            this._valueSets[key] = set;
            list = [];
            this._valueLists[key] = list;
        }
        if (set[value])
            return;
        set[value] = true;
        list.push(value);
    }, parseQuery: function (query) {
        var filters = {};
        var text = [];
        var i = 0;
        var j = 0;
        var part;
        while (true) {
            var colonIndex = query.indexOf(":", i);
            if (colonIndex == -1) {
                part = query.substring(j);
                if (part)
                    text.push(part);
                break;
            }
            var spaceIndex = query.lastIndexOf(" ", colonIndex);
            var key = query.substring(spaceIndex + 1, colonIndex);
            if (this._keys.indexOf(key) == -1) {
                i = colonIndex + 1;
                continue;
            }
            part = spaceIndex > j ? query.substring(j, spaceIndex) : "";
            if (part)
                text.push(part);
            var nextSpace = query.indexOf(" ", colonIndex + 1);
            if (nextSpace == -1) {
                filters[key] = query.substring(colonIndex + 1);
                break;
            }
            filters[key] = query.substring(colonIndex + 1, nextSpace);
            i = nextSpace + 1;
            j = i;
        }
        return {text: text, filters: filters};
    }
};
WebInspector.InspectElementModeController = function () {
    this._toggleSearchButton = new WebInspector.StatusBarButton(WebInspector.UIString("Select an element in the page to inspect it."), "node-search-status-bar-item");
    this._shortcut = WebInspector.InspectElementModeController.createShortcut();
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EnterInspectElementMode, this._toggleSearch, this);
}
WebInspector.InspectElementModeController.createShortcut = function () {
    return WebInspector.KeyboardShortcut.makeDescriptor("c", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta | WebInspector.KeyboardShortcut.Modifiers.Shift);
}
WebInspector.InspectElementModeController.prototype = {
    enabled: function () {
        return this._toggleSearchButton.toggled;
    }, disable: function () {
        if (this.enabled())
            this._toggleSearch();
    }, _toggleSearch: function () {
        var enabled = !this.enabled();
        this._toggleSearchButton.toggled = enabled;
        var targets = WebInspector.targetManager.targets();
        for (var i = 0; i < targets.length; ++i)
            targets[i].domModel.setInspectModeEnabled(enabled, WebInspector.settings.showUAShadowDOM.get());
    }
}
WebInspector.InspectElementModeController.ToggleSearchActionDelegate = function () {
}
WebInspector.InspectElementModeController.ToggleSearchActionDelegate.prototype = {
    handleAction: function () {
        if (!WebInspector.inspectElementModeController)
            return false;
        WebInspector.inspectElementModeController._toggleSearch();
        return true;
    }
}
WebInspector.InspectElementModeController.ToggleButtonProvider = function () {
}
WebInspector.InspectElementModeController.ToggleButtonProvider.prototype = {
    item: function () {
        if (!WebInspector.inspectElementModeController)
            return null;
        return WebInspector.inspectElementModeController._toggleSearchButton;
    }
}
WebInspector.inspectElementModeController = null;
WebInspector.WorkerManager = function (target, isMainFrontend) {
    this._reset();
    target.registerWorkerDispatcher(new WebInspector.WorkerDispatcher(this));
    if (isMainFrontend) {
        target.workerAgent().enable();
        target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this);
    }
}
WebInspector.WorkerManager.Events = {
    WorkerAdded: "WorkerAdded",
    WorkerRemoved: "WorkerRemoved",
    WorkersCleared: "WorkersCleared",
    WorkerSelectionChanged: "WorkerSelectionChanged",
    WorkerDisconnected: "WorkerDisconnected",
    MessageFromWorker: "MessageFromWorker",
}
WebInspector.WorkerManager.MainThreadId = 0;
WebInspector.WorkerManager.prototype = {
    _reset: function () {
        this._threadUrlByThreadId = {};
        this._threadUrlByThreadId[WebInspector.WorkerManager.MainThreadId] = WebInspector.UIString("Thread: Main");
        this._threadsList = [WebInspector.WorkerManager.MainThreadId];
        this._selectedThreadId = WebInspector.WorkerManager.MainThreadId;
    }, _workerCreated: function (workerId, url, inspectorConnected) {
        this._threadsList.push(workerId);
        this._threadUrlByThreadId[workerId] = url;
        this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkerAdded, {workerId: workerId, url: url, inspectorConnected: inspectorConnected});
    }, _workerTerminated: function (workerId) {
        this._threadsList.remove(workerId);
        delete this._threadUrlByThreadId[workerId];
        this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkerRemoved, workerId);
    }, _dispatchMessageFromWorker: function (workerId, message) {
        this.dispatchEventToListeners(WebInspector.WorkerManager.Events.MessageFromWorker, {workerId: workerId, message: message})
    }, _disconnectedFromWorker: function () {
        this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkerDisconnected)
    }, _mainFrameNavigated: function (event) {
        this._reset();
        this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkersCleared);
    }, threadsList: function () {
        return this._threadsList;
    }, threadUrl: function (threadId) {
        return this._threadUrlByThreadId[threadId];
    }, setSelectedThreadId: function (threadId) {
        this._selectedThreadId = threadId;
    }, selectedThreadId: function () {
        return this._selectedThreadId;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.WorkerDispatcher = function (workerManager) {
    this._workerManager = workerManager;
}
WebInspector.WorkerDispatcher.prototype = {
    workerCreated: function (workerId, url, inspectorConnected) {
        this._workerManager._workerCreated(workerId, url, inspectorConnected);
    }, workerTerminated: function (workerId) {
        this._workerManager._workerTerminated(workerId);
    }, dispatchMessageFromWorker: function (workerId, message) {
        this._workerManager._dispatchMessageFromWorker(workerId, message);
    }, disconnectedFromWorker: function () {
        this._workerManager._disconnectedFromWorker();
    }
}
WebInspector.workerManager;
WebInspector.ExternalWorkerConnection = function (workerId) {
    InspectorBackendClass.Connection.call(this);
    this._workerId = workerId;
    window.addEventListener("message", this._processMessage.bind(this), true);
}
WebInspector.ExternalWorkerConnection.prototype = {
    _processMessage: function (event) {
        if (!event)
            return;
        var message = event.data;
        this.dispatch(message);
    }, sendMessage: function (messageObject) {
        window.opener.postMessage({workerId: this._workerId, command: "sendMessageToBackend", message: messageObject}, "*");
    }, __proto__: InspectorBackendClass.Connection.prototype
}
WebInspector.WorkerFrontendManager = function () {
    this._workerIdToWindow = {};
    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerAdded, this._workerAdded, this);
    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerRemoved, this._workerRemoved, this);
    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkersCleared, this._workersCleared, this);
    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.MessageFromWorker, this._sendMessageToWorkerInspector, this);
    window.addEventListener("message", this._handleMessage.bind(this), true);
}
WebInspector.WorkerFrontendManager.prototype = {
    _workerAdded: function (event) {
        var data = (event.data);
        if (data.inspectorConnected)
            this._openInspectorWindow(data.workerId, true);
    }, _workerRemoved: function (event) {
        var data = (event.data);
        this.closeWorkerInspector(data.workerId);
    }, _workersCleared: function () {
        for (var workerId in this._workerIdToWindow)
            this.closeWorkerInspector(workerId);
    }, _handleMessage: function (event) {
        var data = (event.data);
        var workerId = data["workerId"];
        workerId = parseInt(workerId, 10);
        var command = data.command;
        var message = data.message;
        if (command == "sendMessageToBackend")
            WorkerAgent.sendMessageToWorker(workerId, message);
    }, _sendMessageToWorkerInspector: function (event) {
        var data = (event.data);
        var workerInspectorWindow = this._workerIdToWindow[data.workerId];
        if (workerInspectorWindow)
            workerInspectorWindow.postMessage(data.message, "*");
    }, openWorkerInspector: function (workerId) {
        var existingInspector = this._workerIdToWindow[workerId];
        if (existingInspector) {
            existingInspector.focus();
            return;
        }
        this._openInspectorWindow(workerId, false);
        WorkerAgent.connectToWorker(workerId);
    }, _openInspectorWindow: function (workerId, workerIsPaused) {
        var search = window.location.search;
        var hash = window.location.hash;
        var url = window.location.href;
        url = url.replace(hash, "");
        url += (search ? "&dedicatedWorkerId=" : "?dedicatedWorkerId=") + workerId;
        if (workerIsPaused)
            url += "&workerPaused=true";
        url = url.replace("docked=true&", "");
        url = url.replace("can_dock=true&", "");
        url += hash;
        var width = WebInspector.settings.workerInspectorWidth.get();
        var height = WebInspector.settings.workerInspectorHeight.get();
        var workerInspectorWindow = window.open(url, undefined, "location=0,width=" + width + ",height=" + height);
        workerInspectorWindow.addEventListener("resize", this._onWorkerInspectorResize.bind(this, workerInspectorWindow), false);
        this._workerIdToWindow[workerId] = workerInspectorWindow;
        workerInspectorWindow.addEventListener("beforeunload", this._workerInspectorClosing.bind(this, workerId), true);
        window.addEventListener("unload", this._pageInspectorClosing.bind(this), true);
    }, closeWorkerInspector: function (workerId) {
        var workerInspectorWindow = this._workerIdToWindow[workerId];
        if (workerInspectorWindow)
            workerInspectorWindow.close();
    }, _onWorkerInspectorResize: function (workerInspectorWindow) {
        var doc = workerInspectorWindow.document;
        WebInspector.settings.workerInspectorWidth.set(doc.width);
        WebInspector.settings.workerInspectorHeight.set(doc.height);
    }, _workerInspectorClosing: function (workerId, event) {
        if (event.target.location.href === "about:blank")
            return;
        if (this._ignoreWorkerInspectorClosing)
            return;
        delete this._workerIdToWindow[workerId];
        WorkerAgent.disconnectFromWorker(workerId);
    }, _pageInspectorClosing: function () {
        this._ignoreWorkerInspectorClosing = true;
        for (var workerId in this._workerIdToWindow) {
            this._workerIdToWindow[workerId].close();
            WorkerAgent.disconnectFromWorker(parseInt(workerId, 10));
        }
    }
}
WebInspector.workerFrontendManager = null;
WebInspector.WorkerTargetManager = function (mainTarget, targetManager) {
    this._mainTarget = mainTarget;
    this._targetManager = targetManager;
    mainTarget.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerAdded, this._onWorkerAdded, this);
    mainTarget.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkersCleared, this._onWorkersCleared, this);
    WebInspector.profilingLock().addEventListener(WebInspector.Lock.Events.StateChanged, this._onProfilingStateChanged, this);
    this._onProfilingStateChanged();
    this._lastAnonymousTargetId = 0;
}
WebInspector.WorkerTargetManager.prototype = {
    _onProfilingStateChanged: function () {
        var acquired = WebInspector.profilingLock().isAcquired();
        this._mainTarget.workerAgent().setAutoconnectToWorkers(!acquired);
    }, _onWorkerAdded: function (event) {
        var data = (event.data);
        new WebInspector.WorkerConnection(this._mainTarget, data.workerId, data.inspectorConnected, onConnectionReady.bind(this));
        function onConnectionReady(connection) {
            var parsedURL = data.url.asParsedURL();
            var workerId = parsedURL ? parsedURL.lastPathComponent : "#" + (++this._lastAnonymousTargetId);
            this._targetManager.createTarget(WebInspector.UIString("Worker %s", workerId), connection, targetCreated);
        }

        function targetCreated(target) {
            if (data.inspectorConnected)
                target.runtimeAgent().run();
        }
    }, _onWorkersCleared: function () {
        this._lastAnonymousTargetId = 0;
    }
}
WebInspector.WorkerConnection = function (target, workerId, inspectorConnected, onConnectionReady) {
    InspectorBackendClass.Connection.call(this);
    this.suppressErrorsForDomains(["Worker", "Page", "CSS", "DOM", "DOMStorage", "Database", "Network"]);
    this._target = target;
    this._workerId = workerId;
    this._workerAgent = target.workerAgent();
    target.workerManager.addEventListener(WebInspector.WorkerManager.Events.MessageFromWorker, this._dispatchMessageFromWorker, this);
    target.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerRemoved, this._onWorkerRemoved, this);
    target.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkersCleared, this._close, this);
    if (!inspectorConnected)
        this._workerAgent.connectToWorker(workerId, onConnectionReady.bind(null, this)); else
        onConnectionReady.call(null, this);
}
WebInspector.WorkerConnection.prototype = {
    _dispatchMessageFromWorker: function (event) {
        var data = (event.data);
        if (data.workerId === this._workerId)
            this.dispatch(data.message);
    }, sendMessage: function (messageObject) {
        this._workerAgent.sendMessageToWorker(this._workerId, messageObject);
    }, _onWorkerRemoved: function (event) {
        var workerId = (event.data);
        if (workerId === this._workerId)
            this._close();
    }, _close: function () {
        this._target.workerManager.removeEventListener(WebInspector.WorkerManager.Events.MessageFromWorker, this._dispatchMessageFromWorker, this);
        this._target.workerManager.removeEventListener(WebInspector.WorkerManager.Events.WorkerRemoved, this._onWorkerRemoved, this);
        this._target.workerManager.removeEventListener(WebInspector.WorkerManager.Events.WorkersCleared, this._close, this);
        this.connectionClosed("worker_terminated");
    }, __proto__: InspectorBackendClass.Connection.prototype
}
WebInspector.RuntimeModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.RuntimeModel, target);
    this._debuggerModel = target.debuggerModel;
    this._agent = target.runtimeAgent();
    this.target().registerRuntimeDispatcher(new WebInspector.RuntimeDispatcher(this));
    this._agent.enable();
    this._executionContextById = {};
}
WebInspector.RuntimeModel.Events = {ExecutionContextCreated: "ExecutionContextCreated", ExecutionContextDestroyed: "ExecutionContextDestroyed",}
WebInspector.RuntimeModel.prototype = {
    executionContexts: function () {
        return Object.values(this._executionContextById);
    }, _executionContextCreated: function (context) {
        var executionContext = new WebInspector.ExecutionContext(this.target(), context.id, context.name, context.isPageContext, context.frameId);
        this._executionContextById[executionContext.id] = executionContext;
        this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.ExecutionContextCreated, executionContext);
    }, _executionContextDestroyed: function (executionContextId) {
        var executionContext = this._executionContextById[executionContextId];
        delete this._executionContextById[executionContextId];
        this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.ExecutionContextDestroyed, executionContext);
    }, _executionContextsCleared: function () {
        var contexts = this.executionContexts();
        this._executionContextById = {};
        for (var i = 0; i < contexts.length; ++i)
            this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.ExecutionContextDestroyed, contexts[i]);
    }, createRemoteObject: function (payload) {
        console.assert(typeof payload === "object", "Remote object payload should only be an object");
        return new WebInspector.RemoteObjectImpl(this.target(), payload.objectId, payload.type, payload.subtype, payload.value, payload.description, payload.preview);
    }, createScopeRemoteObject: function (payload, scopeRef) {
        return new WebInspector.ScopeRemoteObject(this.target(), payload.objectId, scopeRef, payload.type, payload.subtype, payload.value, payload.description, payload.preview);
    }, createRemoteObjectFromPrimitiveValue: function (value) {
        return new WebInspector.RemoteObjectImpl(this.target(), undefined, typeof value, undefined, value);
    }, createRemotePropertyFromPrimitiveValue: function (name, value) {
        return new WebInspector.RemoteObjectProperty(name, this.createRemoteObjectFromPrimitiveValue(value));
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.RuntimeDispatcher = function (runtimeModel) {
    this._runtimeModel = runtimeModel;
}
WebInspector.RuntimeDispatcher.prototype = {
    executionContextCreated: function (context) {
        this._runtimeModel._executionContextCreated(context);
    }, executionContextDestroyed: function (executionContextId) {
        this._runtimeModel._executionContextDestroyed(executionContextId);
    }, executionContextsCleared: function () {
        this._runtimeModel._executionContextsCleared();
    }
}
WebInspector.ExecutionContext = function (target, id, name, isPageContext, frameId) {
    WebInspector.SDKObject.call(this, target);
    this.id = id;
    this.name = (isPageContext && !name) ? "<page context>" : name;
    this.isMainWorldContext = isPageContext;
    this._debuggerModel = target.debuggerModel;
    this.frameId = frameId;
}
WebInspector.ExecutionContext.comparator = function (a, b) {
    if (a.isMainWorldContext)
        return -1;
    if (b.isMainWorldContext)
        return +1;
    return a.name.localeCompare(b.name);
}
WebInspector.ExecutionContext.prototype = {
    evaluate: function (expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback) {
        if (this._debuggerModel.selectedCallFrame()) {
            this._debuggerModel.evaluateOnSelectedCallFrame(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback);
            return;
        }
        if (!expression) {
            expression = "this";
        }
        function evalCallback(error, result, wasThrown, exceptionDetails) {
            if (error) {
                callback(null, false);
                return;
            }
            if (returnByValue)
                callback(null, !!wasThrown, wasThrown ? null : result, exceptionDetails); else
                callback(this.target().runtimeModel.createRemoteObject(result), !!wasThrown, undefined, exceptionDetails);
        }

        this.target().runtimeAgent().evaluate(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, this.id, returnByValue, generatePreview, evalCallback.bind(this));
    }, completionsForExpression: function (expressionString, prefix, force, completionsReadyCallback) {
        var lastIndex = expressionString.length - 1;
        var dotNotation = (expressionString[lastIndex] === ".");
        var bracketNotation = (expressionString[lastIndex] === "[");
        if (dotNotation || bracketNotation)
            expressionString = expressionString.substr(0, lastIndex);
        if (expressionString && parseInt(expressionString, 10) == expressionString) {
            completionsReadyCallback([]);
            return;
        }
        if (!prefix && !expressionString && !force) {
            completionsReadyCallback([]);
            return;
        }
        if (!expressionString && this._debuggerModel.selectedCallFrame())
            this._debuggerModel.getSelectedCallFrameVariables(receivedPropertyNames.bind(this)); else
            this.evaluate(expressionString, "completion", true, true, false, false, evaluated.bind(this));
        function evaluated(result, wasThrown) {
            if (!result || wasThrown) {
                completionsReadyCallback([]);
                return;
            }
            function getCompletions(primitiveType) {
                var object;
                if (primitiveType === "string")
                    object = new String(""); else if (primitiveType === "number")
                    object = new Number(0); else if (primitiveType === "boolean")
                    object = new Boolean(false); else
                    object = this;
                var resultSet = {};
                for (var o = object; o; o = o.__proto__) {
                    try {
                        var names = Object.getOwnPropertyNames(o);
                        for (var i = 0; i < names.length; ++i)
                            resultSet[names[i]] = true;
                    } catch (e) {
                    }
                }
                return resultSet;
            }

            if (result.type === "object" || result.type === "function")
                result.callFunctionJSON(getCompletions, undefined, receivedPropertyNames.bind(this)); else if (result.type === "string" || result.type === "number" || result.type === "boolean")
                this.evaluate("(" + getCompletions + ")(\"" + result.type + "\")", "completion", false, true, true, false, receivedPropertyNamesFromEval.bind(this));
        }

        function receivedPropertyNamesFromEval(notRelevant, wasThrown, result) {
            if (result && !wasThrown)
                receivedPropertyNames.call(this, result.value); else
                completionsReadyCallback([]);
        }

        function receivedPropertyNames(propertyNames) {
            this.target().runtimeAgent().releaseObjectGroup("completion");
            if (!propertyNames) {
                completionsReadyCallback([]);
                return;
            }
            var includeCommandLineAPI = (!dotNotation && !bracketNotation);
            if (includeCommandLineAPI) {
                const commandLineAPI = ["dir", "dirxml", "keys", "values", "profile", "profileEnd", "monitorEvents", "unmonitorEvents", "inspect", "copy", "clear", "getEventListeners", "debug", "undebug", "monitor", "unmonitor", "table", "$", "$$", "$x"];
                for (var i = 0; i < commandLineAPI.length; ++i)
                    propertyNames[commandLineAPI[i]] = true;
            }
            this._reportCompletions(completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, Object.keys(propertyNames));
        }
    }, _reportCompletions: function (completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, properties) {
        if (bracketNotation) {
            if (prefix.length && prefix[0] === "'")
                var quoteUsed = "'"; else
                var quoteUsed = "\"";
        }
        var results = [];
        if (!expressionString) {
            const keywords = ["break", "case", "catch", "continue", "default", "delete", "do", "else", "finally", "for", "function", "if", "in", "instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with"];
            properties = properties.concat(keywords);
        }
        properties.sort();
        for (var i = 0; i < properties.length; ++i) {
            var property = properties[i];
            if (dotNotation && !/^[a-zA-Z_$\u008F-\uFFFF][a-zA-Z0-9_$\u008F-\uFFFF]*$/.test(property))
                continue;
            if (bracketNotation) {
                if (!/^[0-9]+$/.test(property))
                    property = quoteUsed + property.escapeCharacters(quoteUsed + "\\") + quoteUsed;
                property += "]";
            }
            if (property.length < prefix.length)
                continue;
            if (prefix.length && !property.startsWith(prefix))
                continue;
            results.push(property);
        }
        completionsReadyCallback(results);
    }, __proto__: WebInspector.SDKObject.prototype
}
WebInspector.runtimeModel;
WebInspector.HandlerRegistry = function (setting) {
    WebInspector.Object.call(this);
    this._handlers = {};
    this._setting = setting;
    this._activeHandler = this._setting.get();
}
WebInspector.HandlerRegistry.prototype = {
    get handlerNames() {
        return Object.getOwnPropertyNames(this._handlers);
    }, get activeHandler() {
        return this._activeHandler;
    }, set activeHandler(value) {
        this._activeHandler = value;
        this._setting.set(value);
    }, dispatch: function (data) {
        return this.dispatchToHandler(this._activeHandler, data);
    }, dispatchToHandler: function (name, data) {
        var handler = this._handlers[name];
        var result = handler && handler(data);
        return !!result;
    }, registerHandler: function (name, handler) {
        this._handlers[name] = handler;
        this.dispatchEventToListeners(WebInspector.HandlerRegistry.EventTypes.HandlersUpdated);
    }, unregisterHandler: function (name) {
        delete this._handlers[name];
        this.dispatchEventToListeners(WebInspector.HandlerRegistry.EventTypes.HandlersUpdated);
    }, _openInNewTab: function (url) {
        InspectorFrontendHost.openInNewTab(url);
    }, _appendContentProviderItems: function (contextMenu, target) {
        if (!(target instanceof WebInspector.UISourceCode || target instanceof WebInspector.Resource || target instanceof WebInspector.NetworkRequest))
            return;
        var contentProvider = (target);
        if (!contentProvider.contentURL())
            return;
        contextMenu.appendItem(WebInspector.openLinkExternallyLabel(), this._openInNewTab.bind(this, contentProvider.contentURL()));
        for (var i = 1; i < this.handlerNames.length; ++i) {
            var handler = this.handlerNames[i];
            contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Open using %s" : "Open Using %s", handler), this.dispatchToHandler.bind(this, handler, {url: contentProvider.contentURL()}));
        }
        contextMenu.appendItem(WebInspector.copyLinkAddressLabel(), InspectorFrontendHost.copyText.bind(InspectorFrontendHost, contentProvider.contentURL()));
        if (!contentProvider.contentURL())
            return;
        var contentType = contentProvider.contentType();
        if (contentType !== WebInspector.resourceTypes.Document && contentType !== WebInspector.resourceTypes.Stylesheet && contentType !== WebInspector.resourceTypes.Script)
            return;
        function doSave(forceSaveAs, content) {
            var url = contentProvider.contentURL();
            WebInspector.fileManager.save(url, (content), forceSaveAs);
            WebInspector.fileManager.close(url);
        }

        function save(forceSaveAs) {
            if (contentProvider instanceof WebInspector.UISourceCode) {
                var uiSourceCode = (contentProvider);
                uiSourceCode.save(forceSaveAs);
                return;
            }
            contentProvider.requestContent(doSave.bind(null, forceSaveAs));
        }

        contextMenu.appendSeparator();
        contextMenu.appendItem(WebInspector.UIString("Save"), save.bind(null, false));
        if (contentProvider instanceof WebInspector.UISourceCode) {
            var uiSourceCode = (contentProvider);
            if (uiSourceCode.project().type() !== WebInspector.projectTypes.FileSystem && uiSourceCode.project().type() !== WebInspector.projectTypes.Snippets)
                contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Save as..." : "Save As..."), save.bind(null, true));
        }
    }, _appendHrefItems: function (contextMenu, target) {
        if (!(target instanceof Node))
            return;
        var targetNode = (target);
        var anchorElement = targetNode.enclosingNodeOrSelfWithClass("webkit-html-resource-link") || targetNode.enclosingNodeOrSelfWithClass("webkit-html-external-link");
        if (!anchorElement)
            return;
        var resourceURL = anchorElement.href;
        if (!resourceURL)
            return;
        contextMenu.appendItem(WebInspector.openLinkExternallyLabel(), this._openInNewTab.bind(this, resourceURL));
        function openInResourcesPanel(resourceURL) {
            var resource = WebInspector.resourceForURL(resourceURL);
            if (resource)
                WebInspector.Revealer.reveal(resource); else
                InspectorFrontendHost.openInNewTab(resourceURL);
        }

        if (WebInspector.resourceForURL(resourceURL))
            contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Open link in Resources panel" : "Open Link in Resources Panel"), openInResourcesPanel.bind(null, resourceURL));
        contextMenu.appendItem(WebInspector.copyLinkAddressLabel(), InspectorFrontendHost.copyText.bind(InspectorFrontendHost, resourceURL));
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.HandlerRegistry.EventTypes = {HandlersUpdated: "HandlersUpdated"}
WebInspector.HandlerSelector = function (handlerRegistry) {
    this._handlerRegistry = handlerRegistry;
    this.element = document.createElementWithClass("select", "chrome-select");
    this.element.addEventListener("change", this._onChange.bind(this), false);
    this._update();
    this._handlerRegistry.addEventListener(WebInspector.HandlerRegistry.EventTypes.HandlersUpdated, this._update.bind(this));
}
WebInspector.HandlerSelector.prototype = {
    _update: function () {
        this.element.removeChildren();
        var names = this._handlerRegistry.handlerNames;
        var activeHandler = this._handlerRegistry.activeHandler;
        for (var i = 0; i < names.length; ++i) {
            var option = document.createElement("option");
            option.textContent = names[i];
            option.selected = activeHandler === names[i];
            this.element.appendChild(option);
        }
        this.element.disabled = names.length <= 1;
    }, _onChange: function (event) {
        var value = event.target.value;
        this._handlerRegistry.activeHandler = value;
    }
}
WebInspector.HandlerRegistry.ContextMenuProvider = function () {
}
WebInspector.HandlerRegistry.ContextMenuProvider.prototype = {
    appendApplicableItems: function (event, contextMenu, target) {
        WebInspector.openAnchorLocationRegistry._appendContentProviderItems(contextMenu, target);
        WebInspector.openAnchorLocationRegistry._appendHrefItems(contextMenu, target);
    }
}
WebInspector.HandlerRegistry.LinkHandler = function () {
}
WebInspector.HandlerRegistry.LinkHandler.prototype = {
    handleLink: function (url, lineNumber) {
        return WebInspector.openAnchorLocationRegistry.dispatch({url: url, lineNumber: lineNumber});
    }
}
WebInspector.HandlerRegistry.OpenAnchorLocationSettingDelegate = function () {
    WebInspector.UISettingDelegate.call(this);
}
WebInspector.HandlerRegistry.OpenAnchorLocationSettingDelegate.prototype = {
    settingElement: function () {
        if (!WebInspector.openAnchorLocationRegistry.handlerNames.length)
            return null;
        var handlerSelector = new WebInspector.HandlerSelector(WebInspector.openAnchorLocationRegistry);
        return WebInspector.SettingsUI.createCustomSetting(WebInspector.UIString("Open links in"), handlerSelector.element);
    }, __proto__: WebInspector.UISettingDelegate.prototype
}
WebInspector.openAnchorLocationRegistry;
WebInspector.SnippetStorage = function (settingPrefix, namePrefix) {
    this._snippets = {};
    this._lastSnippetIdentifierSetting = WebInspector.settings.createSetting(settingPrefix + "Snippets_lastIdentifier", 0);
    this._snippetsSetting = WebInspector.settings.createSetting(settingPrefix + "Snippets", []);
    this._namePrefix = namePrefix;
    this._loadSettings();
}
WebInspector.SnippetStorage.prototype = {
    get namePrefix() {
        return this._namePrefix;
    }, _saveSettings: function () {
        var savedSnippets = [];
        for (var id in this._snippets)
            savedSnippets.push(this._snippets[id].serializeToObject());
        this._snippetsSetting.set(savedSnippets);
    }, snippets: function () {
        var result = [];
        for (var id in this._snippets)
            result.push(this._snippets[id]);
        return result;
    }, snippetForId: function (id) {
        return this._snippets[id];
    }, snippetForName: function (name) {
        var snippets = Object.values(this._snippets);
        for (var i = 0; i < snippets.length; ++i)
            if (snippets[i].name === name)
                return snippets[i];
        return null;
    }, _loadSettings: function () {
        var savedSnippets = this._snippetsSetting.get();
        for (var i = 0; i < savedSnippets.length; ++i)
            this._snippetAdded(WebInspector.Snippet.fromObject(this, savedSnippets[i]));
    }, deleteSnippet: function (snippet) {
        delete this._snippets[snippet.id];
        this._saveSettings();
    }, createSnippet: function () {
        var nextId = this._lastSnippetIdentifierSetting.get() + 1;
        var snippetId = String(nextId);
        this._lastSnippetIdentifierSetting.set(nextId);
        var snippet = new WebInspector.Snippet(this, snippetId);
        this._snippetAdded(snippet);
        this._saveSettings();
        return snippet;
    }, _snippetAdded: function (snippet) {
        this._snippets[snippet.id] = snippet;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.Snippet = function (storage, id, name, content) {
    this._storage = storage;
    this._id = id;
    this._name = name || storage.namePrefix + id;
    this._content = content || "";
}
WebInspector.Snippet.fromObject = function (storage, serializedSnippet) {
    return new WebInspector.Snippet(storage, serializedSnippet.id, serializedSnippet.name, serializedSnippet.content);
}
WebInspector.Snippet.prototype = {
    get id() {
        return this._id;
    }, get name() {
        return this._name;
    }, set name(name) {
        if (this._name === name)
            return;
        this._name = name;
        this._storage._saveSettings();
    }, get content() {
        return this._content;
    }, set content(content) {
        if (this._content === content)
            return;
        this._content = content;
        this._storage._saveSettings();
    }, serializeToObject: function () {
        var serializedSnippet = {};
        serializedSnippet.id = this.id;
        serializedSnippet.name = this.name;
        serializedSnippet.content = this.content;
        return serializedSnippet;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.ScriptSnippetModel = function (workspace) {
    this._workspace = workspace;
    this._uiSourceCodeForSnippetId = {};
    this._snippetIdForUISourceCode = new Map();
    this._mappingForTarget = new Map();
    this._snippetStorage = new WebInspector.SnippetStorage("script", "Script snippet #");
    this._lastSnippetEvaluationIndexSetting = WebInspector.settings.createSetting("lastSnippetEvaluationIndex", 0);
    this._projectId = WebInspector.projectTypes.Snippets + ":";
    this._projectDelegate = new WebInspector.SnippetsProjectDelegate(workspace, this, this._projectId);
    this._project = this._workspace.project(this._projectId);
    this._loadSnippets();
    WebInspector.targetManager.observeTargets(this);
}
WebInspector.ScriptSnippetModel.prototype = {
    targetAdded: function (target) {
        this._mappingForTarget.put(target, new WebInspector.SnippetScriptMapping(target, this));
    }, targetRemoved: function (target) {
        this._mappingForTarget.remove(target);
    }, snippetScriptMapping: function (target) {
        return this._mappingForTarget.get(target);
    }, addScript: function (script) {
        this._mappingForTarget.get(script.target()).addScript(script);
    }, createSnippetScriptMapping: function (target) {
        return new WebInspector.SnippetScriptMapping(target, this);
    }, project: function () {
        return this._project;
    }, _loadSnippets: function () {
        var snippets = this._snippetStorage.snippets();
        for (var i = 0; i < snippets.length; ++i)
            this._addScriptSnippet(snippets[i]);
    }, createScriptSnippet: function (content) {
        var snippet = this._snippetStorage.createSnippet();
        snippet.content = content;
        return this._addScriptSnippet(snippet);
    }, _addScriptSnippet: function (snippet) {
        var path = this._projectDelegate.addSnippet(snippet.name, new WebInspector.SnippetContentProvider(snippet));
        var uiSourceCode = this._workspace.uiSourceCode(this._projectId, path);
        if (!uiSourceCode) {
            console.assert(uiSourceCode);
            return "";
        }
        uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this);
        this._snippetIdForUISourceCode.put(uiSourceCode, snippet.id);
        var breakpointLocations = this._removeBreakpoints(uiSourceCode);
        this._restoreBreakpoints(uiSourceCode, breakpointLocations);
        this._uiSourceCodeForSnippetId[snippet.id] = uiSourceCode;
        return path;
    }, _workingCopyChanged: function (event) {
        var uiSourceCode = (event.target);
        this._scriptSnippetEdited(uiSourceCode);
    }, deleteScriptSnippet: function (path) {
        var uiSourceCode = this._workspace.uiSourceCode(this._projectId, path);
        if (!uiSourceCode)
            return;
        var snippetId = this._snippetIdForUISourceCode.get(uiSourceCode) || "";
        var snippet = this._snippetStorage.snippetForId(snippetId);
        this._snippetStorage.deleteSnippet(snippet);
        this._removeBreakpoints(uiSourceCode);
        this._releaseSnippetScript(uiSourceCode);
        delete this._uiSourceCodeForSnippetId[snippet.id];
        this._snippetIdForUISourceCode.remove(uiSourceCode);
        this._projectDelegate.removeFile(snippet.name);
    }, renameScriptSnippet: function (name, newName, callback) {
        newName = newName.trim();
        if (!newName || newName.indexOf("/") !== -1 || name === newName || this._snippetStorage.snippetForName(newName)) {
            callback(false);
            return;
        }
        var snippet = this._snippetStorage.snippetForName(name);
        console.assert(snippet, "Snippet '" + name + "' was not found.");
        var uiSourceCode = this._uiSourceCodeForSnippetId[snippet.id];
        console.assert(uiSourceCode, "No uiSourceCode was found for snippet '" + name + "'.");
        var breakpointLocations = this._removeBreakpoints(uiSourceCode);
        snippet.name = newName;
        this._restoreBreakpoints(uiSourceCode, breakpointLocations);
        callback(true, newName);
    }, _setScriptSnippetContent: function (name, newContent) {
        var snippet = this._snippetStorage.snippetForName(name);
        snippet.content = newContent;
    }, _scriptSnippetEdited: function (uiSourceCode) {
        var breakpointLocations = this._removeBreakpoints(uiSourceCode);
        this._releaseSnippetScript(uiSourceCode);
        this._restoreBreakpoints(uiSourceCode, breakpointLocations);
        this._mappingForTarget.values().forEach(function (mapping) {
            mapping._restoreBreakpoints(uiSourceCode, breakpointLocations)
        });
    }, _nextEvaluationIndex: function () {
        var evaluationIndex = this._lastSnippetEvaluationIndexSetting.get() + 1;
        this._lastSnippetEvaluationIndexSetting.set(evaluationIndex);
        return evaluationIndex;
    }, evaluateScriptSnippet: function (executionContext, uiSourceCode) {
        var breakpointLocations = this._removeBreakpoints(uiSourceCode);
        this._releaseSnippetScript(uiSourceCode);
        this._restoreBreakpoints(uiSourceCode, breakpointLocations);
        var target = executionContext.target();
        var evaluationIndex = this._nextEvaluationIndex();
        var mapping = this._mappingForTarget.get(target);
        mapping._setEvaluationIndex(evaluationIndex, uiSourceCode);
        var evaluationUrl = mapping._evaluationSourceURL(uiSourceCode);
        var expression = uiSourceCode.workingCopy();
        WebInspector.console.show();
        target.debuggerAgent().compileScript(expression, evaluationUrl, executionContext.id, compileCallback.bind(this, target));
        function compileCallback(target, error, scriptId, exceptionDetails) {
            if (!uiSourceCode || this._mappingForTarget.get(target).evaluationIndex(uiSourceCode) !== evaluationIndex)
                return;
            if (error) {
                console.error(error);
                return;
            }
            if (!scriptId) {
                this._printRunOrCompileScriptResultFailure(target, exceptionDetails, evaluationUrl);
                return;
            }
            var breakpointLocations = this._removeBreakpoints(uiSourceCode);
            this._restoreBreakpoints(uiSourceCode, breakpointLocations);
            this._runScript(scriptId, executionContext, evaluationUrl);
        }
    }, _runScript: function (scriptId, executionContext, sourceURL) {
        var target = executionContext.target();
        target.debuggerAgent().runScript(scriptId, executionContext.id, "console", false, runCallback.bind(this, target));
        function runCallback(target, error, result, exceptionDetails) {
            if (error) {
                console.error(error);
                return;
            }
            if (!exceptionDetails)
                this._printRunScriptResult(target, result, sourceURL); else
                this._printRunOrCompileScriptResultFailure(target, exceptionDetails, sourceURL);
        }
    }, _printRunScriptResult: function (target, result, sourceURL) {
        var consoleMessage = new WebInspector.ConsoleMessage(target, WebInspector.ConsoleMessage.MessageSource.JS, WebInspector.ConsoleMessage.MessageLevel.Log, "", undefined, sourceURL, undefined, undefined, undefined, [result], undefined);
        target.consoleModel.addMessage(consoleMessage);
    }, _printRunOrCompileScriptResultFailure: function (target, exceptionDetails, sourceURL) {
        var consoleMessage = new WebInspector.ConsoleMessage(target, exceptionDetails.source, WebInspector.ConsoleMessage.MessageLevel.Error, exceptionDetails.text, undefined, sourceURL, exceptionDetails.line, exceptionDetails.column, undefined, undefined, exceptionDetails.stackTrace);
        target.consoleModel.addMessage(consoleMessage);
    }, _removeBreakpoints: function (uiSourceCode) {
        var breakpointLocations = WebInspector.breakpointManager.breakpointLocationsForUISourceCode(uiSourceCode);
        for (var i = 0; i < breakpointLocations.length; ++i)
            breakpointLocations[i].breakpoint.remove();
        return breakpointLocations;
    }, _restoreBreakpoints: function (uiSourceCode, breakpointLocations) {
        for (var i = 0; i < breakpointLocations.length; ++i) {
            var uiLocation = breakpointLocations[i].uiLocation;
            var breakpoint = breakpointLocations[i].breakpoint;
            WebInspector.breakpointManager.setBreakpoint(uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber, breakpoint.condition(), breakpoint.enabled());
        }
    }, _releaseSnippetScript: function (uiSourceCode) {
        this._mappingForTarget.values().forEach(function (mapping) {
            mapping._releaseSnippetScript(uiSourceCode)
        });
    }, _snippetIdForSourceURL: function (sourceURL) {
        var snippetPrefix = WebInspector.Script.snippetSourceURLPrefix;
        if (!sourceURL.startsWith(snippetPrefix))
            return null;
        var splitURL = sourceURL.substring(snippetPrefix.length).split("_");
        var snippetId = splitURL[0];
        return snippetId;
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.SnippetScriptMapping = function (target, scriptSnippetModel) {
    this._target = target;
    this._scriptSnippetModel = scriptSnippetModel;
    this._uiSourceCodeForScriptId = {};
    this._scriptForUISourceCode = new Map();
    this._evaluationIndexForUISourceCode = new Map();
    target.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._reset, this);
}
WebInspector.SnippetScriptMapping.prototype = {
    _releaseSnippetScript: function (uiSourceCode) {
        var script = this._scriptForUISourceCode.get(uiSourceCode);
        if (!script)
            return;
        delete this._uiSourceCodeForScriptId[script.scriptId];
        this._scriptForUISourceCode.remove(uiSourceCode);
        this._evaluationIndexForUISourceCode.remove(uiSourceCode);
    }, _setEvaluationIndex: function (evaluationIndex, uiSourceCode) {
        this._evaluationIndexForUISourceCode.put(uiSourceCode, evaluationIndex);
    }, evaluationIndex: function (uiSourceCode) {
        return this._evaluationIndexForUISourceCode.get(uiSourceCode);
    }, _evaluationSourceURL: function (uiSourceCode) {
        var evaluationSuffix = "_" + this._evaluationIndexForUISourceCode.get(uiSourceCode);
        var snippetId = this._scriptSnippetModel._snippetIdForUISourceCode.get(uiSourceCode);
        return WebInspector.Script.snippetSourceURLPrefix + snippetId + evaluationSuffix;
    }, _reset: function () {
        this._uiSourceCodeForScriptId = {};
        this._scriptForUISourceCode.clear();
        this._evaluationIndexForUISourceCode.clear();
    }, rawLocationToUILocation: function (rawLocation) {
        var debuggerModelLocation = (rawLocation);
        var uiSourceCode = this._uiSourceCodeForScriptId[debuggerModelLocation.scriptId];
        if (!uiSourceCode)
            return null;
        return uiSourceCode.uiLocation(debuggerModelLocation.lineNumber, debuggerModelLocation.columnNumber || 0);
    }, uiLocationToRawLocation: function (uiSourceCode, lineNumber, columnNumber) {
        var script = this._scriptForUISourceCode.get(uiSourceCode);
        if (!script)
            return null;
        return this._target.debuggerModel.createRawLocation(script, lineNumber, columnNumber);
    }, snippetIdForSourceURL: function (sourceURL) {
        return this._scriptSnippetModel._snippetIdForSourceURL(sourceURL);
    }, addScript: function (script) {
        var snippetId = this.snippetIdForSourceURL(script.sourceURL);
        if (!snippetId)
            return;
        var uiSourceCode = this._scriptSnippetModel._uiSourceCodeForSnippetId[snippetId];
        if (!uiSourceCode || this._evaluationSourceURL(uiSourceCode) !== script.sourceURL)
            return;
        console.assert(!this._scriptForUISourceCode.get(uiSourceCode));
        WebInspector.debuggerWorkspaceBinding.setSourceMapping(this._target, uiSourceCode, this);
        this._uiSourceCodeForScriptId[script.scriptId] = uiSourceCode;
        this._scriptForUISourceCode.put(uiSourceCode, script);
        WebInspector.debuggerWorkspaceBinding.pushSourceMapping(script, this);
    }, _restoreBreakpoints: function (uiSourceCode, breakpointLocations) {
        var script = this._scriptForUISourceCode.get(uiSourceCode);
        if (!script)
            return;
        var rawLocation = (script.target().debuggerModel.createRawLocation(script, 0, 0));
        var scriptUISourceCode = WebInspector.debuggerWorkspaceBinding.rawLocationToUILocation(rawLocation).uiSourceCode;
        if (scriptUISourceCode)
            this._scriptSnippetModel._restoreBreakpoints(scriptUISourceCode, breakpointLocations);
    }, isIdentity: function () {
        return false;
    }, uiLineHasMapping: function (uiSourceCode, lineNumber) {
        return true;
    }
}
WebInspector.SnippetContentProvider = function (snippet) {
    this._snippet = snippet;
}
WebInspector.SnippetContentProvider.prototype = {
    contentURL: function () {
        return "";
    }, contentType: function () {
        return WebInspector.resourceTypes.Script;
    }, requestContent: function (callback) {
        callback(this._snippet.content);
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        function performSearch() {
            callback(WebInspector.ContentProvider.performSearchInContent(this._snippet.content, query, caseSensitive, isRegex));
        }

        window.setTimeout(performSearch.bind(this), 0);
    }
}
WebInspector.SnippetsProjectDelegate = function (workspace, model, id) {
    WebInspector.ContentProviderBasedProjectDelegate.call(this, workspace, id, WebInspector.projectTypes.Snippets);
    this._model = model;
}
WebInspector.SnippetsProjectDelegate.prototype = {
    addSnippet: function (name, contentProvider) {
        return this.addContentProvider("", name, name, contentProvider);
    }, canSetFileContent: function () {
        return true;
    }, setFileContent: function (path, newContent, callback) {
        this._model._setScriptSnippetContent(path, newContent);
        callback("");
    }, canRename: function () {
        return true;
    }, performRename: function (path, newName, callback) {
        this._model.renameScriptSnippet(path, newName, callback);
    }, createFile: function (path, name, content, callback) {
        var filePath = this._model.createScriptSnippet(content);
        callback(filePath);
    }, deleteFile: function (path) {
        this._model.deleteScriptSnippet(path);
    }, __proto__: WebInspector.ContentProviderBasedProjectDelegate.prototype
}
WebInspector.scriptSnippetModel;
WebInspector.ProgressIndicator = function () {
    this.element = document.createElementWithClass("div", "progress-bar-container");
    this._labelElement = this.element.createChild("span");
    this._progressElement = this.element.createChild("progress");
    this._stopButton = new WebInspector.StatusBarButton(WebInspector.UIString("Cancel"), "progress-bar-stop-button");
    this._stopButton.addEventListener("click", this.cancel, this);
    this.element.appendChild(this._stopButton.element);
    this._isCanceled = false;
    this._worked = 0;
}
WebInspector.ProgressIndicator.prototype = {
    show: function (parent) {
        parent.appendChild(this.element);
    }, hide: function () {
        var parent = this.element.parentElement;
        if (parent)
            parent.removeChild(this.element);
    }, done: function () {
        if (this._isDone)
            return;
        this._isDone = true;
        this.hide();
        this.dispatchEventToListeners(WebInspector.Progress.Events.Done);
    }, cancel: function () {
        this._isCanceled = true;
        this.dispatchEventToListeners(WebInspector.Progress.Events.Canceled);
    }, isCanceled: function () {
        return this._isCanceled;
    }, setTitle: function (title) {
        this._labelElement.textContent = title;
    }, setTotalWork: function (totalWork) {
        this._progressElement.max = totalWork;
    }, setWorked: function (worked, title) {
        this._worked = worked;
        this._progressElement.value = worked;
        if (title)
            this.setTitle(title);
    }, worked: function (worked) {
        this.setWorked(this._worked + (worked || 1));
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.StylesSourceMapping = function (cssModel, workspace) {
    this._cssModel = cssModel;
    this._workspace = workspace;
    this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectRemoved, this._projectRemoved, this);
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAddedToWorkspace, this);
    this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this);
    WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this);
    this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._styleSheetChanged, this);
    this._initialize();
}
WebInspector.StylesSourceMapping.MinorChangeUpdateTimeoutMs = 1000;
WebInspector.StylesSourceMapping.prototype = {
    rawLocationToUILocation: function (rawLocation) {
        var location = (rawLocation);
        var uiSourceCode = this._workspace.uiSourceCodeForURL(location.url);
        if (!uiSourceCode)
            return null;
        return uiSourceCode.uiLocation(location.lineNumber, location.columnNumber);
    }, uiLocationToRawLocation: function (uiSourceCode, lineNumber, columnNumber) {
        return new WebInspector.CSSLocation(this._cssModel.target(), null, uiSourceCode.url || "", lineNumber, columnNumber);
    }, isIdentity: function () {
        return true;
    }, uiLineHasMapping: function (uiSourceCode, lineNumber) {
        return true;
    }, target: function () {
        return this._cssModel.target();
    }, addHeader: function (header) {
        var url = header.resourceURL();
        if (!url)
            return;
        WebInspector.cssWorkspaceBinding.pushSourceMapping(header, this);
        var map = this._urlToHeadersByFrameId[url];
        if (!map) {
            map = (new StringMap());
            this._urlToHeadersByFrameId[url] = map;
        }
        var headersById = map.get(header.frameId);
        if (!headersById) {
            headersById = (new StringMap());
            map.put(header.frameId, headersById);
        }
        headersById.put(header.id, header);
        var uiSourceCode = this._workspace.uiSourceCodeForURL(url);
        if (uiSourceCode)
            this._bindUISourceCode(uiSourceCode, header);
    }, removeHeader: function (header) {
        var url = header.resourceURL();
        if (!url)
            return;
        var map = this._urlToHeadersByFrameId[url];
        console.assert(map);
        var headersById = map.get(header.frameId);
        console.assert(headersById);
        headersById.remove(header.id);
        if (!headersById.size()) {
            map.remove(header.frameId);
            if (!map.size()) {
                delete this._urlToHeadersByFrameId[url];
                var uiSourceCode = this._workspace.uiSourceCodeForURL(url);
                if (uiSourceCode)
                    this._unbindUISourceCode(uiSourceCode);
            }
        }
    }, _unbindUISourceCode: function (uiSourceCode) {
        var styleFile = this._styleFiles.get(uiSourceCode);
        if (!styleFile)
            return;
        styleFile.dispose();
        this._styleFiles.remove(uiSourceCode);
    }, _uiSourceCodeAddedToWorkspace: function (event) {
        var uiSourceCode = (event.data);
        var url = uiSourceCode.url;
        if (!url || !this._urlToHeadersByFrameId[url])
            return;
        this._bindUISourceCode(uiSourceCode, this._urlToHeadersByFrameId[url].values()[0].values()[0]);
    }, _bindUISourceCode: function (uiSourceCode, header) {
        if (this._styleFiles.get(uiSourceCode) || header.isInline)
            return;
        var url = uiSourceCode.url;
        this._styleFiles.put(uiSourceCode, new WebInspector.StyleFile(uiSourceCode, this));
        WebInspector.cssWorkspaceBinding.updateLocations(header);
    }, _projectRemoved: function (event) {
        var project = (event.data);
        var uiSourceCodes = project.uiSourceCodes();
        for (var i = 0; i < uiSourceCodes.length; ++i)
            this._unbindUISourceCode(uiSourceCodes[i]);
    }, _uiSourceCodeRemoved: function (event) {
        var uiSourceCode = (event.data);
        this._unbindUISourceCode(uiSourceCode);
    }, _initialize: function () {
        this._urlToHeadersByFrameId = {};
        this._styleFiles = new Map();
    }, _mainFrameNavigated: function (event) {
        for (var url in this._urlToHeadersByFrameId) {
            var uiSourceCode = this._workspace.uiSourceCodeForURL(url);
            if (!uiSourceCode)
                continue;
            this._unbindUISourceCode(uiSourceCode);
        }
        this._initialize();
    }, _setStyleContent: function (uiSourceCode, content, majorChange, userCallback) {
        var styleSheetIds = this._cssModel.styleSheetIdsForURL(uiSourceCode.url);
        if (!styleSheetIds.length) {
            userCallback("No stylesheet found: " + uiSourceCode.url);
            return;
        }
        this._isSettingContent = true;
        function callback(error) {
            userCallback(error);
            delete this._isSettingContent;
        }

        this._cssModel.setStyleSheetText(styleSheetIds[0], content, majorChange, callback.bind(this));
    }, _styleSheetChanged: function (event) {
        if (this._isSettingContent)
            return;
        if (event.data.majorChange) {
            this._updateStyleSheetText(event.data.styleSheetId);
            return;
        }
        this._updateStyleSheetTextSoon(event.data.styleSheetId);
    }, _updateStyleSheetTextSoon: function (styleSheetId) {
        if (this._updateStyleSheetTextTimer)
            clearTimeout(this._updateStyleSheetTextTimer);
        this._updateStyleSheetTextTimer = setTimeout(this._updateStyleSheetText.bind(this, styleSheetId), WebInspector.StylesSourceMapping.MinorChangeUpdateTimeoutMs);
    }, _updateStyleSheetText: function (styleSheetId) {
        if (this._updateStyleSheetTextTimer) {
            clearTimeout(this._updateStyleSheetTextTimer);
            delete this._updateStyleSheetTextTimer;
        }
        var header = this._cssModel.styleSheetHeaderForId(styleSheetId);
        if (!header)
            return;
        var styleSheetURL = header.resourceURL();
        if (!styleSheetURL)
            return;
        var uiSourceCode = this._workspace.uiSourceCodeForURL(styleSheetURL)
        if (!uiSourceCode)
            return;
        header.requestContent(callback.bind(this, uiSourceCode));
        function callback(uiSourceCode, content) {
            var styleFile = this._styleFiles.get(uiSourceCode);
            if (styleFile)
                styleFile.addRevision(content || "");
        }
    }
}
WebInspector.StyleFile = function (uiSourceCode, mapping) {
    this._uiSourceCode = uiSourceCode;
    this._mapping = mapping;
    this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this);
    this._uiSourceCode.addEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this);
    this._commitThrottler = new WebInspector.Throttler(WebInspector.StyleFile.updateTimeout);
}
WebInspector.StyleFile.updateTimeout = 200;
WebInspector.StyleFile.prototype = {
    _workingCopyCommitted: function (event) {
        if (this._isAddingRevision)
            return;
        this._isMajorChangePending = true;
        this._commitThrottler.schedule(this._commitIncrementalEdit.bind(this), true);
    }, _workingCopyChanged: function (event) {
        if (this._isAddingRevision)
            return;
        this._commitThrottler.schedule(this._commitIncrementalEdit.bind(this), false);
    }, _commitIncrementalEdit: function (finishCallback) {
        this._mapping._setStyleContent(this._uiSourceCode, this._uiSourceCode.workingCopy(), this._isMajorChangePending, this._styleContentSet.bind(this, finishCallback));
        this._isMajorChangePending = false;
    }, _styleContentSet: function (finishCallback, error) {
        if (error)
            WebInspector.console.error(error);
        finishCallback();
    }, addRevision: function (content) {
        this._isAddingRevision = true;
        this._uiSourceCode.addRevision(content);
        delete this._isAddingRevision;
    }, dispose: function () {
        this._uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this);
        this._uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this);
    }
}
WebInspector.NetworkUISourceCodeProvider = function (networkWorkspaceBinding, workspace) {
    this._networkWorkspaceBinding = networkWorkspaceBinding;
    this._workspace = workspace;
    this._processedURLs = {};
    WebInspector.targetManager.addModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, this._resourceAdded, this);
    WebInspector.targetManager.addModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this);
    WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this);
    WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this);
    WebInspector.targetManager.addModelListener(WebInspector.CSSStyleModel, WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._styleSheetAdded, this);
}
WebInspector.NetworkUISourceCodeProvider.prototype = {
    _populate: function (target) {
        function populateFrame(frame) {
            for (var i = 0; i < frame.childFrames.length; ++i)
                populateFrame.call(this, frame.childFrames[i]);
            var resources = frame.resources();
            for (var i = 0; i < resources.length; ++i)
                this._addFile(resources[i].url, new WebInspector.NetworkUISourceCodeProvider.FallbackResource(resources[i]));
        }

        var mainFrame = target.resourceTreeModel.mainFrame;
        if (mainFrame)
            populateFrame.call(this, mainFrame);
    }, _parsedScriptSource: function (event) {
        var script = (event.data);
        if (!script.sourceURL || script.isInlineScript() || script.isSnippet())
            return;
        if (script.isContentScript() && !script.hasSourceURL) {
            var parsedURL = new WebInspector.ParsedURL(script.sourceURL);
            if (!parsedURL.isValid)
                return;
        }
        this._addFile(script.sourceURL, script, script.isContentScript());
    }, _styleSheetAdded: function (event) {
        var header = (event.data);
        if (header.isInline && header.origin !== "inspector")
            return;
        this._addFile(header.resourceURL(), header, false);
    }, _resourceAdded: function (event) {
        var resource = (event.data);
        this._addFile(resource.url, new WebInspector.NetworkUISourceCodeProvider.FallbackResource(resource));
    }, _mainFrameNavigated: function (event) {
        var resourceTreeModel = (event.target);
        this._reset(resourceTreeModel.target());
    }, _addFile: function (url, contentProvider, isContentScript) {
        if (this._workspace.hasMappingForURL(url))
            return;
        var type = contentProvider.contentType();
        if (type !== WebInspector.resourceTypes.Stylesheet && type !== WebInspector.resourceTypes.Document && type !== WebInspector.resourceTypes.Script)
            return;
        if (this._processedURLs[url])
            return;
        this._processedURLs[url] = true;
        this._networkWorkspaceBinding.addFileForURL(url, contentProvider, isContentScript);
    }, _reset: function (target) {
        this._processedURLs = {};
        this._networkWorkspaceBinding.reset();
        this._populate(target);
    }
}
WebInspector.NetworkUISourceCodeProvider.FallbackResource = function (resource) {
    this._resource = resource;
}
WebInspector.NetworkUISourceCodeProvider.FallbackResource.prototype = {
    contentURL: function () {
        return this._resource.contentURL();
    }, contentType: function () {
        return this._resource.contentType();
    }, requestContent: function (callback) {
        function loadFallbackContent() {
            var scripts = this._resource.target().debuggerModel.scriptsForSourceURL(this._resource.url);
            if (!scripts.length) {
                callback(null);
                return;
            }
            var contentProvider;
            if (this._resource.type === WebInspector.resourceTypes.Document)
                contentProvider = new WebInspector.ConcatenatedScriptsContentProvider(scripts); else if (this._resource.type === WebInspector.resourceTypes.Script)
                contentProvider = scripts[0];
            console.assert(contentProvider, "Resource content request failed. " + this._resource.url);
            contentProvider.requestContent(callback);
        }

        function requestContentLoaded(content) {
            if (content)
                callback(content)
            else
                loadFallbackContent.call(this);
        }

        this._resource.requestContent(requestContentLoaded.bind(this));
    }, searchInContent: function (query, caseSensitive, isRegex, callback) {
        function documentContentLoaded(content) {
            if (content === null) {
                callback([]);
                return;
            }
            var result = WebInspector.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex);
            callback(result);
        }

        if (this.contentType() === WebInspector.resourceTypes.Document) {
            this.requestContent(documentContentLoaded);
            return;
        }
        this._resource.searchInContent(query, caseSensitive, isRegex, callback);
    }
}
WebInspector.networkWorkspaceBinding;
WebInspector.CPUProfileDataModel = function (profile) {
    this.profileHead = profile.head;
    this.samples = profile.samples;
    this.timestamps = profile.timestamps;
    this.profileStartTime = profile.startTime * 1000;
    this.profileEndTime = profile.endTime * 1000;
    this._assignParentsInProfile();
    if (this.samples) {
        this._normalizeTimestamps();
        this._buildIdToNodeMap();
        this._fixMissingSamples();
    }
    this._calculateTimes(profile);
}
WebInspector.CPUProfileDataModel.beautifyFunctionName = function (name) {
    return name || WebInspector.UIString("(anonymous function)");
}
WebInspector.CPUProfileDataModel.prototype = {
    _calculateTimes: function (profile) {
        function totalHitCount(node) {
            var result = node.hitCount;
            for (var i = 0; i < node.children.length; i++)
                result += totalHitCount(node.children[i]);
            return result;
        }

        profile.totalHitCount = totalHitCount(profile.head);
        var duration = this.profileEndTime - this.profileStartTime;
        var samplingInterval = duration / profile.totalHitCount;
        this.samplingInterval = samplingInterval;
        function calculateTimesForNode(node) {
            node.selfTime = node.hitCount * samplingInterval;
            var totalHitCount = node.hitCount;
            for (var i = 0; i < node.children.length; i++)
                totalHitCount += calculateTimesForNode(node.children[i]);
            node.totalTime = totalHitCount * samplingInterval;
            return totalHitCount;
        }

        calculateTimesForNode(profile.head);
    }, _assignParentsInProfile: function () {
        var head = this.profileHead;
        head.parent = null;
        head.depth = -1;
        this.maxDepth = 0;
        var nodesToTraverse = [head];
        while (nodesToTraverse.length) {
            var parent = nodesToTraverse.pop();
            var depth = parent.depth + 1;
            if (depth > this.maxDepth)
                this.maxDepth = depth;
            var children = parent.children;
            var length = children.length;
            for (var i = 0; i < length; ++i) {
                var child = children[i];
                child.parent = parent;
                child.depth = depth;
                if (child.children.length)
                    nodesToTraverse.push(child);
            }
        }
    }, _normalizeTimestamps: function () {
        var timestamps = this.timestamps;
        if (!timestamps) {
            var profileStartTime = this.profileStartTime;
            var interval = (this.profileEndTime - profileStartTime) / this.samples.length;
            timestamps = new Float64Array(this.samples.length + 1);
            for (var i = 0; i < timestamps.length; ++i)
                timestamps[i] = profileStartTime + i * interval;
            this.timestamps = timestamps;
            return;
        }
        for (var i = 0; i < timestamps.length; ++i)
            timestamps[i] /= 1000;
        var averageSample = (timestamps.peekLast() - timestamps[0]) / (timestamps.length - 1);
        this.timestamps.push(timestamps.peekLast() + averageSample);
        this.profileStartTime = timestamps[0];
        this.profileEndTime = timestamps.peekLast();
    }, _buildIdToNodeMap: function () {
        this._idToNode = {};
        var idToNode = this._idToNode;
        var stack = [this.profileHead];
        while (stack.length) {
            var node = stack.pop();
            idToNode[node.id] = node;
            for (var i = 0; i < node.children.length; i++)
                stack.push(node.children[i]);
        }
        var topLevelNodes = this.profileHead.children;
        for (var i = 0; i < topLevelNodes.length && !(this.gcNode && this.programNode && this.idleNode); i++) {
            var node = topLevelNodes[i];
            if (node.functionName === "(garbage collector)")
                this.gcNode = node; else if (node.functionName === "(program)")
                this.programNode = node; else if (node.functionName === "(idle)")
                this.idleNode = node;
        }
    }, _fixMissingSamples: function () {
        var samples = this.samples;
        var samplesCount = samples.length;
        if (!this.programNode || samplesCount < 3)
            return;
        var idToNode = this._idToNode;
        var programNodeId = this.programNode.id;
        var gcNodeId = this.gcNode ? this.gcNode.id : -1;
        var idleNodeId = this.idleNode ? this.idleNode.id : -1;
        var prevNodeId = samples[0];
        var nodeId = samples[1];
        for (var sampleIndex = 1; sampleIndex < samplesCount - 1; sampleIndex++) {
            var nextNodeId = samples[sampleIndex + 1];
            if (nodeId === programNodeId && !isSystemNode(prevNodeId) && !isSystemNode(nextNodeId) && bottomNode(idToNode[prevNodeId]) === bottomNode(idToNode[nextNodeId])) {
                samples[sampleIndex] = prevNodeId;
            }
            prevNodeId = nodeId;
            nodeId = nextNodeId;
        }
        function bottomNode(node) {
            while (node.parent)
                node = node.parent;
            return node;
        }

        function isSystemNode(nodeId) {
            return nodeId === programNodeId || nodeId === gcNodeId || nodeId === idleNodeId;
        }
    }, forEachFrame: function (openFrameCallback, closeFrameCallback, startTime, stopTime) {
        if (!this.profileHead)
            return;
        startTime = startTime || 0;
        stopTime = stopTime || Infinity;
        var samples = this.samples;
        var timestamps = this.timestamps;
        var idToNode = this._idToNode;
        var gcNode = this.gcNode;
        var samplesCount = samples.length;
        var startIndex = timestamps.lowerBound(startTime);
        var stackTop = 0;
        var stackNodes = [];
        var prevId = this.profileHead.id;
        var prevHeight = this.profileHead.depth;
        var sampleTime = timestamps[samplesCount];
        var gcParentNode = null;
        if (!this._stackStartTimes)
            this._stackStartTimes = new Float64Array(this.maxDepth + 2);
        var stackStartTimes = this._stackStartTimes;
        if (!this._stackChildrenDuration)
            this._stackChildrenDuration = new Float64Array(this.maxDepth + 2);
        var stackChildrenDuration = this._stackChildrenDuration;
        for (var sampleIndex = startIndex; sampleIndex < samplesCount; sampleIndex++) {
            sampleTime = timestamps[sampleIndex];
            if (sampleTime >= stopTime)
                break;
            var id = samples[sampleIndex];
            if (id === prevId)
                continue;
            var node = idToNode[id];
            var prevNode = idToNode[prevId];
            if (node === gcNode) {
                gcParentNode = prevNode;
                openFrameCallback(gcParentNode.depth + 1, gcNode, sampleTime);
                stackStartTimes[++stackTop] = sampleTime;
                stackChildrenDuration[stackTop] = 0;
                prevId = id;
                continue;
            }
            if (prevNode === gcNode) {
                var start = stackStartTimes[stackTop];
                var duration = sampleTime - start;
                stackChildrenDuration[stackTop - 1] += duration;
                closeFrameCallback(gcParentNode.depth + 1, gcNode, start, duration, duration - stackChildrenDuration[stackTop]);
                --stackTop;
                prevNode = gcParentNode;
                prevId = prevNode.id;
                gcParentNode = null;
            }
            while (node.depth > prevNode.depth) {
                stackNodes.push(node);
                node = node.parent;
            }
            while (prevNode !== node) {
                var start = stackStartTimes[stackTop];
                var duration = sampleTime - start;
                stackChildrenDuration[stackTop - 1] += duration;
                closeFrameCallback(prevNode.depth, prevNode, start, duration, duration - stackChildrenDuration[stackTop]);
                --stackTop;
                if (node.depth === prevNode.depth) {
                    stackNodes.push(node);
                    node = node.parent;
                }
                prevNode = prevNode.parent;
            }
            while (stackNodes.length) {
                node = stackNodes.pop();
                openFrameCallback(node.depth, node, sampleTime);
                stackStartTimes[++stackTop] = sampleTime;
                stackChildrenDuration[stackTop] = 0;
            }
            prevId = id;
        }
        if (idToNode[prevId] === gcNode) {
            var start = stackStartTimes[stackTop];
            var duration = sampleTime - start;
            stackChildrenDuration[stackTop - 1] += duration;
            closeFrameCallback(gcParentNode.depth + 1, node, start, duration, duration - stackChildrenDuration[stackTop]);
            --stackTop;
        }
        for (var node = idToNode[prevId]; node.parent; node = node.parent) {
            var start = stackStartTimes[stackTop];
            var duration = sampleTime - start;
            stackChildrenDuration[stackTop - 1] += duration;
            closeFrameCallback(node.depth, node, start, duration, duration - stackChildrenDuration[stackTop]);
            --stackTop;
        }
    }, nodeByIndex: function (index) {
        return this._idToNode[this.samples[index]];
    }
}
WebInspector.CPUProfilerModel = function (target) {
    WebInspector.SDKModel.call(this, WebInspector.CPUProfilerModel, target);
    this._isRecording = false;
    target.registerProfilerDispatcher(this);
    target.profilerAgent().enable();
    this._configureCpuProfilerSamplingInterval();
    WebInspector.settings.highResolutionCpuProfiling.addChangeListener(this._configureCpuProfilerSamplingInterval, this);
}
WebInspector.CPUProfilerModel.EventTypes = {ProfileStarted: "ProfileStarted", ProfileStopped: "ProfileStopped", ConsoleProfileStarted: "ConsoleProfileStarted", ConsoleProfileFinished: "ConsoleProfileFinished"};
WebInspector.CPUProfilerModel.prototype = {
    _configureCpuProfilerSamplingInterval: function () {
        var intervalUs = WebInspector.settings.highResolutionCpuProfiling.get() ? 100 : 1000;
        this.target().profilerAgent().setSamplingInterval(intervalUs, didChangeInterval);
        function didChangeInterval(error) {
            if (error)
                WebInspector.console.error(error);
        }
    }, consoleProfileFinished: function (id, scriptLocation, cpuProfile, title) {
        self.runtime.loadModule("profiler");
        var debuggerLocation = WebInspector.DebuggerModel.Location.fromPayload(this.target(), scriptLocation);
        this.dispatchEventToListeners(WebInspector.CPUProfilerModel.EventTypes.ConsoleProfileFinished, {protocolId: id, scriptLocation: debuggerLocation, cpuProfile: cpuProfile, title: title});
    }, consoleProfileStarted: function (id, scriptLocation, title) {
        self.runtime.loadModule("profiler");
        var debuggerLocation = WebInspector.DebuggerModel.Location.fromPayload(this.target(), scriptLocation)
        this.dispatchEventToListeners(WebInspector.CPUProfilerModel.EventTypes.ConsoleProfileStarted, {protocolId: id, scriptLocation: debuggerLocation, title: title});
    }, isRecordingProfile: function () {
        return this._isRecording;
    }, startRecording: function () {
        this._isRecording = true;
        this.target().profilerAgent().start();
        this.dispatchEventToListeners(WebInspector.CPUProfilerModel.EventTypes.ProfileStarted);
        WebInspector.userMetrics.ProfilesCPUProfileTaken.record();
    }, stopRecording: function (callback) {
        this._isRecording = false;
        this.target().profilerAgent().stop(callback);
        this.dispatchEventToListeners(WebInspector.CPUProfilerModel.EventTypes.ProfileStopped);
    }, dispose: function () {
        WebInspector.settings.highResolutionCpuProfiling.removeChangeListener(this._configureCpuProfilerSamplingInterval, this);
    }, __proto__: WebInspector.SDKModel.prototype
}
WebInspector.cpuProfilerModel;
WebInspector.PieChart = function (size, formatter) {
    var shadowSize = WebInspector.PieChart._ShadowSizePercent;
    this.element = document.createElementWithClass("div", "pie-chart");
    var svg = this._createSVGChild(this.element, "svg");
    svg.setAttribute("width", (100 * (1 + 2 * shadowSize)) + "%");
    svg.setAttribute("height", (100 * (1 + 2 * shadowSize)) + "%");
    this._group = this._createSVGChild(svg, "g");
    var shadow = this._createSVGChild(this._group, "circle");
    shadow.setAttribute("r", 1 + shadowSize);
    shadow.setAttribute("cy", shadowSize);
    shadow.setAttribute("fill", "hsl(0,0%,70%)");
    var background = this._createSVGChild(this._group, "circle");
    background.setAttribute("r", 1);
    background.setAttribute("fill", "hsl(0,0%,92%)");
    this._totalElement = this.element.createChild("div", "pie-chart-foreground");
    this._formatter = formatter;
    this._slices = [];
    this._lastAngle = -Math.PI / 2;
    this._setSize(size);
}
WebInspector.PieChart._ShadowSizePercent = 0.02;
WebInspector.PieChart.prototype = {
    setTotal: function (totalValue) {
        for (var i = 0; i < this._slices.length; ++i)
            this._slices[i].remove();
        this._slices = [];
        this._totalValue = totalValue;
        var totalString;
        if (totalValue)
            totalString = this._formatter ? this._formatter(totalValue) : totalValue; else
            totalString = "";
        this._totalElement.textContent = totalString;
    }, _setSize: function (value) {
        this._group.setAttribute("transform", "scale(" + (value / 2) + ") translate(" + (1 + WebInspector.PieChart._ShadowSizePercent) + ",1)");
        var size = value + "px";
        this.element.style.width = size;
        this.element.style.height = size;
        if (this._totalElement)
            this._totalElement.style.lineHeight = size;
    }, addSlice: function (value, color) {
        var sliceAngle = value / this._totalValue * 2 * Math.PI;
        if (!isFinite(sliceAngle))
            return;
        sliceAngle = Math.min(sliceAngle, 2 * Math.PI * 0.9999);
        var path = this._createSVGChild(this._group, "path");
        var x1 = Math.cos(this._lastAngle);
        var y1 = Math.sin(this._lastAngle);
        this._lastAngle += sliceAngle;
        var x2 = Math.cos(this._lastAngle);
        var y2 = Math.sin(this._lastAngle);
        var largeArc = sliceAngle > Math.PI ? 1 : 0;
        path.setAttribute("d", "M0,0 L" + x1 + "," + y1 + " A1,1,0," + largeArc + ",1," + x2 + "," + y2 + " Z");
        path.setAttribute("fill", color);
        this._slices.push(path);
    }, _createSVGChild: function (parent, childType) {
        var child = document.createElementNS("http://www.w3.org/2000/svg", childType);
        parent.appendChild(child);
        return child;
    }
}
WebInspector.FlameChartDelegate = function () {
}
WebInspector.FlameChartDelegate.prototype = {
    requestWindowTimes: function (startTime, endTime) {
    }
}
WebInspector.FlameChart = function (dataProvider, flameChartDelegate, isTopDown) {
    WebInspector.HBox.call(this);
    this.element.classList.add("flame-chart-main-pane");
    this._flameChartDelegate = flameChartDelegate;
    this._isTopDown = isTopDown;
    this._calculator = new WebInspector.FlameChart.Calculator();
    this._canvas = this.element.createChild("canvas");
    this._canvas.tabIndex = 1;
    this.setDefaultFocusedElement(this._canvas);
    this._canvas.addEventListener("mousemove", this._onMouseMove.bind(this), false);
    this._canvas.addEventListener("mousewheel", this._onMouseWheel.bind(this), false);
    this._canvas.addEventListener("click", this._onClick.bind(this), false);
    this._canvas.addEventListener("keydown", this._onKeyDown.bind(this), false);
    WebInspector.installDragHandle(this._canvas, this._startCanvasDragging.bind(this), this._canvasDragging.bind(this), this._endCanvasDragging.bind(this), "move", null);
    this._vScrollElement = this.element.createChild("div", "flame-chart-v-scroll");
    this._vScrollContent = this._vScrollElement.createChild("div");
    this._vScrollElement.addEventListener("scroll", this.scheduleUpdate.bind(this), false);
    this._entryInfo = this.element.createChild("div", "profile-entry-info");
    this._markerHighlighElement = this.element.createChild("div", "flame-chart-marker-highlight-element");
    this._highlightElement = this.element.createChild("div", "flame-chart-highlight-element");
    this._selectedElement = this.element.createChild("div", "flame-chart-selected-element");
    this._dataProvider = dataProvider;
    this._windowLeft = 0.0;
    this._windowRight = 1.0;
    this._windowWidth = 1.0;
    this._timeWindowLeft = 0;
    this._timeWindowRight = Infinity;
    this._barHeight = dataProvider.barHeight();
    this._barHeightDelta = this._isTopDown ? -this._barHeight : this._barHeight;
    this._minWidth = 1;
    this._paddingLeft = this._dataProvider.paddingLeft();
    this._markerPadding = 2;
    this._markerRadius = this._barHeight / 2 - this._markerPadding;
    this._highlightedMarkerIndex = -1;
    this._highlightedEntryIndex = -1;
    this._selectedEntryIndex = -1;
    this._textWidth = {};
}
WebInspector.FlameChart.DividersBarHeight = 20;
WebInspector.FlameChartDataProvider = function () {
}
WebInspector.FlameChart.TimelineData = function (entryLevels, entryTotalTimes, entryStartTimes) {
    this.entryLevels = entryLevels;
    this.entryTotalTimes = entryTotalTimes;
    this.entryStartTimes = entryStartTimes;
    this.markerTimestamps = [];
}
WebInspector.FlameChartDataProvider.prototype = {
    barHeight: function () {
    }, dividerOffsets: function (startTime, endTime) {
    }, markerColor: function (index) {
    }, markerTitle: function (index) {
    }, minimumBoundary: function () {
    }, totalTime: function () {
    }, maxStackDepth: function () {
    }, timelineData: function () {
    }, prepareHighlightedEntryInfo: function (entryIndex) {
    }, canJumpToEntry: function (entryIndex) {
    }, entryTitle: function (entryIndex) {
    }, entryFont: function (entryIndex) {
    }, entryColor: function (entryIndex) {
    }, decorateEntry: function (entryIndex, context, text, barX, barY, barWidth, barHeight, timeToPosition) {
    }, forceDecoration: function (entryIndex) {
    }, textColor: function (entryIndex) {
    }, textBaseline: function () {
    }, textPadding: function () {
    }, highlightTimeRange: function (entryIndex) {
    }, paddingLeft: function () {
    },
}
WebInspector.FlameChart.Events = {EntrySelected: "EntrySelected"}
WebInspector.FlameChart.ColorGenerator = function (hueSpace, satSpace, lightnessSpace) {
    this._hueSpace = hueSpace || {min: 0, max: 360, count: 20};
    this._satSpace = satSpace || 67;
    this._lightnessSpace = lightnessSpace || 80;
    this._colors = {};
}
WebInspector.FlameChart.ColorGenerator.prototype = {
    setColorForID: function (id, color) {
        this._colors[id] = color;
    }, colorForID: function (id) {
        var color = this._colors[id];
        if (!color) {
            color = this._generateColorForID(id);
            this._colors[id] = color;
        }
        return color;
    }, _generateColorForID: function (id) {
        var hash = id.hashCode();
        var h = this._indexToValueInSpace(hash, this._hueSpace);
        var s = this._indexToValueInSpace(hash, this._satSpace);
        var l = this._indexToValueInSpace(hash, this._lightnessSpace);
        return "hsl(" + h + ", " + s + "%, " + l + "%)";
    }, _indexToValueInSpace: function (index, space) {
        if (typeof space === "number")
            return space;
        index %= space.count;
        return space.min + Math.floor(index / space.count * (space.max - space.min));
    }
}
WebInspector.FlameChart.Calculator = function () {
    this._paddingLeft = 0;
}
WebInspector.FlameChart.Calculator.prototype = {
    paddingLeft: function () {
        return this._paddingLeft;
    }, _updateBoundaries: function (mainPane) {
        this._totalTime = mainPane._dataProvider.totalTime();
        this._zeroTime = mainPane._dataProvider.minimumBoundary();
        this._minimumBoundaries = this._zeroTime + mainPane._windowLeft * this._totalTime;
        this._maximumBoundaries = this._zeroTime + mainPane._windowRight * this._totalTime;
        this._paddingLeft = mainPane._paddingLeft;
        this._width = mainPane._canvas.width / window.devicePixelRatio - this._paddingLeft;
        this._timeToPixel = this._width / this.boundarySpan();
    }, computePosition: function (time) {
        return Math.round((time - this._minimumBoundaries) * this._timeToPixel + this._paddingLeft);
    }, formatTime: function (value, precision) {
        return Number.preciseMillisToString(value - this._zeroTime, precision);
    }, maximumBoundary: function () {
        return this._maximumBoundaries;
    }, minimumBoundary: function () {
        return this._minimumBoundaries;
    }, zeroTime: function () {
        return this._zeroTime;
    }, boundarySpan: function () {
        return this._maximumBoundaries - this._minimumBoundaries;
    }
}
WebInspector.FlameChart.prototype = {
    _resetCanvas: function () {
        var ratio = window.devicePixelRatio;
        this._canvas.width = this._offsetWidth * ratio;
        this._canvas.height = this._offsetHeight * ratio;
        this._canvas.style.width = this._offsetWidth + "px";
        this._canvas.style.height = this._offsetHeight + "px";
    }, _timelineData: function () {
        var timelineData = this._dataProvider.timelineData();
        if (timelineData !== this._rawTimelineData || timelineData.entryStartTimes.length !== this._rawTimelineDataLength)
            this._processTimelineData(timelineData);
        return this._rawTimelineData;
    }, _cancelAnimation: function () {
        if (this._cancelWindowTimesAnimation) {
            this._timeWindowLeft = this._pendingAnimationTimeLeft;
            this._timeWindowRight = this._pendingAnimationTimeRight;
            this._cancelWindowTimesAnimation();
            delete this._cancelWindowTimesAnimation;
        }
    }, setWindowTimes: function (startTime, endTime) {
        if (this._muteAnimation || this._timeWindowLeft === 0 || this._timeWindowRight === Infinity) {
            this._timeWindowLeft = startTime;
            this._timeWindowRight = endTime;
            this.scheduleUpdate();
            return;
        }
        this._cancelAnimation();
        this._cancelWindowTimesAnimation = WebInspector.animateFunction(this._animateWindowTimes.bind(this), [{from: this._timeWindowLeft, to: startTime}, {from: this._timeWindowRight, to: endTime}], 5, this._animationCompleted.bind(this));
        this._pendingAnimationTimeLeft = startTime;
        this._pendingAnimationTimeRight = endTime;
    }, _animateWindowTimes: function (startTime, endTime) {
        this._timeWindowLeft = startTime;
        this._timeWindowRight = endTime;
        this.update();
    }, _animationCompleted: function () {
        delete this._cancelWindowTimesAnimation;
    }, _startCanvasDragging: function (event) {
        if (!this._timelineData() || this._timeWindowRight === Infinity)
            return false;
        this._isDragging = true;
        this._maxDragOffset = 0;
        this._dragStartPointX = event.pageX;
        this._dragStartPointY = event.pageY;
        this._dragStartScrollTop = this._vScrollElement.scrollTop;
        this._dragStartWindowLeft = this._timeWindowLeft;
        this._dragStartWindowRight = this._timeWindowRight;
        this._canvas.style.cursor = "";
        return true;
    }, _canvasDragging: function (event) {
        var pixelShift = this._dragStartPointX - event.pageX;
        this._dragStartPointX = event.pageX;
        this._muteAnimation = true;
        this._handlePanGesture(pixelShift * this._pixelToTime);
        this._muteAnimation = false;
        var pixelScroll = this._dragStartPointY - event.pageY;
        this._vScrollElement.scrollTop = this._dragStartScrollTop + pixelScroll;
        this._maxDragOffset = Math.max(this._maxDragOffset, Math.abs(pixelShift));
    }, _endCanvasDragging: function () {
        this._isDragging = false;
    }, _onMouseMove: function (event) {
        this._lastMouseOffsetX = event.offsetX;
        if (this._isDragging)
            return;
        var inDividersBar = event.offsetY < WebInspector.FlameChart.DividersBarHeight;
        this._highlightedMarkerIndex = inDividersBar ? this._markerIndexAtPosition(event.offsetX) : -1;
        this._updateMarkerHighlight();
        if (inDividersBar)
            return;
        var entryIndex = this._coordinatesToEntryIndex(event.offsetX, event.offsetY);
        if (this._highlightedEntryIndex === entryIndex)
            return;
        if (entryIndex === -1 || !this._dataProvider.canJumpToEntry(entryIndex))
            this._canvas.style.cursor = "default"; else
            this._canvas.style.cursor = "pointer";
        this._highlightedEntryIndex = entryIndex;
        this._updateElementPosition(this._highlightElement, this._highlightedEntryIndex);
        this._entryInfo.removeChildren();
        if (this._highlightedEntryIndex === -1)
            return;
        if (!this._isDragging) {
            var entryInfo = this._dataProvider.prepareHighlightedEntryInfo(this._highlightedEntryIndex);
            if (entryInfo)
                this._entryInfo.appendChild(this._buildEntryInfo(entryInfo));
        }
    }, _onClick: function () {
        this.focus();
        const clickThreshold = 5;
        if (this._maxDragOffset > clickThreshold)
            return;
        if (this._highlightedEntryIndex === -1)
            return;
        this.dispatchEventToListeners(WebInspector.FlameChart.Events.EntrySelected, this._highlightedEntryIndex);
    }, _onMouseWheel: function (e) {
        var panVertically = e.shiftKey && (e.wheelDeltaY || Math.abs(e.wheelDeltaX) === 120);
        var panHorizontally = Math.abs(e.wheelDeltaX) > Math.abs(e.wheelDeltaY) && !e.shiftKey;
        if (panVertically) {
            this._vScrollElement.scrollTop -= (e.wheelDeltaY || e.wheelDeltaX) / 120 * this._offsetHeight / 8;
        } else if (panHorizontally) {
            var shift = -e.wheelDeltaX * this._pixelToTime;
            this._muteAnimation = true;
            this._handlePanGesture(shift);
            this._muteAnimation = false;
        } else {
            const mouseWheelZoomSpeed = 1 / 120;
            this._handleZoomGesture(Math.pow(1.2, -(e.wheelDeltaY || e.wheelDeltaX) * mouseWheelZoomSpeed) - 1);
        }
        e.consume(true);
    }, _onKeyDown: function (e) {
        var zoomMultiplier = e.shiftKey ? 0.8 : 0.3;
        var panMultiplier = e.shiftKey ? 320 : 80;
        if (e.keyCode === "A".charCodeAt(0)) {
            this._handlePanGesture(-panMultiplier * this._pixelToTime);
            e.consume(true);
        } else if (e.keyCode === "D".charCodeAt(0)) {
            this._handlePanGesture(panMultiplier * this._pixelToTime);
            e.consume(true);
        } else if (e.keyCode === "W".charCodeAt(0)) {
            this._handleZoomGesture(-zoomMultiplier);
            e.consume(true);
        } else if (e.keyCode === "S".charCodeAt(0)) {
            this._handleZoomGesture(zoomMultiplier);
            e.consume(true);
        }
    }, _handleZoomGesture: function (zoom) {
        this._cancelAnimation();
        var bounds = this._windowForGesture();
        var cursorTime = this._cursorTime(this._lastMouseOffsetX);
        bounds.left += (bounds.left - cursorTime) * zoom;
        bounds.right += (bounds.right - cursorTime) * zoom;
        this._requestWindowTimes(bounds);
    }, _handlePanGesture: function (shift) {
        this._cancelAnimation();
        var bounds = this._windowForGesture();
        shift = Number.constrain(shift, this._minimumBoundary - bounds.left, this._totalTime + this._minimumBoundary - bounds.right);
        bounds.left += shift;
        bounds.right += shift;
        this._requestWindowTimes(bounds);
    }, _windowForGesture: function () {
        var windowLeft = this._timeWindowLeft ? this._timeWindowLeft : this._dataProvider.minimumBoundary();
        var windowRight = this._timeWindowRight !== Infinity ? this._timeWindowRight : this._dataProvider.minimumBoundary() + this._dataProvider.totalTime();
        return {left: windowLeft, right: windowRight};
    }, _requestWindowTimes: function (bounds) {
        bounds.left = Number.constrain(bounds.left, this._minimumBoundary, this._totalTime + this._minimumBoundary);
        bounds.right = Number.constrain(bounds.right, this._minimumBoundary, this._totalTime + this._minimumBoundary);
        this._flameChartDelegate.requestWindowTimes(bounds.left, bounds.right);
    }, _cursorTime: function (x) {
        return (x + this._pixelWindowLeft - this._paddingLeft) * this._pixelToTime + this._minimumBoundary;
    }, _coordinatesToEntryIndex: function (x, y) {
        y += this._scrollTop;
        var timelineData = this._timelineData();
        if (!timelineData)
            return -1;
        var cursorTime = this._cursorTime(x);
        var cursorLevel;
        var offsetFromLevel;
        if (this._isTopDown) {
            cursorLevel = Math.floor((y - WebInspector.FlameChart.DividersBarHeight) / this._barHeight);
            offsetFromLevel = y - WebInspector.FlameChart.DividersBarHeight - cursorLevel * this._barHeight;
        } else {
            cursorLevel = Math.floor((this._canvas.height / window.devicePixelRatio - y) / this._barHeight);
            offsetFromLevel = this._canvas.height / window.devicePixelRatio - cursorLevel * this._barHeight;
        }
        var entryStartTimes = timelineData.entryStartTimes;
        var entryTotalTimes = timelineData.entryTotalTimes;
        var entryIndexes = this._timelineLevels[cursorLevel];
        if (!entryIndexes || !entryIndexes.length)
            return -1;
        function comparator(time, entryIndex) {
            return time - entryStartTimes[entryIndex];
        }

        var indexOnLevel = Math.max(entryIndexes.upperBound(cursorTime, comparator) - 1, 0);

        function checkEntryHit(entryIndex) {
            if (entryIndex === undefined)
                return false;
            var startTime = entryStartTimes[entryIndex];
            var duration = entryTotalTimes[entryIndex];
            if (isNaN(duration)) {
                var dx = (startTime - cursorTime) / this._pixelToTime;
                var dy = this._barHeight / 2 - offsetFromLevel;
                return dx * dx + dy * dy < this._markerRadius * this._markerRadius;
            }
            var endTime = startTime + duration;
            var barThreshold = 3 * this._pixelToTime;
            return startTime - barThreshold < cursorTime && cursorTime < endTime + barThreshold;
        }

        var entryIndex = entryIndexes[indexOnLevel];
        if (checkEntryHit.call(this, entryIndex))
            return entryIndex;
        entryIndex = entryIndexes[indexOnLevel + 1];
        if (checkEntryHit.call(this, entryIndex))
            return entryIndex;
        return -1;
    }, _markerIndexAtPosition: function (x) {
        var markers = this._timelineData().markerTimestamps;
        if (!markers)
            return -1;
        var accurracyOffsetPx = 1;
        var time = this._cursorTime(x);
        var leftTime = this._cursorTime(x - accurracyOffsetPx);
        var rightTime = this._cursorTime(x + accurracyOffsetPx);

        function comparator(time, markerTimestamp) {
            return time - markerTimestamp;
        }

        var left = markers.lowerBound(leftTime, comparator);
        var markerIndex = -1;
        var distance = Infinity;
        for (var i = left; i < markers.length && markers[i] < rightTime; i++) {
            var nextDistance = Math.abs(markers[i] - time);
            if (nextDistance < distance) {
                markerIndex = i;
                distance = nextDistance;
            }
        }
        return markerIndex;
    }, _draw: function (width, height) {
        var timelineData = this._timelineData();
        if (!timelineData)
            return;
        var context = this._canvas.getContext("2d");
        context.save();
        var ratio = window.devicePixelRatio;
        context.scale(ratio, ratio);
        var timeWindowRight = this._timeWindowRight;
        var timeWindowLeft = this._timeWindowLeft;
        var timeToPixel = this._timeToPixel;
        var pixelWindowLeft = this._pixelWindowLeft;
        var paddingLeft = this._paddingLeft;
        var minWidth = this._minWidth;
        var entryTotalTimes = timelineData.entryTotalTimes;
        var entryStartTimes = timelineData.entryStartTimes;
        var entryLevels = timelineData.entryLevels;
        var titleIndices = new Uint32Array(timelineData.entryTotalTimes);
        var nextTitleIndex = 0;
        var markerIndices = new Uint32Array(timelineData.entryTotalTimes);
        var nextMarkerIndex = 0;
        var textPadding = this._dataProvider.textPadding();
        this._minTextWidth = 2 * textPadding + this._measureWidth(context, "\u2026");
        var minTextWidth = this._minTextWidth;
        var barHeight = this._barHeight;
        var timeToPosition = this._timeToPosition.bind(this);
        var textBaseHeight = this._baseHeight + barHeight - this._dataProvider.textBaseline();
        var colorBuckets = {};
        var minVisibleBarLevel = Math.max(Math.floor((this._scrollTop - this._baseHeight) / barHeight), 0);
        var maxVisibleBarLevel = Math.min(Math.floor((this._scrollTop - this._baseHeight + height) / barHeight), this._dataProvider.maxStackDepth());
        context.translate(0, -this._scrollTop);
        function comparator(time, entryIndex) {
            return time - entryStartTimes[entryIndex];
        }

        for (var level = minVisibleBarLevel; level <= maxVisibleBarLevel; ++level) {
            var levelIndexes = this._timelineLevels[level];
            var rightIndexOnLevel = levelIndexes.lowerBound(timeWindowRight, comparator) - 1;
            var lastDrawOffset = Infinity;
            for (var entryIndexOnLevel = rightIndexOnLevel; entryIndexOnLevel >= 0; --entryIndexOnLevel) {
                var entryIndex = levelIndexes[entryIndexOnLevel];
                var entryStartTime = entryStartTimes[entryIndex];
                var entryOffsetRight = entryStartTime + (isNaN(entryTotalTimes[entryIndex]) ? 0 : entryTotalTimes[entryIndex]);
                if (entryOffsetRight <= timeWindowLeft)
                    break;
                var barX = this._timeToPosition(entryStartTime);
                if (barX >= lastDrawOffset)
                    continue;
                var barRight = Math.min(this._timeToPosition(entryOffsetRight), lastDrawOffset);
                lastDrawOffset = barX;
                var color = this._dataProvider.entryColor(entryIndex);
                var bucket = colorBuckets[color];
                if (!bucket) {
                    bucket = [];
                    colorBuckets[color] = bucket;
                }
                bucket.push(entryIndex);
            }
        }
        var colors = Object.keys(colorBuckets);
        for (var c = 0; c < colors.length; ++c) {
            var color = colors[c];
            context.fillStyle = color;
            context.strokeStyle = color;
            var indexes = colorBuckets[color];
            context.beginPath();
            for (var i = 0; i < indexes.length; ++i) {
                var entryIndex = indexes[i];
                var entryStartTime = entryStartTimes[entryIndex];
                var barX = this._timeToPosition(entryStartTime);
                var barRight = this._timeToPosition(entryStartTime + entryTotalTimes[entryIndex]);
                var barWidth = Math.max(barRight - barX, minWidth);
                var barLevel = entryLevels[entryIndex];
                var barY = this._levelToHeight(barLevel);
                if (isNaN(entryTotalTimes[entryIndex])) {
                    context.moveTo(barX + this._markerRadius, barY + barHeight / 2);
                    context.arc(barX, barY + barHeight / 2, this._markerRadius, 0, Math.PI * 2);
                    markerIndices[nextMarkerIndex++] = entryIndex;
                } else {
                    context.rect(barX, barY, barWidth, barHeight);
                    if (barWidth > minTextWidth || this._dataProvider.forceDecoration(entryIndex))
                        titleIndices[nextTitleIndex++] = entryIndex;
                }
            }
            context.fill();
        }
        context.strokeStyle = "rgb(0, 0, 0)";
        context.beginPath();
        for (var m = 0; m < nextMarkerIndex; ++m) {
            var entryIndex = markerIndices[m];
            var entryStartTime = entryStartTimes[entryIndex];
            var barX = this._timeToPosition(entryStartTime);
            var barLevel = entryLevels[entryIndex];
            var barY = this._levelToHeight(barLevel);
            context.moveTo(barX + this._markerRadius, barY + barHeight / 2);
            context.arc(barX, barY + barHeight / 2, this._markerRadius, 0, Math.PI * 2);
        }
        context.stroke();
        context.textBaseline = "alphabetic";
        for (var i = 0; i < nextTitleIndex; ++i) {
            var entryIndex = titleIndices[i];
            var entryStartTime = entryStartTimes[entryIndex];
            var barX = this._timeToPosition(entryStartTime);
            var barRight = this._timeToPosition(entryStartTime + entryTotalTimes[entryIndex]);
            var barWidth = Math.max(barRight - barX, minWidth);
            var barLevel = entryLevels[entryIndex];
            var barY = this._levelToHeight(barLevel);
            var text = this._dataProvider.entryTitle(entryIndex);
            if (text && text.length) {
                context.font = this._dataProvider.entryFont(entryIndex);
                text = this._prepareText(context, text, barWidth - 2 * textPadding);
            }
            if (this._dataProvider.decorateEntry(entryIndex, context, text, barX, barY, barWidth, barHeight, timeToPosition))
                continue;
            if (!text || !text.length)
                continue;
            context.fillStyle = this._dataProvider.textColor(entryIndex);
            context.fillText(text, barX + textPadding, textBaseHeight - barLevel * this._barHeightDelta);
        }
        context.restore();
        var offsets = this._dataProvider.dividerOffsets(this._calculator.minimumBoundary(), this._calculator.maximumBoundary());
        WebInspector.TimelineGrid.drawCanvasGrid(this._canvas, this._calculator, offsets);
        this._drawMarkers();
        this._updateElementPosition(this._highlightElement, this._highlightedEntryIndex);
        this._updateElementPosition(this._selectedElement, this._selectedEntryIndex);
        this._updateMarkerHighlight();
    }, _drawMarkers: function () {
        var markerTimestamps = this._timelineData().markerTimestamps;

        function compare(time, markerTimestamp) {
            return time - markerTimestamp;
        }

        var left = markerTimestamps.lowerBound(this._calculator.minimumBoundary(), compare);
        var rightBoundary = this._calculator.maximumBoundary();
        var context = this._canvas.getContext("2d");
        context.save();
        var ratio = window.devicePixelRatio;
        context.scale(ratio, ratio);
        var height = WebInspector.FlameChart.DividersBarHeight - 1;
        context.lineWidth = 2;
        for (var i = left; i < markerTimestamps.length; i++) {
            var timestamp = markerTimestamps[i];
            if (timestamp > rightBoundary)
                break;
            var position = this._calculator.computePosition(timestamp);
            context.strokeStyle = this._dataProvider.markerColor(i);
            context.beginPath();
            context.moveTo(position, 0);
            context.lineTo(position, height);
            context.stroke();
        }
        context.restore();
    }, _updateMarkerHighlight: function () {
        var element = this._markerHighlighElement;
        if (element.parentElement)
            element.remove();
        var markerIndex = this._highlightedMarkerIndex;
        if (markerIndex === -1)
            return;
        var barX = this._timeToPosition(this._timelineData().markerTimestamps[markerIndex]);
        element.title = this._dataProvider.markerTitle(markerIndex);
        var style = element.style;
        style.left = barX + "px";
        style.backgroundColor = this._dataProvider.markerColor(markerIndex);
        this.element.appendChild(element);
    }, _processTimelineData: function (timelineData) {
        if (!timelineData) {
            this._timelineLevels = null;
            this._rawTimelineData = null;
            this._rawTimelineDataLength = 0;
            return;
        }
        var entryCounters = new Uint32Array(this._dataProvider.maxStackDepth() + 1);
        for (var i = 0; i < timelineData.entryLevels.length; ++i)
            ++entryCounters[timelineData.entryLevels[i]];
        var levelIndexes = new Array(entryCounters.length);
        for (var i = 0; i < levelIndexes.length; ++i) {
            levelIndexes[i] = new Uint32Array(entryCounters[i]);
            entryCounters[i] = 0;
        }
        for (var i = 0; i < timelineData.entryLevels.length; ++i) {
            var level = timelineData.entryLevels[i];
            levelIndexes[level][entryCounters[level]++] = i;
        }
        this._timelineLevels = levelIndexes;
        this._rawTimelineData = timelineData;
        this._rawTimelineDataLength = timelineData.entryStartTimes.length;
    }, setSelectedEntry: function (entryIndex) {
        this._selectedEntryIndex = entryIndex;
        this._updateElementPosition(this._selectedElement, this._selectedEntryIndex);
    }, _updateElementPosition: function (element, entryIndex) {
        if (element.parentElement)
            element.remove();
        if (entryIndex === -1)
            return;
        var timeRange = this._dataProvider.highlightTimeRange(entryIndex);
        if (!timeRange)
            return;
        var timelineData = this._timelineData();
        var barX = this._timeToPosition(timeRange.startTime);
        var barRight = this._timeToPosition(timeRange.endTime);
        if (barRight === 0 || barX === this._canvas.width)
            return;
        var barWidth = Math.max(barRight - barX, this._minWidth);
        var barY = this._levelToHeight(timelineData.entryLevels[entryIndex]) - this._scrollTop;
        var style = element.style;
        style.left = barX + "px";
        style.top = barY + "px";
        style.width = barWidth + "px";
        style.height = this._barHeight + "px";
        this.element.appendChild(element);
    }, _timeToPosition: function (time) {
        var value = Math.floor((time - this._minimumBoundary) * this._timeToPixel) - this._pixelWindowLeft + this._paddingLeft;
        return Math.min(this._canvas.width, Math.max(0, value));
    }, _levelToHeight: function (level) {
        return this._baseHeight - level * this._barHeightDelta;
    }, _buildEntryInfo: function (entryInfo) {
        var infoTable = document.createElementWithClass("table", "info-table");
        for (var i = 0; i < entryInfo.length; ++i) {
            var row = infoTable.createChild("tr");
            row.createChild("td", "title").textContent = entryInfo[i].title;
            row.createChild("td").textContent = entryInfo[i].text;
        }
        return infoTable;
    }, _prepareText: function (context, title, maxSize) {
        var titleWidth = this._measureWidth(context, title);
        if (maxSize >= titleWidth)
            return title;
        var l = 2;
        var r = title.length;
        while (l < r) {
            var m = (l + r) >> 1;
            if (this._measureWidth(context, title.trimMiddle(m)) <= maxSize)
                l = m + 1; else
                r = m;
        }
        title = title.trimMiddle(r - 1);
        return title !== "\u2026" ? title : "";
    }, _measureWidth: function (context, text) {
        if (text.length > 20)
            return context.measureText(text).width;
        var font = context.font;
        var textWidths = this._textWidth[font];
        if (!textWidths) {
            textWidths = {};
            this._textWidth[font] = textWidths;
        }
        var width = textWidths[text];
        if (!width) {
            width = context.measureText(text).width;
            textWidths[text] = width;
        }
        return width;
    }, _updateBoundaries: function () {
        this._totalTime = this._dataProvider.totalTime();
        this._minimumBoundary = this._dataProvider.minimumBoundary();
        if (this._timeWindowRight !== Infinity) {
            this._windowLeft = (this._timeWindowLeft - this._minimumBoundary) / this._totalTime;
            this._windowRight = (this._timeWindowRight - this._minimumBoundary) / this._totalTime;
            this._windowWidth = this._windowRight - this._windowLeft;
        } else {
            this._windowLeft = 0;
            this._windowRight = 1;
            this._windowWidth = 1;
        }
        this._pixelWindowWidth = this._offsetWidth - this._paddingLeft;
        this._totalPixels = Math.floor(this._pixelWindowWidth / this._windowWidth);
        this._pixelWindowLeft = Math.floor(this._totalPixels * this._windowLeft);
        this._pixelWindowRight = Math.floor(this._totalPixels * this._windowRight);
        this._timeToPixel = this._totalPixels / this._totalTime;
        this._pixelToTime = this._totalTime / this._totalPixels;
        this._paddingLeftTime = this._paddingLeft / this._timeToPixel;
        this._baseHeight = this._isTopDown ? WebInspector.FlameChart.DividersBarHeight : this._offsetHeight - this._barHeight;
        this._totalHeight = this._levelToHeight(this._dataProvider.maxStackDepth() + 1);
        this._vScrollContent.style.height = this._totalHeight + "px";
        this._scrollTop = this._vScrollElement.scrollTop;
        this._updateScrollBar();
    }, onResize: function () {
        this._updateScrollBar();
        this.scheduleUpdate();
    }, _updateScrollBar: function () {
        var showScroll = this._totalHeight > this._offsetHeight;
        this._vScrollElement.classList.toggle("hidden", !showScroll);
        this._offsetWidth = this.element.offsetWidth - (WebInspector.isMac() ? 0 : this._vScrollElement.offsetWidth);
        this._offsetHeight = this.element.offsetHeight;
    }, scheduleUpdate: function () {
        if (this._updateTimerId || this._cancelWindowTimesAnimation)
            return;
        this._updateTimerId = requestAnimationFrame(this.update.bind(this));
    }, update: function () {
        this._updateTimerId = 0;
        if (!this._timelineData())
            return;
        this._resetCanvas();
        this._updateBoundaries();
        this._calculator._updateBoundaries(this);
        this._draw(this._offsetWidth, this._offsetHeight);
    }, reset: function () {
        this._highlightedMarkerIndex = -1;
        this._highlightedEntryIndex = -1;
        this._selectedEntryIndex = -1;
        this._textWidth = {};
        this.update();
    }, __proto__: WebInspector.HBox.prototype
}
WebInspector.DockController = function (canDock) {
    this._canDock = canDock;
    if (!canDock) {
        this._dockSide = WebInspector.DockController.State.Undocked;
        this._updateUI();
        return;
    }
    WebInspector.settings.currentDockState = WebInspector.settings.createSetting("currentDockState", "");
    WebInspector.settings.lastDockState = WebInspector.settings.createSetting("lastDockState", "");
}
WebInspector.DockController.State = {DockedToBottom: "bottom", DockedToRight: "right", DockedToLeft: "left", Undocked: "undocked"}
WebInspector.DockController.Events = {BeforeDockSideChanged: "BeforeDockSideChanged", DockSideChanged: "DockSideChanged", AfterDockSideChanged: "AfterDockSideChanged"}
WebInspector.DockController.prototype = {
    initialize: function () {
        if (!this._canDock)
            return;
        this._states = [WebInspector.DockController.State.DockedToBottom, WebInspector.DockController.State.Undocked, WebInspector.DockController.State.DockedToRight];
        this._titles = [WebInspector.UIString("Dock to main window."), WebInspector.UIString("Undock into separate window."), WebInspector.UIString("Dock to main window.")];
        if (WebInspector.experimentsSettings.dockToLeft.isEnabled()) {
            this._states.push(WebInspector.DockController.State.DockedToLeft);
            this._titles.push(WebInspector.UIString("Dock to main window."));
        }
        var initialState = WebInspector.settings.currentDockState.get();
        initialState = this._states.indexOf(initialState) >= 0 ? initialState : this._states[0];
        this._dockSideChanged(initialState);
    }, dockSide: function () {
        return this._dockSide;
    }, canDock: function () {
        return this._canDock;
    }, isVertical: function () {
        return this._dockSide === WebInspector.DockController.State.DockedToRight || this._dockSide === WebInspector.DockController.State.DockedToLeft;
    }, _dockSideChanged: function (dockSide) {
        if (this._dockSide === dockSide)
            return;
        var eventData = {from: this._dockSide, to: dockSide};
        this.dispatchEventToListeners(WebInspector.DockController.Events.BeforeDockSideChanged, eventData);
        console.timeStamp("DockController.setIsDocked");
        InspectorFrontendHost.setIsDocked(dockSide !== WebInspector.DockController.State.Undocked, this._setIsDockedResponse.bind(this, eventData));
        this._dockSide = dockSide;
        this._updateUI();
        this.dispatchEventToListeners(WebInspector.DockController.Events.DockSideChanged, eventData);
    }, _setIsDockedResponse: function (eventData) {
        this.dispatchEventToListeners(WebInspector.DockController.Events.AfterDockSideChanged, eventData);
    }, _updateUI: function () {
        var body = document.body;
        switch (this._dockSide) {
            case WebInspector.DockController.State.DockedToBottom:
                body.classList.remove("undocked");
                body.classList.remove("dock-to-right");
                body.classList.remove("dock-to-left");
                body.classList.add("dock-to-bottom");
                break;
            case WebInspector.DockController.State.DockedToRight:
                body.classList.remove("undocked");
                body.classList.add("dock-to-right");
                body.classList.remove("dock-to-left");
                body.classList.remove("dock-to-bottom");
                break;
            case WebInspector.DockController.State.DockedToLeft:
                body.classList.remove("undocked");
                body.classList.remove("dock-to-right");
                body.classList.add("dock-to-left");
                body.classList.remove("dock-to-bottom");
                break;
            case WebInspector.DockController.State.Undocked:
                body.classList.add("undocked");
                body.classList.remove("dock-to-right");
                body.classList.remove("dock-to-left");
                body.classList.remove("dock-to-bottom");
                break;
        }
    }, __proto__: WebInspector.Object.prototype
}
WebInspector.DockController.ButtonProvider = function () {
}
WebInspector.DockController.ButtonProvider.prototype = {
    item: function () {
        if (!WebInspector.dockController.canDock())
            return null;
        if (!this._dockToggleButton) {
            this._dockToggleButton = new WebInspector.StatusBarStatesSettingButton("dock-status-bar-item", WebInspector.dockController._states, WebInspector.dockController._titles, WebInspector.dockController.dockSide(), WebInspector.settings.currentDockState, WebInspector.settings.lastDockState, WebInspector.dockController._dockSideChanged.bind(WebInspector.dockController));
        }
        return this._dockToggleButton;
    }
}
WebInspector.dockController;
WebInspector.TargetsComboBoxController = function (selectElement, elementToHide) {
    elementToHide.classList.add("hidden");
    selectElement.addEventListener("change", this._onComboBoxSelectionChange.bind(this), false);
    this._selectElement = selectElement;
    this._elementToHide = elementToHide;
    this._targetToOption = new Map();
    WebInspector.context.addFlavorChangeListener(WebInspector.Target, this._targetChangedExternally, this);
    WebInspector.targetManager.observeTargets(this);
}
WebInspector.TargetsComboBoxController.prototype = {
    targetAdded: function (target) {
        var option = this._selectElement.createChild("option");
        option.text = target.name();
        option.__target = target;
        this._targetToOption.put(target, option);
        if (WebInspector.context.flavor(WebInspector.Target) === target)
            this._selectElement.selectedIndex = Array.prototype.indexOf.call((this._selectElement), option);
        this._updateVisibility();
    }, targetRemoved: function (target) {
        var option = this._targetToOption.remove(target);
        this._selectElement.removeChild(option);
        this._updateVisibility();
    }, _onComboBoxSelectionChange: function () {
        var selectedOption = this._selectElement[this._selectElement.selectedIndex];
        if (!selectedOption)
            return;
        WebInspector.context.setFlavor(WebInspector.Target, selectedOption.__target);
    }, _updateVisibility: function () {
        var hidden = this._selectElement.childElementCount === 1;
        this._elementToHide.classList.toggle("hidden", hidden);
    }, _targetChangedExternally: function (event) {
        var target = (event.data);
        if (target) {
            var option = (this._targetToOption.get(target));
            this._select(option);
        }
    }, _select: function (option) {
        this._selectElement.selectedIndex = Array.prototype.indexOf.call((this._selectElement), option);
    }
}
WebInspector.PaintProfilerSnapshot = function (target, snapshotId) {
    this._target = target;
    this._id = snapshotId;
}
WebInspector.PaintProfilerSnapshot.load = function (target, encodedPicture, callback) {
    var wrappedCallback = InspectorBackend.wrapClientCallback(callback, "LayerTreeAgent.loadSnapshot(): ", WebInspector.PaintProfilerSnapshot.bind(null, target));
    target.layerTreeAgent().loadSnapshot(encodedPicture, wrappedCallback);
}
WebInspector.PaintProfilerSnapshot._processAnnotations = function (log) {
    var result = [];
    var commentGroupStack = [];
    for (var i = 0; i < log.length; ++i) {
        var method = log[i].method;
        switch (method) {
            case"beginCommentGroup":
                commentGroupStack.push({});
                break;
            case"addComment":
                var group = commentGroupStack.peekLast();
                if (!group) {
                    console.assert(false, "Stray comment without a group");
                    break;
                }
                var key = String(log[i].params["key"]);
                var value = String(log[i].params["value"]);
                if (!key || typeof value === "undefined") {
                    console.assert(false, "Missing key or value in addComment() params");
                    break;
                }
                if (key in group) {
                    console.assert(false, "Duplicate key in comment group");
                    break;
                }
                group[key] = value;
                break;
            case"endCommentGroup":
                if (!commentGroupStack.length)
                    console.assert(false, "Unbalanced commentGroupEnd call"); else
                    commentGroupStack.pop();
                break;
            default:
                result.push(new WebInspector.PaintProfilerLogItem(log[i], i, commentGroupStack.peekLast()));
        }
    }
    return result;
}
WebInspector.PaintProfilerSnapshot.prototype = {
    dispose: function () {
        this._target.layerTreeAgent().releaseSnapshot(this._id);
    }, target: function () {
        return this._target;
    }, requestImage: function (firstStep, lastStep, scale, callback) {
        var wrappedCallback = InspectorBackend.wrapClientCallback(callback, "LayerTreeAgent.replaySnapshot(): ");
        this._target.layerTreeAgent().replaySnapshot(this._id, firstStep || undefined, lastStep || undefined, scale || 1.0, wrappedCallback);
    }, profile: function (callback) {
        var wrappedCallback = InspectorBackend.wrapClientCallback(callback, "LayerTreeAgent.profileSnapshot(): ");
        this._target.layerTreeAgent().profileSnapshot(this._id, 5, 1, wrappedCallback);
    }, commandLog: function (callback) {
        function callbackWrapper(error, log) {
            if (error) {
                console.error("LayerTreeAgent.snapshotCommandLog(): " + error);
                callback();
                return;
            }
            callback(WebInspector.PaintProfilerSnapshot._processAnnotations(log));
        }

        this._target.layerTreeAgent().snapshotCommandLog(this._id, callbackWrapper);
    }
};
WebInspector.RawPaintProfilerLogItem;
WebInspector.PaintProfilerLogItem = function (rawEntry, commandIndex, annotations) {
    this.method = rawEntry.method;
    this.params = rawEntry.params;
    this.annotations = annotations;
    this.commandIndex = commandIndex;
}
WebInspector.PaintProfilerLogItem.prototype = {
    nodeId: function () {
        if (!this.annotations)
            return 0;
        var inspectorId = this.annotations["INSPECTOR_ID"];
        return Number(inspectorId);
    }
}
WebInspector.ExtensionServerAPI = function () {
}
WebInspector.ExtensionServerAPI.prototype = {
    addExtensions: function (descriptors) {
    }
}
WebInspector.ExtensionServerProxy = function () {
}
WebInspector.ExtensionServerProxy._ensureExtensionServer = function () {
    if (!WebInspector.extensionServer)
        WebInspector.extensionServer = self.runtime.instance(WebInspector.ExtensionServerAPI);
}, WebInspector.ExtensionServerProxy.prototype = {
    setFrontendReady: function () {
        this._frontendReady = true;
        this._pushExtensionsToServer();
    }, _addExtensions: function (extensions) {
        if (extensions.length === 0)
            return;
        console.assert(!this._pendingExtensions);
        this._pendingExtensions = extensions;
        this._pushExtensionsToServer();
    }, _pushExtensionsToServer: function () {
        if (!this._frontendReady || !this._pendingExtensions)
            return;
        WebInspector.ExtensionServerProxy._ensureExtensionServer();
        WebInspector.extensionServer.addExtensions(this._pendingExtensions);
        delete this._pendingExtensions;
    }
}
WebInspector.extensionServerProxy = new WebInspector.ExtensionServerProxy();
WebInspector.addExtensions = function (extensions) {
    WebInspector.extensionServerProxy._addExtensions(extensions);
}
WebInspector.setInspectedTabId = function (tabId) {
    WebInspector._inspectedTabId = tabId;
}
WebInspector.HelpScreenUntilReload = function (title, message) {
    WebInspector.HelpScreen.call(this, title);
    var p = this.contentElement.createChild("p");
    p.classList.add("help-section");
    p.textContent = message;
    WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this.hide, this);
}
WebInspector.HelpScreenUntilReload.prototype = {
    willHide: function () {
        WebInspector.debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this.hide, this);
        WebInspector.HelpScreen.prototype.willHide.call(this);
    }, __proto__: WebInspector.HelpScreen.prototype
}
WebInspector.App = function () {
    WebInspector.console.setUIDelegate(this);
};
WebInspector.App.prototype = {
    createRootView: function () {
    }, presentUI: function (mainTarget) {
        WebInspector.inspectorView.showInitialPanel();
        WebInspector.overridesSupport.applyInitialOverrides();
        if (!WebInspector.overridesSupport.responsiveDesignAvailable() && WebInspector.overridesSupport.emulationEnabled())
            WebInspector.inspectorView.showViewInDrawer("emulation", true);
    }, showConsole: function () {
        WebInspector.Revealer.reveal(WebInspector.console);
    }
};
WebInspector.app;
WebInspector.SimpleApp = function () {
    WebInspector.App.call(this);
};
WebInspector.SimpleApp.prototype = {
    createRootView: function () {
        var rootView = new WebInspector.RootView();
        WebInspector.inspectorView.show(rootView.element);
        rootView.attachToBody();
    }, __proto__: WebInspector.App.prototype
};
WebInspector.AdvancedApp = function () {
    WebInspector.App.call(this);
    if (WebInspector.overridesSupport.responsiveDesignAvailable()) {
        this._toggleEmulationButton = new WebInspector.StatusBarButton(WebInspector.UIString("Toggle device mode."), "emulation-status-bar-item");
        this._toggleEmulationButton.toggled = WebInspector.overridesSupport.emulationEnabled();
        this._toggleEmulationButton.addEventListener("click", this._toggleEmulationEnabled, this);
        WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.EmulationStateChanged, this._emulationEnabledChanged, this);
        WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.OverridesWarningUpdated, this._overridesWarningUpdated, this);
    }
    WebInspector.dockController.addEventListener(WebInspector.DockController.Events.BeforeDockSideChanged, this._openToolboxWindow, this);
};
WebInspector.AdvancedApp.prototype = {
    _toggleEmulationEnabled: function () {
        var enabled = !this._toggleEmulationButton.toggled;
        if (enabled)
            WebInspector.userMetrics.DeviceModeEnabled.record();
        WebInspector.overridesSupport.setEmulationEnabled(enabled);
    }, _emulationEnabledChanged: function () {
        this._toggleEmulationButton.toggled = WebInspector.overridesSupport.emulationEnabled();
        if (!WebInspector.overridesSupport.responsiveDesignAvailable() && WebInspector.overridesSupport.emulationEnabled())
            WebInspector.inspectorView.showViewInDrawer("emulation", true);
    }, _overridesWarningUpdated: function () {
        if (!this._toggleEmulationButton)
            return;
        var message = WebInspector.overridesSupport.warningMessage();
        this._toggleEmulationButton.title = message || WebInspector.UIString("Toggle device mode.");
        this._toggleEmulationButton.element.classList.toggle("warning", !!message);
    }, createRootView: function () {
        var rootView = new WebInspector.RootView();
        this._rootSplitView = new WebInspector.SplitView(false, true, "InspectorView.splitViewState", 300, 300, true);
        this._rootSplitView.show(rootView.element);
        WebInspector.inspectorView.show(this._rootSplitView.sidebarElement());
        this._inspectedPagePlaceholder = new WebInspector.InspectedPagePlaceholder();
        this._inspectedPagePlaceholder.addEventListener(WebInspector.InspectedPagePlaceholder.Events.Update, this._onSetInspectedPageBounds.bind(this, false), this);
        this._responsiveDesignView = new WebInspector.ResponsiveDesignView(this._inspectedPagePlaceholder);
        this._responsiveDesignView.show(this._rootSplitView.mainElement());
        WebInspector.dockController.addEventListener(WebInspector.DockController.Events.BeforeDockSideChanged, this._onBeforeDockSideChange, this);
        WebInspector.dockController.addEventListener(WebInspector.DockController.Events.DockSideChanged, this._onDockSideChange, this);
        WebInspector.dockController.addEventListener(WebInspector.DockController.Events.AfterDockSideChanged, this._onAfterDockSideChange, this);
        this._onDockSideChange();
        console.timeStamp("AdvancedApp.attachToBody");
        rootView.attachToBody();
        this._inspectedPagePlaceholder.update();
    }, presentUI: function (mainTarget) {
        WebInspector.App.prototype.presentUI.call(this, mainTarget);
        this._overridesWarningUpdated();
    }, _openToolboxWindow: function (event) {
        if ((event.data.to) !== WebInspector.DockController.State.Undocked)
            return;
        if (this._toolboxWindow)
            return;
        var toolbox = (window.location.search ? "&" : "?") + "toolbox=true";
        var hash = window.location.hash;
        var url = window.location.href.replace(hash, "") + toolbox + hash;
        this._toolboxWindow = window.open(url, undefined);
    }, toolboxLoaded: function (responsiveDesignView, placeholder) {
        this._toolboxResponsiveDesignView = responsiveDesignView;
        placeholder.addEventListener(WebInspector.InspectedPagePlaceholder.Events.Update, this._onSetInspectedPageBounds.bind(this, true));
        this._updatePageResizer();
    }, _updatePageResizer: function () {
        if (this._isDocked())
            this._responsiveDesignView.updatePageResizer(); else if (this._toolboxResponsiveDesignView)
            this._toolboxResponsiveDesignView.updatePageResizer();
    }, _onBeforeDockSideChange: function (event) {
        if ((event.data.to) === WebInspector.DockController.State.Undocked && this._toolboxResponsiveDesignView) {
            this._rootSplitView.hideSidebar();
            this._inspectedPagePlaceholder.update();
        }
        this._changingDockSide = true;
    }, _onDockSideChange: function (event) {
        this._updatePageResizer();
        var toDockSide = event ? (event.data.to) : WebInspector.dockController.dockSide();
        if (toDockSide === WebInspector.DockController.State.Undocked) {
            this._updateForUndocked();
        } else if (this._toolboxResponsiveDesignView && event && (event.data.from) === WebInspector.DockController.State.Undocked) {
            this._rootSplitView.hideSidebar();
        } else {
            this._updateForDocked(toDockSide);
        }
    }, _onAfterDockSideChange: function (event) {
        if (!this._changingDockSide)
            return;
        this._changingDockSide = false;
        if ((event.data.from) === WebInspector.DockController.State.Undocked) {
            this._updateForDocked((event.data.to));
        }
        this._inspectedPagePlaceholder.update();
    }, _updateForDocked: function (dockSide) {
        this._rootSplitView.setVertical(dockSide === WebInspector.DockController.State.DockedToLeft || dockSide === WebInspector.DockController.State.DockedToRight);
        this._rootSplitView.setSecondIsSidebar(dockSide === WebInspector.DockController.State.DockedToRight || dockSide === WebInspector.DockController.State.DockedToBottom);
        this._rootSplitView.toggleResizer(this._rootSplitView.resizerElement(), true);
        this._rootSplitView.toggleResizer(WebInspector.inspectorView.topResizerElement(), dockSide === WebInspector.DockController.State.DockedToBottom);
        this._rootSplitView.showBoth();
    }, _updateForUndocked: function () {
        this._rootSplitView.toggleResizer(this._rootSplitView.resizerElement(), false);
        this._rootSplitView.toggleResizer(WebInspector.inspectorView.topResizerElement(), false);
        this._rootSplitView.hideMain();
    }, _isDocked: function () {
        return WebInspector.dockController.dockSide() !== WebInspector.DockController.State.Undocked;
    }, _onSetInspectedPageBounds: function (toolbox, event) {
        if (this._changingDockSide || (this._isDocked() === toolbox))
            return;
        if (!window.innerWidth || !window.innerHeight)
            return;
        var bounds = (event.data);
        console.timeStamp("AdvancedApp.setInspectedPageBounds");
        InspectorFrontendHost.setInspectedPageBounds(bounds);
    }, __proto__: WebInspector.App.prototype
};
WebInspector.AdvancedApp.DeviceCounter = function () {
    if (!WebInspector.experimentsSettings.devicesPanel.isEnabled() || !(WebInspector.app instanceof WebInspector.AdvancedApp)) {
        this._counter = null;
        return;
    }
    this._counter = new WebInspector.StatusBarCounter(["device-icon-small"]);
    this._counter.addEventListener("click", showDevices);
    function showDevices() {
        WebInspector.inspectorView.showViewInDrawer("devices", true);
    }

    InspectorFrontendHost.setDeviceCountUpdatesEnabled(true);
    InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DeviceCountUpdated, this._onDeviceCountUpdated, this);
}
WebInspector.AdvancedApp.DeviceCounter.prototype = {
    _onDeviceCountUpdated: function (event) {
        var count = (event.data);
        this._counter.setCounter("device-icon-small", count, WebInspector.UIString(count > 1 ? "%d devices found" : "%d device found", count));
        WebInspector.inspectorView.toolbarItemResized();
    }, item: function () {
        return this._counter;
    }
}
WebInspector.AdvancedApp.EmulationButtonProvider = function () {
}
WebInspector.AdvancedApp.EmulationButtonProvider.prototype = {
    item: function () {
        if (!(WebInspector.app instanceof WebInspector.AdvancedApp))
            return null;
        return WebInspector.app._toggleEmulationButton || null;
    }
}
WebInspector.AdvancedApp.ToggleDeviceModeActionDelegate = function () {
}
WebInspector.AdvancedApp.ToggleDeviceModeActionDelegate.prototype = {
    handleAction: function () {
        if (!WebInspector.overridesSupport.responsiveDesignAvailable())
            return false;
        if (!(WebInspector.app instanceof WebInspector.AdvancedApp))
            return false;
        WebInspector.app._toggleEmulationEnabled();
        return true;
    }
}
WebInspector.RenderingOptions = function () {
    this._setterNames = new Map();
    this._mapSettingToSetter(WebInspector.settings.showPaintRects, "setShowPaintRects");
    this._mapSettingToSetter(WebInspector.settings.showDebugBorders, "setShowDebugBorders");
    this._mapSettingToSetter(WebInspector.settings.showFPSCounter, "setShowFPSCounter");
    this._mapSettingToSetter(WebInspector.settings.continuousPainting, "setContinuousPaintingEnabled");
    this._mapSettingToSetter(WebInspector.settings.showScrollBottleneckRects, "setShowScrollBottleneckRects");
    WebInspector.targetManager.observeTargets(this);
}
WebInspector.RenderingOptions.prototype = {
    targetAdded: function (target) {
        var settings = this._setterNames.keys();
        for (var i = 0; i < settings.length; ++i) {
            var setting = settings[i];
            if (setting.get()) {
                var setterName = this._setterNames.get(setting);
                target.pageAgent()[setterName](true);
            }
        }
    }, targetRemoved: function (target) {
    }, _mapSettingToSetter: function (setting, setterName) {
        this._setterNames.put(setting, setterName);
        setting.addChangeListener(changeListener);
        function changeListener() {
            var targets = WebInspector.targetManager.targets();
            for (var i = 0; i < targets.length; ++i)
                targets[i].pageAgent()[setterName](setting.get());
        }
    }
}
WebInspector.RenderingOptions.View = function () {
    WebInspector.VBox.call(this);
    this.registerRequiredCSS("helpScreen.css");
    this.element.classList.add("help-indent-labels");
    var div = this.element.createChild("div", "settings-tab help-content help-container help-no-columns");
    div.appendChild(WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Show paint rectangles"), WebInspector.settings.showPaintRects));
    div.appendChild(WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Show composited layer borders"), WebInspector.settings.showDebugBorders));
    div.appendChild(WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Show FPS meter"), WebInspector.settings.showFPSCounter));
    div.appendChild(WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Enable continuous page repainting"), WebInspector.settings.continuousPainting));
    var child = WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Show potential scroll bottlenecks"), WebInspector.settings.showScrollBottleneckRects);
    child.title = WebInspector.UIString("Shows areas of the page that slow down scrolling:\nTouch and mousewheel event listeners can delay scrolling.\nSome areas need to repaint their content when scrolled.");
    div.appendChild(child);
}
WebInspector.RenderingOptions.View.prototype = {__proto__: WebInspector.VBox.prototype}
WebInspector.ScreencastApp = function () {
    WebInspector.App.call(this);
    var lastScreencastState = WebInspector.settings.createSetting("lastScreencastState", "left");
    this._currentScreencastState = WebInspector.settings.createSetting("currentScreencastState", "disabled");
    this._toggleScreencastButton = new WebInspector.StatusBarStatesSettingButton("screencast-status-bar-item", ["disabled", "left", "top"], [WebInspector.UIString("Disable screencast."), WebInspector.UIString("Switch to portrait screencast."), WebInspector.UIString("Switch to landscape screencast.")], this._currentScreencastState.get(), this._currentScreencastState, lastScreencastState, this._onStatusBarButtonStateChanged.bind(this));
};
WebInspector.ScreencastApp.prototype = {
    createRootView: function () {
        var rootView = new WebInspector.RootView();
        this._rootSplitView = new WebInspector.SplitView(false, true, "InspectorView.screencastSplitViewState", 300, 300);
        this._rootSplitView.show(rootView.element);
        this._rootSplitView.hideMain();
        WebInspector.inspectorView.show(this._rootSplitView.sidebarElement());
        rootView.attachToBody();
    }, presentUI: function (mainTarget) {
        if (mainTarget.hasCapability(WebInspector.Target.Capabilities.CanScreencast)) {
            this._screencastView = new WebInspector.ScreencastView(mainTarget);
            this._screencastView.show(this._rootSplitView.mainElement());
            this._screencastView.initialize();
            this._onStatusBarButtonStateChanged(this._currentScreencastState.get());
        } else {
            this._onStatusBarButtonStateChanged("disabled");
            this._toggleScreencastButton.setEnabled(false);
        }
        WebInspector.App.prototype.presentUI.call(this, mainTarget);
    }, _onStatusBarButtonStateChanged: function (state) {
        if (!this._rootSplitView)
            return;
        if (state === "disabled") {
            this._rootSplitView.toggleResizer(this._rootSplitView.resizerElement(), false);
            this._rootSplitView.toggleResizer(WebInspector.inspectorView.topResizerElement(), false);
            this._rootSplitView.hideMain();
            return;
        }
        this._rootSplitView.setVertical(state === "left");
        this._rootSplitView.setSecondIsSidebar(true);
        this._rootSplitView.toggleResizer(this._rootSplitView.resizerElement(), true);
        this._rootSplitView.toggleResizer(WebInspector.inspectorView.topResizerElement(), state === "top");
        this._rootSplitView.showBoth();
    }, __proto__: WebInspector.App.prototype
};
WebInspector.ScreencastApp.StatusBarButtonProvider = function () {
}
WebInspector.ScreencastApp.StatusBarButtonProvider.prototype = {
    item: function () {
        if (!(WebInspector.app instanceof WebInspector.ScreencastApp))
            return null;
        return (WebInspector.app)._toggleScreencastButton;
    }
}
WebInspector.OverridesView = function () {
    WebInspector.VBox.call(this);
    this.registerRequiredCSS("overrides.css");
    this.element.classList.add("overrides-view");
    this._tabbedPane = new WebInspector.TabbedPane();
    this._tabbedPane.shrinkableTabs = false;
    this._tabbedPane.verticalTabLayout = true;
    new WebInspector.OverridesView.DeviceTab().appendAsTab(this._tabbedPane);
    new WebInspector.OverridesView.MediaTab().appendAsTab(this._tabbedPane);
    new WebInspector.OverridesView.NetworkTab().appendAsTab(this._tabbedPane);
    new WebInspector.OverridesView.SensorsTab().appendAsTab(this._tabbedPane);
    this._lastSelectedTabSetting = WebInspector.settings.createSetting("lastSelectedEmulateTab", "device");
    this._tabbedPane.selectTab(this._lastSelectedTabSetting.get());
    this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this);
    this._tabbedPane.show(this.element);
    var resetButtonElement = this._tabbedPane.headerElement().createChild("button", "text-button");
    resetButtonElement.id = "overrides-reset-button";
    resetButtonElement.textContent = WebInspector.UIString("Reset");
    resetButtonElement.addEventListener("click", WebInspector.overridesSupport.reset.bind(WebInspector.overridesSupport), false);
    if (!WebInspector.overridesSupport.responsiveDesignAvailable()) {
        var disableButtonElement = this._tabbedPane.headerElement().createChild("button", "text-button overrides-disable-button");
        disableButtonElement.id = "overrides-disable-button";
        disableButtonElement.textContent = WebInspector.UIString("Disable");
        disableButtonElement.addEventListener("click", this._toggleEmulationEnabled.bind(this), false);
    }
    this._splashScreenElement = this.element.createChild("div", "overrides-splash-screen");
    this._unavailableSplashScreenElement = this.element.createChild("div", "overrides-splash-screen");
    this._unavailableSplashScreenElement.createTextChild(WebInspector.UIString("Emulation is not available."));
    if (WebInspector.overridesSupport.responsiveDesignAvailable()) {
        this._splashScreenElement.createTextChild(WebInspector.UIString("Emulation is currently disabled. Toggle "));
        var toggleEmulationButton = new WebInspector.StatusBarButton("", "emulation-status-bar-item");
        toggleEmulationButton.addEventListener("click", this._toggleEmulationEnabled, this);
        this._splashScreenElement.appendChild(toggleEmulationButton.element);
        this._splashScreenElement.createTextChild(WebInspector.UIString("in the main toolbar to enable it."));
    } else {
        var toggleEmulationButton = this._splashScreenElement.createChild("button", "text-button overrides-enable-button");
        toggleEmulationButton.textContent = WebInspector.UIString("Enable emulation");
        toggleEmulationButton.addEventListener("click", this._toggleEmulationEnabled.bind(this), false);
    }
    this._warningFooter = this.element.createChild("div", "overrides-footer");
    this._overridesWarningUpdated();
    WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.OverridesWarningUpdated, this._overridesWarningUpdated, this);
    WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.EmulationStateChanged, this._emulationStateChanged, this);
    this._emulationStateChanged();
}
WebInspector.OverridesView.prototype = {
    _tabSelected: function (event) {
        this._lastSelectedTabSetting.set(this._tabbedPane.selectedTabId);
    }, _overridesWarningUpdated: function () {
        var message = WebInspector.overridesSupport.warningMessage();
        this._warningFooter.classList.toggle("hidden", !message);
        this._warningFooter.textContent = message;
    }, _toggleEmulationEnabled: function () {
        WebInspector.overridesSupport.setEmulationEnabled(!WebInspector.overridesSupport.emulationEnabled());
    }, _emulationStateChanged: function () {
        this._unavailableSplashScreenElement.classList.toggle("hidden", WebInspector.overridesSupport.canEmulate());
        this._tabbedPane.element.classList.toggle("hidden", !WebInspector.overridesSupport.emulationEnabled());
        this._splashScreenElement.classList.toggle("hidden", WebInspector.overridesSupport.emulationEnabled());
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.OverridesView.Tab = function (id, name, settings, predicates) {
    WebInspector.VBox.call(this);
    this._id = id;
    this._name = name;
    this._settings = settings;
    this._predicates = predicates || [];
    for (var i = 0; i < settings.length; ++i)
        settings[i].addChangeListener(this.updateActiveState, this);
}
WebInspector.OverridesView.Tab.prototype = {
    appendAsTab: function (tabbedPane) {
        this._tabbedPane = tabbedPane;
        tabbedPane.appendTab(this._id, this._name, this);
        this.updateActiveState();
    }, updateActiveState: function () {
        if (!this._tabbedPane)
            return;
        var active = false;
        for (var i = 0; !active && i < this._settings.length; ++i)
            active = this._settings[i].get();
        for (var i = 0; !active && i < this._predicates.length; ++i)
            active = this._predicates[i]();
        this._tabbedPane.element.classList.toggle("overrides-activate-" + this._id, active);
    }, _createSettingCheckbox: function (name, setting, callback) {
        var checkbox = WebInspector.SettingsUI.createSettingCheckbox(name, setting, true);

        function changeListener(value) {
            callback(setting.get());
        }

        if (callback)
            setting.addChangeListener(changeListener);
        return checkbox;
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.OverridesView.DeviceTab = function () {
    WebInspector.OverridesView.Tab.call(this, "device", WebInspector.UIString("Device"), [WebInspector.overridesSupport.settings.emulateResolution, WebInspector.overridesSupport.settings.deviceScaleFactor, WebInspector.overridesSupport.settings.emulateMobile]);
    this.element.classList.add("overrides-device");
    this.element.appendChild(this._createDeviceElement());
    var footnote = this.element.createChild("p", "help-footnote");
    var footnoteLink = footnote.createChild("a");
    footnoteLink.href = "https://developers.google.com/chrome-developer-tools/docs/mobile-emulation";
    footnoteLink.target = "_blank";
    footnoteLink.createTextChild(WebInspector.UIString("More information about screen emulation"));
}
WebInspector.OverridesView.DeviceTab.prototype = {
    _createDeviceElement: function () {
        var fieldsetElement = document.createElement("fieldset");
        fieldsetElement.id = "metrics-override-section";
        var deviceModelElement = fieldsetElement.createChild("p", "overrides-device-model-section");
        deviceModelElement.createChild("span").textContent = WebInspector.UIString("Model:");
        var deviceSelectElement = WebInspector.OverridesUI.createDeviceSelect(document, this._showTitleDialog.bind(this));
        var buttons = deviceSelectElement.querySelectorAll("button");
        for (var i = 0; i < buttons.length; ++i)
            buttons[i].classList.add("text-button");
        deviceModelElement.appendChild(deviceSelectElement);
        var emulateResolutionCheckbox = WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Emulate screen resolution"), WebInspector.overridesSupport.settings.emulateResolution, true);
        fieldsetElement.appendChild(emulateResolutionCheckbox);
        var resolutionFieldset = WebInspector.SettingsUI.createSettingFieldset(WebInspector.overridesSupport.settings.emulateResolution);
        fieldsetElement.appendChild(resolutionFieldset);
        var tableElement = resolutionFieldset.createChild("table", "nowrap");
        var rowElement = tableElement.createChild("tr");
        var cellElement = rowElement.createChild("td");
        cellElement.appendChild(document.createTextNode(WebInspector.UIString("Resolution:")));
        cellElement = rowElement.createChild("td");
        var widthOverrideInput = WebInspector.SettingsUI.createSettingInputField("", WebInspector.overridesSupport.settings.deviceWidth, true, 4, "80px", WebInspector.OverridesSupport.deviceSizeValidator, true, true, WebInspector.UIString("\u2013"));
        cellElement.appendChild(widthOverrideInput);
        this._swapDimensionsElement = cellElement.createChild("button", "overrides-swap");
        this._swapDimensionsElement.appendChild(document.createTextNode(" \u21C4 "));
        this._swapDimensionsElement.title = WebInspector.UIString("Swap dimensions");
        this._swapDimensionsElement.addEventListener("click", WebInspector.overridesSupport.swapDimensions.bind(WebInspector.overridesSupport), false);
        this._swapDimensionsElement.tabIndex = -1;
        var heightOverrideInput = WebInspector.SettingsUI.createSettingInputField("", WebInspector.overridesSupport.settings.deviceHeight, true, 4, "80px", WebInspector.OverridesSupport.deviceSizeValidator, true, true, WebInspector.UIString("\u2013"));
        cellElement.appendChild(heightOverrideInput);
        rowElement = tableElement.createChild("tr");
        cellElement = rowElement.createChild("td");
        cellElement.colSpan = 4;
        rowElement = tableElement.createChild("tr");
        rowElement.title = WebInspector.UIString("Ratio between a device's physical pixels and device-independent pixels.");
        rowElement.createChild("td").appendChild(document.createTextNode(WebInspector.UIString("Device pixel ratio:")));
        rowElement.createChild("td").appendChild(WebInspector.SettingsUI.createSettingInputField("", WebInspector.overridesSupport.settings.deviceScaleFactor, true, 4, "80px", WebInspector.OverridesSupport.deviceScaleFactorValidator, true, true, WebInspector.UIString("\u2013")));
        var mobileCheckbox = this._createSettingCheckbox(WebInspector.UIString("Emulate mobile"), WebInspector.overridesSupport.settings.emulateMobile);
        mobileCheckbox.title = WebInspector.UIString("Enable meta viewport, overlay scrollbars, text autosizing and default 980px body width");
        fieldsetElement.appendChild(mobileCheckbox);
        fieldsetElement.appendChild(this._createSettingCheckbox(WebInspector.UIString("Shrink to fit"), WebInspector.overridesSupport.settings.deviceFitWindow));
        return fieldsetElement;
    }, _showTitleDialog: function (callback) {
        WebInspector.Dialog.show(this.element, new WebInspector.OverridesView.DeviceTab.CustomDeviceTitleDialog(callback));
    }, __proto__: WebInspector.OverridesView.Tab.prototype
}
WebInspector.OverridesView.DeviceTab.CustomDeviceTitleDialog = function (callback) {
    WebInspector.DialogDelegate.call(this);
    this.element = document.createElementWithClass("div", "custom-device-title-dialog");
    this.element.createChild("label").textContent = WebInspector.UIString("Save as: ");
    this._input = this.element.createChild("input");
    this._input.setAttribute("type", "text");
    this._input.placeholder = WebInspector.UIString("device model name");
    this._input.addEventListener("input", this._onInput.bind(this), false);
    this._saveButton = this.element.createChild("button");
    this._saveButton.textContent = WebInspector.UIString("Save");
    this._saveButton.addEventListener("click", this._onSaveClick.bind(this), false);
    this._callback = callback;
    this._result = "";
    this._onInput();
}
WebInspector.OverridesView.DeviceTab.CustomDeviceTitleDialog.prototype = {
    focus: function () {
        WebInspector.setCurrentFocusElement(this._input);
        this._input.select();
    }, _onSaveClick: function () {
        this._result = this._input.value.trim();
        WebInspector.Dialog.hide();
    }, _onInput: function () {
        this._saveButton.disabled = !this._input.value.trim();
    }, onEnter: function (event) {
        if (this._input.value.trim()) {
            this._result = this._input.value.trim();
        } else {
            event.consume();
        }
    }, willHide: function () {
        this._callback(this._result);
    }, __proto__: WebInspector.DialogDelegate.prototype
}
WebInspector.OverridesView.MediaTab = function () {
    var settings = [WebInspector.overridesSupport.settings.overrideCSSMedia];
    WebInspector.OverridesView.Tab.call(this, "media", WebInspector.UIString("Media"), settings);
    this.element.classList.add("overrides-media");
    this._createMediaEmulationFragment();
}
WebInspector.OverridesView.MediaTab.prototype = {
    _createMediaEmulationFragment: function () {
        var checkbox = WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("CSS media"), WebInspector.overridesSupport.settings.overrideCSSMedia, true);
        var fieldsetElement = WebInspector.SettingsUI.createSettingFieldset(WebInspector.overridesSupport.settings.overrideCSSMedia);
        var mediaSelectElement = fieldsetElement.createChild("select");
        var mediaTypes = WebInspector.CSSStyleModel.MediaTypes;
        var defaultMedia = WebInspector.overridesSupport.settings.emulatedCSSMedia.get();
        for (var i = 0; i < mediaTypes.length; ++i) {
            var mediaType = mediaTypes[i];
            if (mediaType === "all") {
                continue;
            }
            var option = document.createElement("option");
            option.text = mediaType;
            option.value = mediaType;
            mediaSelectElement.add(option);
            if (mediaType === defaultMedia)
                mediaSelectElement.selectedIndex = mediaSelectElement.options.length - 1;
        }
        mediaSelectElement.addEventListener("change", this._emulateMediaChanged.bind(this, mediaSelectElement), false);
        var fragment = document.createDocumentFragment();
        fragment.appendChild(checkbox);
        fragment.appendChild(fieldsetElement);
        this.element.appendChild(fragment);
    }, _emulateMediaChanged: function (select) {
        var media = select.options[select.selectedIndex].value;
        WebInspector.overridesSupport.settings.emulatedCSSMedia.set(media);
    }, __proto__: WebInspector.OverridesView.Tab.prototype
}
WebInspector.OverridesView.NetworkTab = function () {
    WebInspector.OverridesView.Tab.call(this, "network", WebInspector.UIString("Network"), [], [this._userAgentOverrideEnabled.bind(this), this._networkThroughputIsLimited.bind(this)]);
    this.element.classList.add("overrides-network");
    this._createNetworkConditionsElement();
    this._createUserAgentSection();
}
WebInspector.OverridesView.NetworkTab.prototype = {
    _networkThroughputIsLimited: function () {
        return WebInspector.overridesSupport.networkThroughputIsLimited();
    }, _createNetworkConditionsElement: function () {
        var fieldsetElement = this.element.createChild("fieldset");
        fieldsetElement.createChild("span").textContent = WebInspector.UIString("Limit network throughput:");
        fieldsetElement.createChild("br");
        fieldsetElement.appendChild(WebInspector.OverridesUI.createNetworkConditionsSelect(document));
        WebInspector.overridesSupport.settings.networkConditions.addChangeListener(this.updateActiveState, this);
    }, _userAgentOverrideEnabled: function () {
        return !!WebInspector.overridesSupport.settings.userAgent.get();
    }, _createUserAgentSection: function () {
        var fieldsetElement = this.element.createChild("fieldset");
        fieldsetElement.createChild("label").textContent = WebInspector.UIString("Spoof user agent:");
        var selectAndInput = WebInspector.OverridesUI.createUserAgentSelectAndInput(document);
        fieldsetElement.appendChild(selectAndInput.select);
        fieldsetElement.appendChild(selectAndInput.input);
        WebInspector.overridesSupport.settings.userAgent.addChangeListener(this.updateActiveState, this);
    }, __proto__: WebInspector.OverridesView.Tab.prototype
}
WebInspector.OverridesView.SensorsTab = function () {
    WebInspector.OverridesView.Tab.call(this, "sensors", WebInspector.UIString("Sensors"), [WebInspector.overridesSupport.settings.overrideGeolocation, WebInspector.overridesSupport.settings.overrideDeviceOrientation, WebInspector.overridesSupport.settings.emulateTouch]);
    this.element.classList.add("overrides-sensors");
    this.registerRequiredCSS("accelerometer.css");
    this.element.appendChild(this._createSettingCheckbox(WebInspector.UIString("Emulate touch screen"), WebInspector.overridesSupport.settings.emulateTouch, undefined));
    this._appendGeolocationOverrideControl();
    this._apendDeviceOrientationOverrideControl();
}
WebInspector.OverridesView.SensorsTab.prototype = {
    _appendGeolocationOverrideControl: function () {
        const geolocationSetting = WebInspector.overridesSupport.settings.geolocationOverride.get();
        var geolocation = WebInspector.OverridesSupport.GeolocationPosition.parseSetting(geolocationSetting);
        this.element.appendChild(this._createSettingCheckbox(WebInspector.UIString("Emulate geolocation coordinates"), WebInspector.overridesSupport.settings.overrideGeolocation, this._geolocationOverrideCheckboxClicked.bind(this)));
        this.element.appendChild(this._createGeolocationOverrideElement(geolocation));
        this._geolocationOverrideCheckboxClicked(WebInspector.overridesSupport.settings.overrideGeolocation.get());
    }, _geolocationOverrideCheckboxClicked: function (enabled) {
        if (enabled && !this._latitudeElement.value)
            this._latitudeElement.focus();
    }, _applyGeolocationUserInput: function () {
        this._setGeolocationPosition(WebInspector.OverridesSupport.GeolocationPosition.parseUserInput(this._latitudeElement.value.trim(), this._longitudeElement.value.trim(), this._geolocationErrorElement.checked), true);
    }, _setGeolocationPosition: function (geolocation, userInputModified) {
        if (!geolocation)
            return;
        if (!userInputModified) {
            this._latitudeElement.value = geolocation.latitude;
            this._longitudeElement.value = geolocation.longitude;
        }
        var value = geolocation.toSetting();
        WebInspector.overridesSupport.settings.geolocationOverride.set(value);
    }, _createGeolocationOverrideElement: function (geolocation) {
        var fieldsetElement = WebInspector.SettingsUI.createSettingFieldset(WebInspector.overridesSupport.settings.overrideGeolocation);
        fieldsetElement.id = "geolocation-override-section";
        var tableElement = fieldsetElement.createChild("table");
        var rowElement = tableElement.createChild("tr");
        var cellElement = rowElement.createChild("td");
        cellElement = rowElement.createChild("td");
        cellElement.appendChild(document.createTextNode(WebInspector.UIString("Lat = ")));
        this._latitudeElement = WebInspector.SettingsUI.createInput(cellElement, "geolocation-override-latitude", String(geolocation.latitude), this._applyGeolocationUserInput.bind(this), true);
        cellElement.appendChild(document.createTextNode(" , "));
        cellElement.appendChild(document.createTextNode(WebInspector.UIString("Lon = ")));
        this._longitudeElement = WebInspector.SettingsUI.createInput(cellElement, "geolocation-override-longitude", String(geolocation.longitude), this._applyGeolocationUserInput.bind(this), true);
        rowElement = tableElement.createChild("tr");
        cellElement = rowElement.createChild("td");
        cellElement.colSpan = 2;
        var geolocationErrorLabelElement = document.createElement("label");
        var geolocationErrorCheckboxElement = geolocationErrorLabelElement.createChild("input");
        geolocationErrorCheckboxElement.id = "geolocation-error";
        geolocationErrorCheckboxElement.type = "checkbox";
        geolocationErrorCheckboxElement.checked = !geolocation || geolocation.error;
        geolocationErrorCheckboxElement.addEventListener("click", this._applyGeolocationUserInput.bind(this), false);
        geolocationErrorLabelElement.appendChild(document.createTextNode(WebInspector.UIString("Emulate position unavailable")));
        this._geolocationErrorElement = geolocationErrorCheckboxElement;
        cellElement.appendChild(geolocationErrorLabelElement);
        return fieldsetElement;
    }, _apendDeviceOrientationOverrideControl: function () {
        const deviceOrientationSetting = WebInspector.overridesSupport.settings.deviceOrientationOverride.get();
        var deviceOrientation = WebInspector.OverridesSupport.DeviceOrientation.parseSetting(deviceOrientationSetting);
        this.element.appendChild(this._createSettingCheckbox(WebInspector.UIString("Accelerometer"), WebInspector.overridesSupport.settings.overrideDeviceOrientation, this._deviceOrientationOverrideCheckboxClicked.bind(this)));
        this.element.appendChild(this._createDeviceOrientationOverrideElement(deviceOrientation));
        this._deviceOrientationOverrideCheckboxClicked(WebInspector.overridesSupport.settings.overrideDeviceOrientation.get());
    }, _deviceOrientationOverrideCheckboxClicked: function (enabled) {
        if (enabled && !this._alphaElement.value)
            this._alphaElement.focus();
    }, _applyDeviceOrientationUserInput: function () {
        this._setDeviceOrientation(WebInspector.OverridesSupport.DeviceOrientation.parseUserInput(this._alphaElement.value.trim(), this._betaElement.value.trim(), this._gammaElement.value.trim()), WebInspector.OverridesView.SensorsTab.DeviceOrientationModificationSource.UserInput);
    }, _resetDeviceOrientation: function () {
        this._setDeviceOrientation(new WebInspector.OverridesSupport.DeviceOrientation(0, 0, 0), WebInspector.OverridesView.SensorsTab.DeviceOrientationModificationSource.ResetButton);
    }, _setDeviceOrientation: function (deviceOrientation, modificationSource) {
        if (!deviceOrientation)
            return;
        if (modificationSource != WebInspector.OverridesView.SensorsTab.DeviceOrientationModificationSource.UserInput) {
            this._alphaElement.value = deviceOrientation.alpha;
            this._betaElement.value = deviceOrientation.beta;
            this._gammaElement.value = deviceOrientation.gamma;
        }
        if (modificationSource != WebInspector.OverridesView.SensorsTab.DeviceOrientationModificationSource.UserDrag)
            this._setBoxOrientation(deviceOrientation);
        var value = deviceOrientation.toSetting();
        WebInspector.overridesSupport.settings.deviceOrientationOverride.set(value);
    }, _createAxisInput: function (parentElement, id, label, defaultText) {
        var div = parentElement.createChild("div", "accelerometer-axis-input-container");
        div.appendChild(document.createTextNode(label));
        return WebInspector.SettingsUI.createInput(div, id, defaultText, this._applyDeviceOrientationUserInput.bind(this), true);
    }, _createDeviceOrientationOverrideElement: function (deviceOrientation) {
        var fieldsetElement = WebInspector.SettingsUI.createSettingFieldset(WebInspector.overridesSupport.settings.overrideDeviceOrientation);
        fieldsetElement.id = "device-orientation-override-section";
        var tableElement = fieldsetElement.createChild("table");
        var rowElement = tableElement.createChild("tr");
        var cellElement = rowElement.createChild("td", "accelerometer-inputs-cell");
        this._alphaElement = this._createAxisInput(cellElement, "device-orientation-override-alpha", "\u03B1: ", String(deviceOrientation.alpha));
        this._betaElement = this._createAxisInput(cellElement, "device-orientation-override-beta", "\u03B2: ", String(deviceOrientation.beta));
        this._gammaElement = this._createAxisInput(cellElement, "device-orientation-override-gamma", "\u03B3: ", String(deviceOrientation.gamma));
        var resetButton = cellElement.createChild("button", "text-button accelerometer-reset-button");
        resetButton.textContent = WebInspector.UIString("Reset");
        resetButton.addEventListener("click", this._resetDeviceOrientation.bind(this), false);
        this._stageElement = rowElement.createChild("td", "accelerometer-stage");
        this._boxElement = this._stageElement.createChild("section", "accelerometer-box");
        this._boxElement.createChild("section", "front");
        this._boxElement.createChild("section", "top");
        this._boxElement.createChild("section", "back");
        this._boxElement.createChild("section", "left");
        this._boxElement.createChild("section", "right");
        this._boxElement.createChild("section", "bottom");
        WebInspector.installDragHandle(this._stageElement, this._onBoxDragStart.bind(this), this._onBoxDrag.bind(this), this._onBoxDragEnd.bind(this), "move");
        this._setBoxOrientation(deviceOrientation);
        return fieldsetElement;
    }, _setBoxOrientation: function (deviceOrientation) {
        var matrix = new WebKitCSSMatrix();
        this._boxMatrix = matrix.rotate(-deviceOrientation.beta, deviceOrientation.gamma, -deviceOrientation.alpha);
        this._boxElement.style.webkitTransform = this._boxMatrix.toString();
    }, _onBoxDrag: function (event) {
        var mouseMoveVector = this._calculateRadiusVector(event.x, event.y);
        if (!mouseMoveVector)
            return true;
        event.consume(true);
        var axis = WebInspector.Geometry.crossProduct(this._mouseDownVector, mouseMoveVector);
        axis.normalize();
        var angle = WebInspector.Geometry.calculateAngle(this._mouseDownVector, mouseMoveVector);
        var matrix = new WebKitCSSMatrix();
        var rotationMatrix = matrix.rotateAxisAngle(axis.x, axis.y, axis.z, angle);
        this._currentMatrix = rotationMatrix.multiply(this._boxMatrix)
        this._boxElement.style.webkitTransform = this._currentMatrix;
        var eulerAngles = WebInspector.Geometry.EulerAngles.fromRotationMatrix(this._currentMatrix);
        var newOrientation = new WebInspector.OverridesSupport.DeviceOrientation(-eulerAngles.alpha, -eulerAngles.beta, eulerAngles.gamma);
        this._setDeviceOrientation(newOrientation, WebInspector.OverridesView.SensorsTab.DeviceOrientationModificationSource.UserDrag);
        return false;
    }, _onBoxDragStart: function (event) {
        if (!WebInspector.overridesSupport.settings.overrideDeviceOrientation.get())
            return false;
        this._mouseDownVector = this._calculateRadiusVector(event.x, event.y);
        if (!this._mouseDownVector)
            return false;
        event.consume(true);
        return true;
    }, _onBoxDragEnd: function () {
        this._boxMatrix = this._currentMatrix;
    }, _calculateRadiusVector: function (x, y) {
        var rect = this._stageElement.getBoundingClientRect();
        var radius = Math.max(rect.width, rect.height) / 2;
        var sphereX = (x - rect.left - rect.width / 2) / radius;
        var sphereY = (y - rect.top - rect.height / 2) / radius;
        var sqrSum = sphereX * sphereX + sphereY * sphereY;
        if (sqrSum > 0.5)
            return new WebInspector.Geometry.Vector(sphereX, sphereY, 0.5 / Math.sqrt(sqrSum));
        return new WebInspector.Geometry.Vector(sphereX, sphereY, Math.sqrt(1 - sqrSum));
    }, __proto__: WebInspector.OverridesView.Tab.prototype
}
WebInspector.OverridesView.SensorsTab.DeviceOrientationModificationSource = {UserInput: "userInput", UserDrag: "userDrag", ResetButton: "resetButton"}
WebInspector.OverridesView.Revealer = function () {
}
WebInspector.OverridesView.Revealer.prototype = {
    reveal: function (overridesSupport) {
        WebInspector.inspectorView.showViewInDrawer("emulation");
    }
}
WebInspector.ZoomManager = function (frontendHost) {
    this._frontendHost = frontendHost;
    this._zoomFactor = this._frontendHost.zoomFactor();
    window.addEventListener("resize", this._onWindowResize.bind(this), true);
};
WebInspector.ZoomManager.Events = {ZoomChanged: "ZoomChanged"};
WebInspector.ZoomManager.prototype = {
    zoomFactor: function () {
        return this._zoomFactor;
    }, _onWindowResize: function () {
        var oldZoomFactor = this._zoomFactor;
        this._zoomFactor = this._frontendHost.zoomFactor();
        if (oldZoomFactor !== this._zoomFactor)
            this.dispatchEventToListeners(WebInspector.ZoomManager.Events.ZoomChanged, {from: oldZoomFactor, to: this._zoomFactor});
    }, __proto__: WebInspector.Object.prototype
};
WebInspector.zoomManager;
WebInspector.ScreencastView = function (target) {
    WebInspector.VBox.call(this);
    this._target = target;
    this.setMinimumSize(150, 150);
    this.registerRequiredCSS("screencastView.css");
};
WebInspector.ScreencastView._bordersSize = 44;
WebInspector.ScreencastView._navBarHeight = 29;
WebInspector.ScreencastView._HttpRegex = /^https?:\/\/(.+)/;
WebInspector.ScreencastView.prototype = {
    initialize: function () {
        this.element.classList.add("screencast");
        this._createNavigationBar();
        this._viewportElement = this.element.createChild("div", "screencast-viewport hidden");
        this._canvasContainerElement = this._viewportElement.createChild("div", "screencast-canvas-container");
        this._glassPaneElement = this._canvasContainerElement.createChild("div", "screencast-glasspane hidden");
        this._canvasElement = this._canvasContainerElement.createChild("canvas");
        this._canvasElement.tabIndex = 1;
        this._canvasElement.addEventListener("mousedown", this._handleMouseEvent.bind(this), false);
        this._canvasElement.addEventListener("mouseup", this._handleMouseEvent.bind(this), false);
        this._canvasElement.addEventListener("mousemove", this._handleMouseEvent.bind(this), false);
        this._canvasElement.addEventListener("mousewheel", this._handleMouseEvent.bind(this), false);
        this._canvasElement.addEventListener("click", this._handleMouseEvent.bind(this), false);
        this._canvasElement.addEventListener("contextmenu", this._handleContextMenuEvent.bind(this), false);
        this._canvasElement.addEventListener("keydown", this._handleKeyEvent.bind(this), false);
        this._canvasElement.addEventListener("keyup", this._handleKeyEvent.bind(this), false);
        this._canvasElement.addEventListener("keypress", this._handleKeyEvent.bind(this), false);
        this._canvasElement.addEventListener("blur", this._handleBlurEvent.bind(this), false);
        this._titleElement = this._canvasContainerElement.createChild("div", "screencast-element-title monospace hidden");
        this._tagNameElement = this._titleElement.createChild("span", "screencast-tag-name");
        this._nodeIdElement = this._titleElement.createChild("span", "screencast-node-id");
        this._classNameElement = this._titleElement.createChild("span", "screencast-class-name");
        this._titleElement.appendChild(document.createTextNode(" "));
        this._nodeWidthElement = this._titleElement.createChild("span");
        this._titleElement.createChild("span", "screencast-px").textContent = "px";
        this._titleElement.appendChild(document.createTextNode(" \u00D7 "));
        this._nodeHeightElement = this._titleElement.createChild("span");
        this._titleElement.createChild("span", "screencast-px").textContent = "px";
        this._imageElement = new Image();
        this._isCasting = false;
        this._context = this._canvasElement.getContext("2d");
        this._checkerboardPattern = this._createCheckerboardPattern(this._context);
        this._shortcuts = ({});
        this._shortcuts[WebInspector.KeyboardShortcut.makeKey("l", WebInspector.KeyboardShortcut.Modifiers.Ctrl)] = this._focusNavigationBar.bind(this);
        WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.ScreencastFrame, this._screencastFrame, this);
        WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.ScreencastVisibilityChanged, this._screencastVisibilityChanged, this);
        WebInspector.profilingLock().addEventListener(WebInspector.Lock.Events.StateChanged, this._onProfilingStateChange, this);
        this._updateGlasspane();
    }, wasShown: function () {
        this._startCasting();
    }, willHide: function () {
        this._stopCasting();
    }, _startCasting: function () {
        if (WebInspector.profilingLock().isAcquired())
            return;
        if (this._isCasting)
            return;
        this._isCasting = true;
        const maxImageDimension = 2048;
        var dimensions = this._viewportDimensions();
        if (dimensions.width < 0 || dimensions.height < 0) {
            this._isCasting = false;
            return;
        }
        dimensions.width *= window.devicePixelRatio;
        dimensions.height *= window.devicePixelRatio;
        this._target.pageAgent().startScreencast("jpeg", 80, Math.min(maxImageDimension, dimensions.width), Math.min(maxImageDimension, dimensions.height));
        this._target.domModel.setHighlighter(this);
    }, _stopCasting: function () {
        if (!this._isCasting)
            return;
        this._isCasting = false;
        this._target.pageAgent().stopScreencast();
        this._target.domModel.setHighlighter(null);
    }, _screencastFrame: function (event) {
        var metadata = (event.data.metadata);
        var base64Data = (event.data.data);
        this._imageElement.src = "data:image/jpg;base64," + base64Data;
        this._pageScaleFactor = metadata.pageScaleFactor;
        this._screenOffsetTop = metadata.offsetTop;
        this._deviceWidth = metadata.deviceWidth;
        this._deviceHeight = metadata.deviceHeight;
        this._scrollOffsetX = metadata.scrollOffsetX;
        this._scrollOffsetY = metadata.scrollOffsetY;
        var deviceSizeRatio = metadata.deviceHeight / metadata.deviceWidth;
        var dimensionsCSS = this._viewportDimensions();
        this._imageZoom = Math.min(dimensionsCSS.width / this._imageElement.naturalWidth, dimensionsCSS.height / (this._imageElement.naturalWidth * deviceSizeRatio));
        this._viewportElement.classList.remove("hidden");
        var bordersSize = WebInspector.ScreencastView._bordersSize;
        if (this._imageZoom < 1.01 / window.devicePixelRatio)
            this._imageZoom = 1 / window.devicePixelRatio;
        this._screenZoom = this._imageElement.naturalWidth * this._imageZoom / metadata.deviceWidth;
        this._viewportElement.style.width = metadata.deviceWidth * this._screenZoom + bordersSize + "px";
        this._viewportElement.style.height = metadata.deviceHeight * this._screenZoom + bordersSize + "px";
        this.highlightDOMNode(this._highlightNode, this._highlightConfig);
    }, _isGlassPaneActive: function () {
        return !this._glassPaneElement.classList.contains("hidden");
    }, _screencastVisibilityChanged: function (event) {
        this._targetInactive = !event.data.visible;
        this._updateGlasspane();
    }, _onProfilingStateChange: function (event) {
        if (WebInspector.profilingLock().isAcquired())
            this._stopCasting(); else
            this._startCasting();
        this._updateGlasspane();
    }, _updateGlasspane: function () {
        if (this._targetInactive) {
            this._glassPaneElement.textContent = WebInspector.UIString("The tab is inactive");
            this._glassPaneElement.classList.remove("hidden");
        } else if (WebInspector.profilingLock().isAcquired()) {
            this._glassPaneElement.textContent = WebInspector.UIString("Profiling in progress");
            this._glassPaneElement.classList.remove("hidden");
        } else {
            this._glassPaneElement.classList.add("hidden");
        }
    }, _handleMouseEvent: function (event) {
        if (this._isGlassPaneActive()) {
            event.consume();
            return;
        }
        if (!this._pageScaleFactor)
            return;
        if (!this._inspectModeConfig || event.type === "mousewheel") {
            this._simulateTouchForMouseEvent(event);
            event.preventDefault();
            if (event.type === "mousedown")
                this._canvasElement.focus();
            return;
        }
        var position = this._convertIntoScreenSpace(event);
        this._target.domModel.nodeForLocation(position.x / this._pageScaleFactor + this._scrollOffsetX, position.y / this._pageScaleFactor + this._scrollOffsetY, callback.bind(this));
        function callback(node) {
            if (!node)
                return;
            if (event.type === "mousemove")
                this.highlightDOMNode(node, this._inspectModeConfig); else if (event.type === "click")
                WebInspector.Revealer.reveal(node);
        }
    }, _handleKeyEvent: function (event) {
        if (this._isGlassPaneActive()) {
            event.consume();
            return;
        }
        var shortcutKey = WebInspector.KeyboardShortcut.makeKeyFromEvent((event));
        var handler = this._shortcuts[shortcutKey];
        if (handler && handler(event)) {
            event.consume();
            return;
        }
        var type;
        switch (event.type) {
            case"keydown":
                type = "keyDown";
                break;
            case"keyup":
                type = "keyUp";
                break;
            case"keypress":
                type = "char";
                break;
            default:
                return;
        }
        var text = event.type === "keypress" ? String.fromCharCode(event.charCode) : undefined;
        InputAgent.dispatchKeyEvent(type, this._modifiersForEvent(event), event.timeStamp / 1000, text, text ? text.toLowerCase() : undefined, event.keyIdentifier, event.keyCode, event.keyCode, false, false, false);
        event.consume();
        this._canvasElement.focus();
    }, _handleContextMenuEvent: function (event) {
        event.consume(true);
    }, _simulateTouchForMouseEvent: function (event) {
        const buttons = {0: "none", 1: "left", 2: "middle", 3: "right"};
        const types = {"mousedown": "mousePressed", "mouseup": "mouseReleased", "mousemove": "mouseMoved", "mousewheel": "mouseWheel"};
        if (!(event.type in types) || !(event.which in buttons))
            return;
        if (event.type !== "mousewheel" && buttons[event.which] === "none")
            return;
        if (event.type === "mousedown" || typeof this._eventScreenOffsetTop === "undefined")
            this._eventScreenOffsetTop = this._screenOffsetTop;
        var modifiers = (event.altKey ? 1 : 0) | (event.ctrlKey ? 2 : 0) | (event.metaKey ? 4 : 0) | (event.shiftKey ? 8 : 0);
        var convertedPosition = this._zoomIntoScreenSpace(event);
        convertedPosition.y = Math.round(convertedPosition.y - this._eventScreenOffsetTop);
        var params = {type: types[event.type], x: convertedPosition.x, y: convertedPosition.y, modifiers: modifiers, timestamp: event.timeStamp / 1000, button: buttons[event.which], clickCount: 0};
        if (event.type === "mousewheel") {
            params.deltaX = event.wheelDeltaX / this._screenZoom;
            params.deltaY = event.wheelDeltaY / this._screenZoom;
        } else {
            this._eventParams = params;
        }
        if (event.type === "mouseup")
            delete this._eventScreenOffsetTop;
        InputAgent.invoke_emulateTouchFromMouseEvent(params);
    }, _handleBlurEvent: function (event) {
        if (typeof this._eventScreenOffsetTop !== "undefined") {
            var params = this._eventParams;
            delete this._eventParams;
            params.type = "mouseReleased";
            InputAgent.invoke_emulateTouchFromMouseEvent(params);
        }
    }, _zoomIntoScreenSpace: function (event) {
        var position = {};
        position.x = Math.round(event.offsetX / this._screenZoom);
        position.y = Math.round(event.offsetY / this._screenZoom);
        return position;
    }, _convertIntoScreenSpace: function (event) {
        var position = this._zoomIntoScreenSpace(event);
        position.y = Math.round(position.y - this._screenOffsetTop);
        return position;
    }, _modifiersForEvent: function (event) {
        var modifiers = 0;
        if (event.altKey)
            modifiers = 1;
        if (event.ctrlKey)
            modifiers += 2;
        if (event.metaKey)
            modifiers += 4;
        if (event.shiftKey)
            modifiers += 8;
        return modifiers;
    }, onResize: function () {
        if (this._deferredCasting) {
            clearTimeout(this._deferredCasting);
            delete this._deferredCasting;
        }
        this._stopCasting();
        this._deferredCasting = setTimeout(this._startCasting.bind(this), 100);
    }, highlightDOMNode: function (node, config, objectId) {
        this._highlightNode = node;
        this._highlightConfig = config;
        if (!node) {
            this._model = null;
            this._config = null;
            this._node = null;
            this._titleElement.classList.add("hidden");
            this._repaint();
            return;
        }
        this._node = node;
        node.boxModel(callback.bind(this));
        function callback(model) {
            if (!model || !this._pageScaleFactor) {
                this._repaint();
                return;
            }
            this._model = this._scaleModel(model);
            this._config = config;
            this._repaint();
        }
    }, _scaleModel: function (model) {
        function scaleQuad(quad) {
            for (var i = 0; i < quad.length; i += 2) {
                quad[i] = quad[i] * this._pageScaleFactor * this._screenZoom;
                quad[i + 1] = (quad[i + 1] * this._pageScaleFactor + this._screenOffsetTop) * this._screenZoom;
            }
        }

        scaleQuad.call(this, model.content);
        scaleQuad.call(this, model.padding);
        scaleQuad.call(this, model.border);
        scaleQuad.call(this, model.margin);
        return model;
    }, _repaint: function () {
        var model = this._model;
        var config = this._config;
        var canvasWidth = this._canvasElement.getBoundingClientRect().width;
        var canvasHeight = this._canvasElement.getBoundingClientRect().height;
        this._canvasElement.width = window.devicePixelRatio * canvasWidth;
        this._canvasElement.height = window.devicePixelRatio * canvasHeight;
        this._context.save();
        this._context.scale(window.devicePixelRatio, window.devicePixelRatio);
        this._context.save();
        this._context.fillStyle = this._checkerboardPattern;
        this._context.fillRect(0, 0, canvasWidth, this._screenOffsetTop * this._screenZoom);
        this._context.fillRect(0, this._screenOffsetTop * this._screenZoom + this._imageElement.naturalHeight * this._imageZoom, canvasWidth, canvasHeight);
        this._context.restore();
        if (model && config) {
            this._context.save();
            const transparentColor = "rgba(0, 0, 0, 0)";
            var hasContent = model.content && config.contentColor !== transparentColor;
            var hasPadding = model.padding && config.paddingColor !== transparentColor;
            var hasBorder = model.border && config.borderColor !== transparentColor;
            var hasMargin = model.margin && config.marginColor !== transparentColor;
            var clipQuad;
            if (hasMargin && (!hasBorder || !this._quadsAreEqual(model.margin, model.border))) {
                this._drawOutlinedQuadWithClip(model.margin, model.border, config.marginColor);
                clipQuad = model.border;
            }
            if (hasBorder && (!hasPadding || !this._quadsAreEqual(model.border, model.padding))) {
                this._drawOutlinedQuadWithClip(model.border, model.padding, config.borderColor);
                clipQuad = model.padding;
            }
            if (hasPadding && (!hasContent || !this._quadsAreEqual(model.padding, model.content))) {
                this._drawOutlinedQuadWithClip(model.padding, model.content, config.paddingColor);
                clipQuad = model.content;
            }
            if (hasContent)
                this._drawOutlinedQuad(model.content, config.contentColor);
            this._context.restore();
            this._drawElementTitle();
            this._context.globalCompositeOperation = "destination-over";
        }
        this._context.drawImage(this._imageElement, 0, this._screenOffsetTop * this._screenZoom, this._imageElement.naturalWidth * this._imageZoom, this._imageElement.naturalHeight * this._imageZoom);
        this._context.restore();
    }, _quadsAreEqual: function (quad1, quad2) {
        for (var i = 0; i < quad1.length; ++i) {
            if (quad1[i] !== quad2[i])
                return false;
        }
        return true;
    }, _cssColor: function (color) {
        if (!color)
            return "transparent";
        return WebInspector.Color.fromRGBA([color.r, color.g, color.b, color.a]).toString(WebInspector.Color.Format.RGBA) || "";
    }, _quadToPath: function (quad) {
        this._context.beginPath();
        this._context.moveTo(quad[0], quad[1]);
        this._context.lineTo(quad[2], quad[3]);
        this._context.lineTo(quad[4], quad[5]);
        this._context.lineTo(quad[6], quad[7]);
        this._context.closePath();
        return this._context;
    }, _drawOutlinedQuad: function (quad, fillColor) {
        this._context.save();
        this._context.lineWidth = 2;
        this._quadToPath(quad).clip();
        this._context.fillStyle = this._cssColor(fillColor);
        this._context.fill();
        this._context.restore();
    }, _drawOutlinedQuadWithClip: function (quad, clipQuad, fillColor) {
        this._context.fillStyle = this._cssColor(fillColor);
        this._context.save();
        this._context.lineWidth = 0;
        this._quadToPath(quad).fill();
        this._context.globalCompositeOperation = "destination-out";
        this._context.fillStyle = "red";
        this._quadToPath(clipQuad).fill();
        this._context.restore();
    }, _drawElementTitle: function () {
        if (!this._node)
            return;
        var canvasWidth = this._canvasElement.getBoundingClientRect().width;
        var canvasHeight = this._canvasElement.getBoundingClientRect().height;
        var lowerCaseName = this._node.localName() || this._node.nodeName().toLowerCase();
        this._tagNameElement.textContent = lowerCaseName;
        this._nodeIdElement.textContent = this._node.getAttribute("id") ? "#" + this._node.getAttribute("id") : "";
        this._nodeIdElement.textContent = this._node.getAttribute("id") ? "#" + this._node.getAttribute("id") : "";
        var className = this._node.getAttribute("class");
        if (className && className.length > 50)
            className = className.substring(0, 50) + "\u2026";
        this._classNameElement.textContent = className || "";
        this._nodeWidthElement.textContent = this._model.width;
        this._nodeHeightElement.textContent = this._model.height;
        var marginQuad = this._model.margin;
        var titleWidth = this._titleElement.offsetWidth + 6;
        var titleHeight = this._titleElement.offsetHeight + 4;
        var anchorTop = this._model.margin[1];
        var anchorBottom = this._model.margin[7];
        const arrowHeight = 7;
        var renderArrowUp = false;
        var renderArrowDown = false;
        var boxX = Math.max(2, this._model.margin[0]);
        if (boxX + titleWidth > canvasWidth)
            boxX = canvasWidth - titleWidth - 2;
        var boxY;
        if (anchorTop > canvasHeight) {
            boxY = canvasHeight - titleHeight - arrowHeight;
            renderArrowDown = true;
        } else if (anchorBottom < 0) {
            boxY = arrowHeight;
            renderArrowUp = true;
        } else if (anchorBottom + titleHeight + arrowHeight < canvasHeight) {
            boxY = anchorBottom + arrowHeight - 4;
            renderArrowUp = true;
        } else if (anchorTop - titleHeight - arrowHeight > 0) {
            boxY = anchorTop - titleHeight - arrowHeight + 3;
            renderArrowDown = true;
        } else
            boxY = arrowHeight;
        this._context.save();
        this._context.translate(0.5, 0.5);
        this._context.beginPath();
        this._context.moveTo(boxX, boxY);
        if (renderArrowUp) {
            this._context.lineTo(boxX + 2 * arrowHeight, boxY);
            this._context.lineTo(boxX + 3 * arrowHeight, boxY - arrowHeight);
            this._context.lineTo(boxX + 4 * arrowHeight, boxY);
        }
        this._context.lineTo(boxX + titleWidth, boxY);
        this._context.lineTo(boxX + titleWidth, boxY + titleHeight);
        if (renderArrowDown) {
            this._context.lineTo(boxX + 4 * arrowHeight, boxY + titleHeight);
            this._context.lineTo(boxX + 3 * arrowHeight, boxY + titleHeight + arrowHeight);
            this._context.lineTo(boxX + 2 * arrowHeight, boxY + titleHeight);
        }
        this._context.lineTo(boxX, boxY + titleHeight);
        this._context.closePath();
        this._context.fillStyle = "rgb(255, 255, 194)";
        this._context.fill();
        this._context.strokeStyle = "rgb(128, 128, 128)";
        this._context.stroke();
        this._context.restore();
        this._titleElement.classList.remove("hidden");
        this._titleElement.style.top = (boxY + 3) + "px";
        this._titleElement.style.left = (boxX + 3) + "px";
    }, _viewportDimensions: function () {
        const gutterSize = 30;
        const bordersSize = WebInspector.ScreencastView._bordersSize;
        var width = this.element.offsetWidth - bordersSize - gutterSize;
        var height = this.element.offsetHeight - bordersSize - gutterSize - WebInspector.ScreencastView._navBarHeight;
        return {width: width, height: height};
    }, setInspectModeEnabled: function (enabled, inspectUAShadowDOM, config, callback) {
        this._inspectModeConfig = enabled ? config : null;
        if (callback)
            callback(null);
    }, _createCheckerboardPattern: function (context) {
        var pattern = (document.createElement("canvas"));
        const size = 32;
        pattern.width = size * 2;
        pattern.height = size * 2;
        var pctx = pattern.getContext("2d");
        pctx.fillStyle = "rgb(195, 195, 195)";
        pctx.fillRect(0, 0, size * 2, size * 2);
        pctx.fillStyle = "rgb(225, 225, 225)";
        pctx.fillRect(0, 0, size, size);
        pctx.fillRect(size, size, size, size);
        return context.createPattern(pattern, "repeat");
    }, _createNavigationBar: function () {
        this._navigationBar = this.element.createChild("div", "toolbar-background toolbar-colors screencast-navigation");
        if (WebInspector.queryParam("hideNavigation"))
            this._navigationBar.classList.add("hidden");
        this._navigationBack = this._navigationBar.createChild("button", "back");
        this._navigationBack.disabled = true;
        this._navigationBack.addEventListener("click", this._navigateToHistoryEntry.bind(this, -1), false);
        this._navigationForward = this._navigationBar.createChild("button", "forward");
        this._navigationForward.disabled = true;
        this._navigationForward.addEventListener("click", this._navigateToHistoryEntry.bind(this, 1), false);
        this._navigationReload = this._navigationBar.createChild("button", "reload");
        this._navigationReload.addEventListener("click", this._navigateReload.bind(this), false);
        this._navigationUrl = this._navigationBar.createChild("input");
        this._navigationUrl.type = "text";
        this._navigationUrl.addEventListener('keyup', this._navigationUrlKeyUp.bind(this), true);
        this._navigationProgressBar = new WebInspector.ScreencastView.ProgressTracker(this._navigationBar.createChild("div", "progress"));
        this._requestNavigationHistory();
        WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._requestNavigationHistory, this);
    }, _navigateToHistoryEntry: function (offset) {
        var newIndex = this._historyIndex + offset;
        if (newIndex < 0 || newIndex >= this._historyEntries.length)
            return;
        PageAgent.navigateToHistoryEntry(this._historyEntries[newIndex].id);
        this._requestNavigationHistory();
    }, _navigateReload: function () {
        WebInspector.resourceTreeModel.reloadPage();
    }, _navigationUrlKeyUp: function (event) {
        if (event.keyIdentifier != 'Enter')
            return;
        var url = this._navigationUrl.value;
        if (!url)
            return;
        if (!url.match(WebInspector.ScreencastView._HttpRegex))
            url = "http://" + url;
        PageAgent.navigate(url);
        this._canvasElement.focus();
    }, _requestNavigationHistory: function () {
        PageAgent.getNavigationHistory(this._onNavigationHistory.bind(this));
    }, _onNavigationHistory: function (error, currentIndex, entries) {
        if (error)
            return;
        this._historyIndex = currentIndex;
        this._historyEntries = entries;
        this._navigationBack.disabled = currentIndex == 0;
        this._navigationForward.disabled = currentIndex == (entries.length - 1);
        var url = entries[currentIndex].url;
        var match = url.match(WebInspector.ScreencastView._HttpRegex);
        if (match)
            url = match[1];
        InspectorFrontendHost.inspectedURLChanged(url);
        this._navigationUrl.value = url;
    }, _focusNavigationBar: function () {
        this._navigationUrl.focus();
        this._navigationUrl.select();
        return true;
    }, __proto__: WebInspector.VBox.prototype
}
WebInspector.ScreencastView.ProgressTracker = function (element) {
    this._element = element;
    WebInspector.targetManager.addModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._onMainFrameNavigated, this);
    WebInspector.targetManager.addModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.Load, this._onLoad, this);
    WebInspector.targetManager.addModelListener(WebInspector.NetworkManager, WebInspector.NetworkManager.EventTypes.RequestStarted, this._onRequestStarted, this);
    WebInspector.targetManager.addModelListener(WebInspector.NetworkManager, WebInspector.NetworkManager.EventTypes.RequestFinished, this._onRequestFinished, this);
}
WebInspector.ScreencastView.ProgressTracker.prototype = {
    _onMainFrameNavigated: function () {
        this._requestIds = {};
        this._startedRequests = 0;
        this._finishedRequests = 0;
        this._maxDisplayedProgress = 0;
        this._updateProgress(0.1);
    }, _onLoad: function () {
        delete this._requestIds;
        this._updateProgress(1);
        setTimeout(function () {
            if (!this._navigationProgressVisible())
                this._displayProgress(0);
        }.bind(this), 500);
    }, _navigationProgressVisible: function () {
        return !!this._requestIds;
    }, _onRequestStarted: function (event) {
        if (!this._navigationProgressVisible())
            return;
        var request = (event.data);
        if (request.type === WebInspector.resourceTypes.WebSocket)
            return;
        this._requestIds[request.requestId] = request;
        ++this._startedRequests;
    }, _onRequestFinished: function (event) {
        if (!this._navigationProgressVisible())
            return;
        var request = (event.data);
        if (!(request.requestId in this._requestIds))
            return;
        ++this._finishedRequests;
        setTimeout(function () {
            this._updateProgress(this._finishedRequests / this._startedRequests * 0.9);
        }.bind(this), 500);
    }, _updateProgress: function (progress) {
        if (!this._navigationProgressVisible())
            return;
        if (this._maxDisplayedProgress >= progress)
            return;
        this._maxDisplayedProgress = progress;
        this._displayProgress(progress);
    }, _displayProgress: function (progress) {
        this._element.style.width = (100 * progress) + "%";
    }
};
WebInspector.ResizerWidget = function () {
    WebInspector.Object.call(this);
    this._isEnabled = true;
    this._isVertical = true;
    this._elements = [];
    this._installDragOnMouseDownBound = this._installDragOnMouseDown.bind(this);
};
WebInspector.ResizerWidget.Events = {ResizeStart: "ResizeStart", ResizeUpdate: "ResizeUpdate", ResizeEnd: "ResizeEnd"};
WebInspector.ResizerWidget.prototype = {
    isEnabled: function () {
        return this._isEnabled;
    }, setEnabled: function (enabled) {
        this._isEnabled = enabled;
        this._updateElementsClass();
    }, isVertical: function () {
        return this._isVertical;
    }, setVertical: function (vertical) {
        this._isVertical = vertical;
        this._updateElementsClass();
    }, elements: function () {
        return this._elements.slice();
    }, addElement: function (element) {
        if (this._elements.indexOf(element) !== -1)
            return;
        this._elements.push(element);
        element.addEventListener("mousedown", this._installDragOnMouseDownBound, false);
        element.classList.toggle("ns-resizer-widget", this._isVertical && this._isEnabled);
        element.classList.toggle("ew-resizer-widget", !this._isVertical && this._isEnabled);
    }, removeElement: function (element) {
        if (this._elements.indexOf(element) === -1)
            return;
        this._elements.remove(element);
        element.removeEventListener("mousedown", this._installDragOnMouseDownBound, false);
        element.classList.remove("ns-resizer-widget");
        element.classList.remove("ew-resizer-widget");
    }, _updateElementsClass: function () {
        for (var i = 0; i < this._elements.length; ++i) {
            this._elements[i].classList.toggle("ns-resizer-widget", this._isVertical && this._isEnabled);
            this._elements[i].classList.toggle("ew-resizer-widget", !this._isVertical && this._isEnabled);
        }
    }, _installDragOnMouseDown: function (event) {
        if (this._elements.indexOf(event.target) === -1)
            return false;
        WebInspector.elementDragStart(this._dragStart.bind(this), this._drag.bind(this), this._dragEnd.bind(this), this._isVertical ? "ns-resize" : "ew-resize", event);
    }, _dragStart: function (event) {
        if (!this._isEnabled)
            return false;
        this._startPosition = this._isVertical ? event.pageY : event.pageX;
        this.dispatchEventToListeners(WebInspector.ResizerWidget.Events.ResizeStart, {startPosition: this._startPosition, currentPosition: this._startPosition});
        return true;
    }, _drag: function (event) {
        if (!this._isEnabled) {
            this._dragEnd(event);
            return true;
        }
        var position = this._isVertical ? event.pageY : event.pageX;
        this.dispatchEventToListeners(WebInspector.ResizerWidget.Events.ResizeUpdate, {startPosition: this._startPosition, currentPosition: position, shiftKey: event.shiftKey});
        event.preventDefault();
        return false;
    }, _dragEnd: function (event) {
        this.dispatchEventToListeners(WebInspector.ResizerWidget.Events.ResizeEnd);
        delete this._startPosition;
    }, __proto__: WebInspector.Object.prototype
};
WebInspector.InspectedPagePlaceholder = function () {
    WebInspector.View.call(this);
    this.element.classList.add("white-background");
    WebInspector.zoomManager.addEventListener(WebInspector.ZoomManager.Events.ZoomChanged, this._scheduleUpdate, this);
    this._margins = {top: 0, right: 0, bottom: 0, left: 0};
    this.restoreMinimumSizeAndMargins();
};
WebInspector.InspectedPagePlaceholder.Events = {Update: "Update"};
WebInspector.InspectedPagePlaceholder.MarginValue = 3;
WebInspector.InspectedPagePlaceholder.prototype = {
    _findMargins: function () {
        var margins = {top: 0, right: 0, bottom: 0, left: 0};
        if (this._useMargins) {
            var adjacent = {top: true, right: true, bottom: true, left: true};
            var view = this;
            while (view.parentView()) {
                var parent = view.parentView();
                if (parent instanceof WebInspector.SplitView) {
                    var side = parent.sidebarSide();
                    if (adjacent[side] && !parent.hasCustomResizer() && parent.isResizable())
                        margins[side] = WebInspector.InspectedPagePlaceholder.MarginValue;
                    adjacent[side] = false;
                }
                view = parent;
            }
        }
        if (this._margins.top !== margins.top || this._margins.left !== margins.left || this._margins.right !== margins.right || this._margins.bottom !== margins.bottom) {
            this._margins = margins;
            this._scheduleUpdate();
        }
    }, onResize: function () {
        this._findMargins();
        this._scheduleUpdate();
    }, _scheduleUpdate: function () {
        if (this._updateId)
            window.cancelAnimationFrame(this._updateId);
        this._updateId = window.requestAnimationFrame(this.update.bind(this));
    }, dipPageSize: function () {
        var rect = this._dipPageRect();
        return new Size(Math.round(rect.width), Math.round(rect.height));
    }, cssElementSize: function () {
        var zoomFactor = WebInspector.zoomManager.zoomFactor();
        var rect = this.element.getBoundingClientRect();
        var width = rect.width - (this._margins.left + this._margins.right) / zoomFactor;
        var height = rect.height - (this._margins.top + this._margins.bottom) / zoomFactor;
        return new Size(width, height);
    }, restoreMinimumSizeAndMargins: function () {
        this._useMargins = true;
        this.setMinimumSize(50, 50);
        this._findMargins();
    }, clearMinimumSizeAndMargins: function () {
        this._useMargins = false;
        this.setMinimumSize(1, 1);
        this._findMargins();
    }, _dipPageRect: function () {
        var zoomFactor = WebInspector.zoomManager.zoomFactor();
        var rect = this.element.getBoundingClientRect();
        var bodyRect = document.body.getBoundingClientRect();
        var left = Math.max(rect.left * zoomFactor + this._margins.left, bodyRect.left * zoomFactor);
        var top = Math.max(rect.top * zoomFactor + this._margins.top, bodyRect.top * zoomFactor);
        var bottom = Math.min(rect.bottom * zoomFactor - this._margins.bottom, bodyRect.bottom * zoomFactor);
        var right = Math.min(rect.right * zoomFactor - this._margins.right, bodyRect.right * zoomFactor);
        return {x: left, y: top, width: right - left, height: bottom - top};
    }, update: function () {
        delete this._updateId;
        var rect = this._dipPageRect();
        var bounds = {x: Math.round(rect.x), y: Math.round(rect.y), height: Math.max(1, Math.round(rect.height)), width: Math.max(1, Math.round(rect.width))};
        this.dispatchEventToListeners(WebInspector.InspectedPagePlaceholder.Events.Update, bounds);
    }, __proto__: WebInspector.View.prototype
};
WebInspector.MediaQueryInspector = function () {
    WebInspector.View.call(this);
    this.element.classList.add("media-inspector-view", "media-inspector-view-empty");
    this.element.addEventListener("click", this._onMediaQueryClicked.bind(this), false);
    this.element.addEventListener("contextmenu", this._onContextMenu.bind(this), false);
    this.element.addEventListener("webkitAnimationEnd", this._onAnimationEnd.bind(this), false);
    this._mediaThrottler = new WebInspector.Throttler(100);
    this._translateZero = 0;
    this._offset = 0;
    this._scale = 1;
    this._rulerDecorationLayer = document.createElementWithClass("div", "fill");
    this._rulerDecorationLayer.classList.add("media-inspector-ruler-decoration");
    this._rulerDecorationLayer.addEventListener("click", this._onRulerDecorationClicked.bind(this), false);
    WebInspector.targetManager.observeTargets(this);
    WebInspector.zoomManager.addEventListener(WebInspector.ZoomManager.Events.ZoomChanged, this._renderMediaQueries.bind(this), this);
}
WebInspector.MediaQueryInspector.Section = {Max: 0, MinMax: 1, Min: 2}
WebInspector.MediaQueryInspector.Events = {HeightUpdated: "HeightUpdated"}
WebInspector.MediaQueryInspector.prototype = {
    targetAdded: function (target) {
        if (this._target)
            return;
        this._target = target;
        target.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this);
        target.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this);
        target.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._scheduleMediaQueriesUpdate, this);
        target.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.MediaQueryResultChanged, this._scheduleMediaQueriesUpdate, this);
    }, targetRemoved: function (target) {
        if (target !== this._target)
            return;
        target.cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this);
        target.cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this);
        target.cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._scheduleMediaQueriesUpdate, this);
        target.cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.MediaQueryResultChanged, this._scheduleMediaQueriesUpdate, this);
    }, rulerDecorationLayer: function () {
        return this._rulerDecorationLayer;
    }, _mediaQueryThresholds: function () {
        if (!this._cachedQueryModels)
            return [];
        var thresholds = [];
        for (var i = 0; i < this._cachedQueryModels.length; ++i) {
            var model = this._cachedQueryModels[i];
            if (model.minWidthExpression())
                thresholds.push(model.minWidthExpression().computedLength());
            if (model.maxWidthExpression())
                thresholds.push(model.maxWidthExpression().computedLength());
        }
        thresholds.sortNumbers();
        return thresholds;
    }, _onRulerDecorationClicked: function (event) {
        var thresholdElement = event.target.enclosingNodeOrSelfWithClass("media-inspector-threshold-serif");
        if (!thresholdElement)
            return;
        WebInspector.settings.showMediaQueryInspector.set(true);
        var revealValue = thresholdElement._value;
        for (var mediaQueryContainer = this.element.firstChild; mediaQueryContainer; mediaQueryContainer = mediaQueryContainer.nextSibling) {
            var model = mediaQueryContainer._model;
            if ((model.minWidthExpression() && Math.abs(model.minWidthExpression().computedLength() - revealValue) === 0) || (model.maxWidthExpression() && Math.abs(model.maxWidthExpression().computedLength() - revealValue) === 0)) {
                mediaQueryContainer.scrollIntoViewIfNeeded(false);
                var hasRunningAnimation = mediaQueryContainer.classList.contains("media-inspector-marker-highlight-1") || mediaQueryContainer.classList.contains("media-inspector-marker-highlight-2");
                mediaQueryContainer.classList.toggle("media-inspector-marker-highlight-1");
                if (hasRunningAnimation)
                    mediaQueryContainer.classList.toggle("media-inspector-marker-highlight-2");
                return;
            }
        }
    }, _onAnimationEnd: function (event) {
        event.target.classList.remove("media-inspector-marker-highlight-1");
        event.target.classList.remove("media-inspector-marker-highlight-2");
    }, setAxisTransform: function (translate, offset, scale) {
        if (this._translateZero === translate && this._offset === offset && Math.abs(this._scale - scale) < 1e-8)
            return;
        this._translateZero = translate;
        this._offset = offset;
        this._scale = scale;
        this._renderMediaQueries();
    }, setEnabled: function (enabled) {
        this._enabled = enabled;
        this._scheduleMediaQueriesUpdate();
    }, _onMediaQueryClicked: function (event) {
        var mediaQueryMarkerContainer = event.target.enclosingNodeOrSelfWithClass("media-inspector-marker-container");
        if (!mediaQueryMarkerContainer)
            return;
        function setWidth(width) {
            WebInspector.overridesSupport.settings.deviceWidth.set(width);
            WebInspector.overridesSupport.settings.emulateResolution.set(true);
        }

        var model = mediaQueryMarkerContainer._model;
        if (model.section() === WebInspector.MediaQueryInspector.Section.Max) {
            setWidth(model.maxWidthExpression().computedLength());
            return;
        }
        if (model.section() === WebInspector.MediaQueryInspector.Section.Min) {
            setWidth(model.minWidthExpression().computedLength());
            return;
        }
        var currentWidth = WebInspector.overridesSupport.settings.deviceWidth.get();
        if (currentWidth !== model.minWidthExpression().computedLength())
            setWidth(model.minWidthExpression().computedLength()); else
            setWidth(model.maxWidthExpression().computedLength());
    }, _onContextMenu: function (event) {
        var mediaQueryMarkerContainer = event.target.enclosingNodeOrSelfWithClass("media-inspector-marker-container");
        if (!mediaQueryMarkerContainer)
            return;
        var locations = mediaQueryMarkerContainer._locations;
        var contextMenu = new WebInspector.ContextMenu(event);
        var subMenuItem = contextMenu.appendSubMenuItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Reveal in source code" : "Reveal In Source Code"));
        for (var i = 0; i < locations.length; ++i) {
            var location = locations[i];
            var title = String.sprintf("%s:%d:%d", location.uiSourceCode.uri(), location.lineNumber + 1, location.columnNumber + 1);
            subMenuItem.appendItem(title, this._revealSourceLocation.bind(this, location));
        }
        contextMenu.show();
    }, _revealSourceLocation: function (location) {
        WebInspector.Revealer.reveal(location);
    }, _scheduleMediaQueriesUpdate: function () {
        if (!this._enabled)
            return;
        this._mediaThrottler.schedule(this._refetchMediaQueries.bind(this));
    }, _refetchMediaQueries: function (finishCallback) {
        if (!this._enabled) {
            finishCallback();
            return;
        }
        function callback(cssMedias) {
            this._rebuildMediaQueries(cssMedias);
            finishCallback();
        }

        this._target.cssModel.getMediaQueries(callback.bind(this));
    }, _squashAdjacentEqual: function (models) {
        var filtered = [];
        for (var i = 0; i < models.length; ++i) {
            var last = filtered.peekLast();
            if (!last || !last.equals(models[i]))
                filtered.push(models[i]);
        }
        return filtered;
    }, _rebuildMediaQueries: function (cssMedias) {
        var queryModels = [];
        for (var i = 0; i < cssMedias.length; ++i) {
            var cssMedia = cssMedias[i];
            if (!cssMedia.mediaList)
                continue;
            for (var j = 0; j < cssMedia.mediaList.length; ++j) {
                var mediaQueryExpressions = cssMedia.mediaList[j];
                var queryModel = WebInspector.MediaQueryInspector.MediaQueryUIModel.createFromMediaExpressions(cssMedia, mediaQueryExpressions);
                if (queryModel)
                    queryModels.push(queryModel);
            }
        }
        queryModels.sort(compareModels);
        queryModels = this._squashAdjacentEqual(queryModels);
        var allEqual = this._cachedQueryModels && this._cachedQueryModels.length == queryModels.length;
        for (var i = 0; allEqual && i < queryModels.length; ++i)
            allEqual = allEqual && this._cachedQueryModels[i].equals(queryModels[i]);
        if (allEqual)
            return;
        this._cachedQueryModels = queryModels;
        this._renderMediaQueries();
        function compareModels(model1, model2) {
            return model1.compareTo(model2);
        }
    }, _renderMediaQueries: function () {
        if (!this._cachedQueryModels)
            return;
        this._renderRulerDecorations();
        if (!this.isShowing())
            return;
        var markers = [];
        var lastMarker = null;
        for (var i = 0; i < this._cachedQueryModels.length; ++i) {
            var model = this._cachedQueryModels[i];
            if (!model.uiLocation())
                continue;
            if (lastMarker && lastMarker.model.dimensionsEqual(model)) {
                lastMarker.locations.push(model.uiLocation());
            } else {
                lastMarker = {model: model, locations: [model.uiLocation()]};
                markers.push(lastMarker);
            }
        }
        var heightChanges = this.element.children.length !== markers.length;
        var scrollTop = this.element.scrollTop;
        this.element.removeChildren();
        for (var i = 0; i < markers.length; ++i) {
            var marker = markers[i];
            var bar = this._createElementFromMediaQueryModel(marker.model);
            bar._model = marker.model;
            bar._locations = marker.locations;
            this.element.appendChild(bar);
        }
        this.element.scrollTop = scrollTop;
        this.element.classList.toggle("media-inspector-view-empty", !this.element.children.length);
        if (heightChanges)
            this.dispatchEventToListeners(WebInspector.MediaQueryInspector.Events.HeightUpdated);
    }, _zoomFactor: function () {
        return WebInspector.zoomManager.zoomFactor() / this._scale;
    }, _renderRulerDecorations: function () {
        this._rulerDecorationLayer.removeChildren();
        var zoomFactor = this._zoomFactor();
        var thresholds = this._mediaQueryThresholds();
        for (var i = 0; i < thresholds.length; ++i) {
            var thresholdElement = this._rulerDecorationLayer.createChild("div", "media-inspector-threshold-serif");
            thresholdElement._value = thresholds[i];
            thresholdElement.style.left = (thresholds[i] - this._offset) / zoomFactor + "px";
        }
    }, wasShown: function () {
        this._renderMediaQueries();
    }, _createElementFromMediaQueryModel: function (model) {
        var zoomFactor = this._zoomFactor();
        var minWidthValue = model.minWidthExpression() ? model.minWidthExpression().computedLength() : 0;
        const styleClassPerSection = ["media-inspector-marker-container-max-width", "media-inspector-marker-container-min-max-width", "media-inspector-marker-container-min-width"];
        var container = document.createElementWithClass("div", "media-inspector-marker-container hbox");
        container.classList.add(styleClassPerSection[model.section()]);
        var markerElement = container.createChild("div", "media-inspector-marker");
        var leftPixelValue = minWidthValue ? (minWidthValue - this._offset) / zoomFactor + this._translateZero : 0;
        markerElement.style.left = leftPixelValue + "px";
        var widthPixelValue = null;
        if (model.maxWidthExpression() && model.minWidthExpression())
            widthPixelValue = (model.maxWidthExpression().computedLength() - minWidthValue) / zoomFactor; else if (model.maxWidthExpression())
            widthPixelValue = (model.maxWidthExpression().computedLength() - this._offset) / zoomFactor + this._translateZero; else
            markerElement.style.right = "0";
        if (typeof widthPixelValue === "number")
            markerElement.style.width = widthPixelValue + "px";
        var maxLabelFiller = container.createChild("div", "media-inspector-max-label-filler");
        if (model.maxWidthExpression()) {
            maxLabelFiller.style.maxWidth = Math.max(widthPixelValue + leftPixelValue, 0) + "px";
            var label = container.createChild("span", "media-inspector-marker-label media-inspector-max-label");
            label.textContent = model.maxWidthExpression().computedLength() + "px";
        }
        if (model.minWidthExpression()) {
            var minLabelFiller = maxLabelFiller.createChild("div", "media-inspector-min-label-filler");
            minLabelFiller.style.maxWidth = Math.max(leftPixelValue, 0) + "px";
            var label = minLabelFiller.createChild("span", "media-inspector-marker-label media-inspector-min-label");
            label.textContent = model.minWidthExpression().computedLength() + "px";
        }
        return container;
    }, __proto__: WebInspector.View.prototype
};
WebInspector.MediaQueryInspector.MediaQueryUIModel = function (cssMedia, minWidthExpression, maxWidthExpression) {
    this._cssMedia = cssMedia;
    this._minWidthExpression = minWidthExpression;
    this._maxWidthExpression = maxWidthExpression;
    if (maxWidthExpression && !minWidthExpression)
        this._section = WebInspector.MediaQueryInspector.Section.Max; else if (minWidthExpression && maxWidthExpression)
        this._section = WebInspector.MediaQueryInspector.Section.MinMax; else
        this._section = WebInspector.MediaQueryInspector.Section.Min;
}
WebInspector.MediaQueryInspector.MediaQueryUIModel.createFromMediaExpressions = function (cssMedia, mediaQueryExpressions) {
    var maxWidthExpression = null;
    var maxWidthPixels = Number.MAX_VALUE;
    var minWidthExpression = null;
    var minWidthPixels = Number.MIN_VALUE;
    for (var i = 0; i < mediaQueryExpressions.length; ++i) {
        var expression = mediaQueryExpressions[i];
        var feature = expression.feature();
        if (feature.indexOf("width") === -1)
            continue;
        var pixels = expression.computedLength();
        if (feature.startsWith("max-") && pixels < maxWidthPixels) {
            maxWidthExpression = expression;
            maxWidthPixels = pixels;
        } else if (feature.startsWith("min-") && pixels > minWidthPixels) {
            minWidthExpression = expression;
            minWidthPixels = pixels;
        }
    }
    if (minWidthPixels > maxWidthPixels || (!maxWidthExpression && !minWidthExpression))
        return null;
    return new WebInspector.MediaQueryInspector.MediaQueryUIModel(cssMedia, minWidthExpression, maxWidthExpression);
}
WebInspector.MediaQueryInspector.MediaQueryUIModel.prototype = {
    equals: function (other) {
        return this.compareTo(other) === 0;
    }, dimensionsEqual: function (other) {
        return this.section() === other.section() && (!this.minWidthExpression() || (this.minWidthExpression().computedLength() === other.minWidthExpression().computedLength())) && (!this.maxWidthExpression() || (this.maxWidthExpression().computedLength() === other.maxWidthExpression().computedLength()));
    }, compareTo: function (other) {
        if (this.section() !== other.section())
            return this.section() - other.section();
        if (this.dimensionsEqual(other)) {
            var myLocation = this.uiLocation();
            var otherLocation = other.uiLocation();
            if (!myLocation && !otherLocation)
                return this.mediaText().compareTo(other.mediaText());
            if (myLocation && !otherLocation)
                return 1;
            if (!myLocation && otherLocation)
                return -1;
            return myLocation.uiSourceCode.uri().compareTo(otherLocation.uiSourceCode.uri()) || myLocation.lineNumber - otherLocation.lineNumber || myLocation.columnNumber - otherLocation.columnNumber;
        }
        if (this.section() === WebInspector.MediaQueryInspector.Section.Max)
            return this.maxWidthExpression().computedLength() - other.maxWidthExpression().computedLength();
        if (this.section() === WebInspector.MediaQueryInspector.Section.Min)
            return this.minWidthExpression().computedLength() - other.minWidthExpression().computedLength();
        return this.minWidthExpression().computedLength() - other.minWidthExpression().computedLength() || this.maxWidthExpression().computedLength() - other.maxWidthExpression().computedLength();
    }, section: function () {
        return this._section;
    }, mediaText: function () {
        return this._cssMedia.text;
    }, uiLocation: function () {
        return WebInspector.cssWorkspaceBinding.rawLocationToUILocation(this._cssMedia.rawLocation());
    }, minWidthExpression: function () {
        return this._minWidthExpression;
    }, maxWidthExpression: function () {
        return this._maxWidthExpression;
    }
}
WebInspector.OverridesUI = {}
WebInspector.OverridesUI.createDeviceSelect = function (document, titleProvider) {
    var p = document.createElement("p");
    var deviceSelectElement = p.createChild("select");
    deviceSelectElement.addEventListener("change", deviceSelected, false);
    var saveButton = p.createChild("button");
    saveButton.textContent = WebInspector.UIString("Save as");
    saveButton.addEventListener("click", saveClicked, false);
    var removeButton = p.createChild("button");
    removeButton.textContent = WebInspector.UIString("Remove");
    removeButton.addEventListener("click", removeClicked, false);
    var emulatedSettingChangedMuted = {muted: false};
    WebInspector.overridesSupport.settings.emulateResolution.addChangeListener(emulatedSettingChanged);
    WebInspector.overridesSupport.settings.deviceWidth.addChangeListener(emulatedSettingChanged);
    WebInspector.overridesSupport.settings.deviceHeight.addChangeListener(emulatedSettingChanged);
    WebInspector.overridesSupport.settings.deviceScaleFactor.addChangeListener(emulatedSettingChanged);
    WebInspector.overridesSupport.settings.emulateMobile.addChangeListener(emulatedSettingChanged);
    WebInspector.overridesSupport.settings.emulateTouch.addChangeListener(emulatedSettingChanged);
    WebInspector.overridesSupport.settings.userAgent.addChangeListener(emulatedSettingChanged);
    WebInspector.overridesSupport.settings.customDevicePresets.addChangeListener(customPresetsChanged);
    customPresetsChanged();
    function deviceSelected() {
        updateButtons();
        if (deviceSelectElement.selectedIndex === 0)
            return;
        var option = deviceSelectElement.options[deviceSelectElement.selectedIndex];
        emulatedSettingChangedMuted.muted = true;
        WebInspector.overridesSupport.emulateDevice(option.device);
        emulatedSettingChangedMuted.muted = false;
    }

    function emulatedSettingChanged() {
        if (emulatedSettingChangedMuted.muted)
            return;
        var index = 0;
        for (var i = 1; i < deviceSelectElement.options.length; ++i) {
            var option = deviceSelectElement.options[i];
            if (WebInspector.overridesSupport.isEmulatingDevice(option.device)) {
                index = i;
                break;
            }
        }
        deviceSelectElement.selectedIndex = index;
        updateButtons();
    }

    function updateButtons() {
        var index = deviceSelectElement.selectedIndex;
        var custom = deviceSelectElement.options[index].custom;
        saveButton.disabled = !!index || !titleProvider;
        removeButton.disabled = !custom;
    }

    function customPresetsChanged() {
        deviceSelectElement.removeChildren();
        var selectDeviceOption = new Option(WebInspector.UIString("<Select model>"), WebInspector.UIString("<Select model>"));
        selectDeviceOption.device = {title: WebInspector.UIString("<Select model>"), width: 0, height: 0, deviceScaleFactor: 0, userAgent: "", touch: false, mobile: false};
        selectDeviceOption.disabled = true;
        deviceSelectElement.appendChild(selectDeviceOption);
        addGroup(WebInspector.UIString("Custom"), WebInspector.overridesSupport.settings.customDevicePresets.get(), true);
        addGroup(WebInspector.UIString("Devices"), WebInspector.OverridesUI._phones.concat(WebInspector.OverridesUI._tablets));
        addGroup(WebInspector.UIString("Notebooks"), WebInspector.OverridesUI._notebooks);
        function addGroup(name, devices, custom) {
            if (!devices.length)
                return;
            devices = devices.slice();
            devices.sort(compareDevices);
            var groupElement = deviceSelectElement.createChild("optgroup");
            groupElement.label = name;
            for (var i = 0; i < devices.length; ++i) {
                var option = new Option(devices[i].title, devices[i].title);
                option.device = devices[i];
                option.custom = custom;
                groupElement.appendChild(option);
            }
        }

        function compareDevices(device1, device2) {
            return device1.title < device2.title ? -1 : (device1.title > device2.title ? 1 : 0);
        }

        emulatedSettingChanged();
    }

    function saveClicked() {
        titleProvider(saveDevicePreset);
    }

    function saveDevicePreset(title) {
        if (!title)
            return;
        var device = WebInspector.overridesSupport.deviceFromCurrentSettings();
        device.title = title;
        var presets = WebInspector.overridesSupport.settings.customDevicePresets.get();
        presets.push(device);
        WebInspector.overridesSupport.settings.customDevicePresets.set(presets);
    }

    function removeClicked() {
        var presets = WebInspector.overridesSupport.settings.customDevicePresets.get();
        var option = deviceSelectElement.options[deviceSelectElement.selectedIndex];
        var device = option.device;
        presets.remove(device);
        WebInspector.overridesSupport.settings.customDevicePresets.set(presets);
    }

    return p;
}
WebInspector.OverridesUI.createNetworkConditionsSelect = function (document) {
    var networkConditionsSetting = WebInspector.overridesSupport.settings.networkConditions;
    var conditionsSelectElement = document.createElement("select");
    var presets = WebInspector.OverridesUI._networkConditionsPresets;
    for (var i = 0; i < presets.length; ++i) {
        var preset = presets[i];
        var throughput = preset.throughput | 0;
        var latency = preset.latency | 0;
        var isThrottling = (throughput > 0) || latency;
        if (!isThrottling) {
            conditionsSelectElement.add(new Option(preset.title, preset.id));
        } else {
            var throughputText = (throughput < 1024) ? WebInspector.UIString("%d Kbps", throughput) : WebInspector.UIString("%d Mbps", (throughput / 1024) | 0);
            var title = WebInspector.UIString("%s (%s %dms RTT)", preset.title, throughputText, latency);
            var option = new Option(title, preset.id);
            option.title = WebInspector.UIString("Maximum download throughput: %s.\r\nMinimum round-trip time: %dms.", throughputText, latency);
            conditionsSelectElement.add(option);
        }
    }
    settingChanged();
    networkConditionsSetting.addChangeListener(settingChanged);
    conditionsSelectElement.addEventListener("change", presetSelected, false);
    function presetSelected() {
        var selectedOption = conditionsSelectElement.options[conditionsSelectElement.selectedIndex];
        conditionsSelectElement.title = selectedOption.title;
        var presetId = selectedOption.value;
        var preset = presets[presets.length - 1];
        for (var i = 0; i < presets.length; ++i) {
            if (presets[i].id === presetId) {
                preset = presets[i];
                break;
            }
        }
        var kbps = 1024 / 8;
        networkConditionsSetting.removeChangeListener(settingChanged);
        networkConditionsSetting.set({throughput: preset.throughput * kbps, latency: preset.latency});
        networkConditionsSetting.addChangeListener(settingChanged);
    }

    function settingChanged() {
        var conditions = networkConditionsSetting.get();
        var presetIndex = presets.length - 1;
        for (var i = 0; i < presets.length; ++i) {
            if (presets[i].throughput === conditions.throughput && presets[i].latency === conditions.latency) {
                conditionsSelectElement.selectedIndex = i;
                break;
            }
        }
        conditionsSelectElement.selectedIndex = presetIndex;
        conditionsSelectElement.title = conditionsSelectElement.options[presetIndex].title;
    }

    return conditionsSelectElement;
}
WebInspector.OverridesUI.createUserAgentSelectAndInput = function (document) {
    var userAgentSetting = WebInspector.overridesSupport.settings.userAgent;
    const noOverride = {title: WebInspector.UIString("No override"), value: ""};
    const customOverride = {title: WebInspector.UIString("Other"), value: "Other"};
    var userAgents = [noOverride].concat(WebInspector.OverridesUI._userAgents).concat([customOverride]);
    var userAgentSelectElement = document.createElement("select");
    for (var i = 0; i < userAgents.length; ++i)
        userAgentSelectElement.add(new Option(userAgents[i].title, userAgents[i].value));
    userAgentSelectElement.selectedIndex = 0;
    var otherUserAgentElement = document.createElement("input");
    otherUserAgentElement.type = "text";
    otherUserAgentElement.value = userAgentSetting.get();
    otherUserAgentElement.title = userAgentSetting.get();
    settingChanged();
    userAgentSetting.addChangeListener(settingChanged);
    userAgentSelectElement.addEventListener("change", userAgentSelected, false);
    otherUserAgentElement.addEventListener("dblclick", textDoubleClicked, true);
    otherUserAgentElement.addEventListener("blur", textChanged, false);
    otherUserAgentElement.addEventListener("keydown", textKeyDown, false);
    function userAgentSelected() {
        var value = userAgentSelectElement.options[userAgentSelectElement.selectedIndex].value;
        if (value !== customOverride.value) {
            userAgentSetting.removeChangeListener(settingChanged);
            userAgentSetting.set(value);
            userAgentSetting.addChangeListener(settingChanged);
            otherUserAgentElement.value = value;
            otherUserAgentElement.title = value;
            otherUserAgentElement.readOnly = true;
        } else {
            otherUserAgentElement.readOnly = false;
            otherUserAgentElement.focus();
        }
    }

    function settingChanged() {
        var value = userAgentSetting.get();
        var options = userAgentSelectElement.options;
        var selectionRestored = false;
        for (var i = 0; i < options.length; ++i) {
            if (options[i].value === value) {
                userAgentSelectElement.selectedIndex = i;
                selectionRestored = true;
                break;
            }
        }
        otherUserAgentElement.readOnly = selectionRestored;
        if (!selectionRestored)
            userAgentSelectElement.selectedIndex = options.length - 1;
        if (otherUserAgentElement.value !== value) {
            otherUserAgentElement.value = value;
            otherUserAgentElement.title = value;
        }
    }

    function textKeyDown(event) {
        if (isEnterKey(event))
            textChanged();
    }

    function textDoubleClicked() {
        userAgentSelectElement.selectedIndex = userAgents.length - 1;
        userAgentSelected();
    }

    function textChanged() {
        if (userAgentSetting.get() !== otherUserAgentElement.value)
            userAgentSetting.set(otherUserAgentElement.value);
    }

    return {select: userAgentSelectElement, input: otherUserAgentElement};
}
WebInspector.OverridesUI._phones = [{
    title: "Apple iPhone 3GS",
    width: 320,
    height: 480,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
    touch: true,
    mobile: true
}, {
    title: "Apple iPhone 4",
    width: 320,
    height: 480,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
    touch: true,
    mobile: true
}, {
    title: "Apple iPhone 5",
    width: 320,
    height: 568,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; en-us) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53",
    touch: true,
    mobile: true
}, {
    title: "BlackBerry Z10",
    width: 384,
    height: 640,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",
    touch: true,
    mobile: true
}, {
    title: "BlackBerry Z30",
    width: 360,
    height: 640,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+",
    touch: true,
    mobile: true
}, {
    title: "Google Nexus 4",
    width: 384,
    height: 640,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
    touch: true,
    mobile: true
}, {
    title: "Google Nexus 5",
    width: 360,
    height: 640,
    deviceScaleFactor: 3,
    userAgent: "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
    touch: true,
    mobile: true
}, {
    title: "Google Nexus S",
    width: 320,
    height: 533,
    deviceScaleFactor: 1.5,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; Nexus S Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}, {
    title: "HTC Evo, Touch HD, Desire HD, Desire",
    width: 320,
    height: 533,
    deviceScaleFactor: 1.5,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Sprint APA9292KT Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}, {
    title: "HTC One X, EVO LTE",
    width: 360,
    height: 640,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; Android 4.0.3; HTC One X Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19",
    touch: true,
    mobile: true
}, {
    title: "HTC Sensation, Evo 3D",
    width: 360,
    height: 640,
    deviceScaleFactor: 1.5,
    userAgent: "Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
    touch: true,
    mobile: true
}, {
    title: "LG Optimus 2X, Optimus 3D, Optimus Black",
    width: 320,
    height: 533,
    deviceScaleFactor: 1.5,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.2; en-us; LG-P990/V08c Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 MMS/LG-Android-MMS-V1.0/1.2",
    touch: true,
    mobile: true
}, {
    title: "LG Optimus G",
    width: 384,
    height: 640,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; Android 4.0; LG-E975 Build/IMM76L) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
    touch: true,
    mobile: true
}, {
    title: "LG Optimus LTE, Optimus 4X HD",
    width: 424,
    height: 753,
    deviceScaleFactor: 1.7,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.3; en-us; LG-P930 Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}, {
    title: "LG Optimus One",
    width: 213,
    height: 320,
    deviceScaleFactor: 1.5,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; LG-MS690 Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}, {
    title: "Motorola Defy, Droid, Droid X, Milestone",
    width: 320,
    height: 569,
    deviceScaleFactor: 1.5,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.0; en-us; Milestone Build/ SHOLS_U2_01.03.1) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17",
    touch: true,
    mobile: true
}, {
    title: "Motorola Droid 3, Droid 4, Droid Razr, Atrix 4G, Atrix 2",
    width: 540,
    height: 960,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Droid Build/FRG22D) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}, {
    title: "Motorola Droid Razr HD",
    width: 720,
    height: 1280,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.3; en-us; DROID RAZR 4G Build/6.5.1-73_DHD-11_M1-29) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}, {
    title: "Nokia C5, C6, C7, N97, N8, X7",
    width: 360,
    height: 640,
    deviceScaleFactor: 1,
    userAgent: "NokiaN97/21.1.107 (SymbianOS/9.4; Series60/5.0 Mozilla/5.0; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebkit/525 (KHTML, like Gecko) BrowserNG/7.1.4",
    touch: true,
    mobile: true
}, {
    title: "Nokia Lumia 7X0, Lumia 8XX, Lumia 900, N800, N810, N900",
    width: 320,
    height: 533,
    deviceScaleFactor: 1.5,
    userAgent: "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 820)",
    touch: true,
    mobile: true
}, {
    title: "Samsung Galaxy Note 3",
    width: 360,
    height: 640,
    deviceScaleFactor: 3,
    userAgent: "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
    touch: true,
    mobile: true
}, {
    title: "Samsung Galaxy Note II",
    width: 360,
    height: 640,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
    touch: true,
    mobile: true
}, {
    title: "Samsung Galaxy Note",
    width: 400,
    height: 640,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.3; en-us; SAMSUNG-SGH-I717 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}, {
    title: "Samsung Galaxy S III, Galaxy Nexus",
    width: 360,
    height: 640,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
    touch: true,
    mobile: true
}, {
    title: "Samsung Galaxy S, S II, W",
    width: 320,
    height: 533,
    deviceScaleFactor: 1.5,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.1; en-us; GT-I9000 Build/ECLAIR) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2",
    touch: true,
    mobile: true
}, {
    title: "Samsung Galaxy S4",
    width: 360,
    height: 640,
    deviceScaleFactor: 3,
    userAgent: "Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36",
    touch: true,
    mobile: true
}, {
    title: "Sony Xperia S, Ion",
    width: 360,
    height: 640,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; U; Android 4.0; en-us; LT28at Build/6.1.C.1.111) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
    touch: true,
    mobile: true
}, {
    title: "Sony Xperia Sola, U",
    width: 480,
    height: 854,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.3; en-us; SonyEricssonST25i Build/6.0.B.1.564) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}, {
    title: "Sony Xperia Z, Z1",
    width: 360,
    height: 640,
    deviceScaleFactor: 3,
    userAgent: "Mozilla/5.0 (Linux; U; Android 4.2; en-us; SonyC6903 Build/14.1.G.1.518) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
    touch: true,
    mobile: true
}];
WebInspector.OverridesUI._tablets = [{
    title: "Amazon Kindle Fire HDX 7″",
    width: 1920,
    height: 1200,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; U; en-us; KFTHWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
    touch: true,
    mobile: true
}, {
    title: "Amazon Kindle Fire HDX 8.9″",
    width: 2560,
    height: 1600,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true",
    touch: true,
    mobile: true
}, {
    title: "Amazon Kindle Fire (First Generation)",
    width: 1024,
    height: 600,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.0.141.16-Gen4_11004310) AppleWebkit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true",
    touch: true,
    mobile: true
}, {
    title: "Apple iPad 1 / 2 / iPad Mini",
    width: 1024,
    height: 768,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (iPad; CPU OS 4_3_5 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8L1 Safari/6533.18.5",
    touch: true,
    mobile: true
}, {
    title: "Apple iPad 3 / 4",
    width: 1024,
    height: 768,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53",
    touch: true,
    mobile: true
}, {
    title: "BlackBerry PlayBook",
    width: 1024,
    height: 600,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+",
    touch: true,
    mobile: true
}, {
    title: "Google Nexus 10",
    width: 1280,
    height: 800,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36",
    touch: true,
    mobile: true
}, {
    title: "Google Nexus 7 2",
    width: 960,
    height: 600,
    deviceScaleFactor: 2,
    userAgent: "Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36",
    touch: true,
    mobile: true
}, {
    title: "Google Nexus 7",
    width: 966,
    height: 604,
    deviceScaleFactor: 1.325,
    userAgent: "Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.72 Safari/537.36",
    touch: true,
    mobile: true
}, {
    title: "Motorola Xoom, Xyboard",
    width: 1280,
    height: 800,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/525.10 (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2",
    touch: true,
    mobile: true
}, {
    title: "Samsung Galaxy Tab 7.7, 8.9, 10.1",
    width: 1280,
    height: 800,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.2; en-us; SCH-I800 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}, {
    title: "Samsung Galaxy Tab",
    width: 1024,
    height: 600,
    deviceScaleFactor: 1,
    userAgent: "Mozilla/5.0 (Linux; U; Android 2.2; en-us; SCH-I800 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    touch: true,
    mobile: true
}];
WebInspector.OverridesUI._notebooks = [{title: "Notebook with touch", width: 1280, height: 950, deviceScaleFactor: 1, userAgent: "", touch: true, mobile: false}, {
    title: "Notebook with HiDPI screen",
    width: 1440,
    height: 900,
    deviceScaleFactor: 2,
    userAgent: "",
    touch: false,
    mobile: false
}, {title: "Generic notebook", width: 1280, height: 800, deviceScaleFactor: 1, userAgent: "", touch: false, mobile: false}];
WebInspector.OverridesUI._networkConditionsPresets = [{id: "offline", title: "Offline", throughput: 0, latency: 0}, {id: "gprs", title: "GPRS", throughput: 50, latency: 500}, {
    id: "edge",
    title: "EDGE",
    throughput: 250,
    latency: 300
}, {id: "3g", title: "3G", throughput: 750, latency: 100}, {id: "dsl", title: "DSL", throughput: 2 * 1024, latency: 5}, {id: "wifi", title: "WiFi", throughput: 30 * 1024, latency: 2}, {
    id: "online",
    title: "No throttling",
    throughput: WebInspector.OverridesSupport.NetworkThroughputUnlimitedValue,
    latency: 0
}];
WebInspector.OverridesUI._userAgents = [{
    title: "Android 4.0.2 \u2014 Galaxy Nexus",
    value: "Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"
}, {title: "Android 2.3 \u2014 Nexus S", value: "Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"}, {
    title: "BlackBerry \u2014 BB10",
    value: "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.1+ (KHTML, like Gecko) Version/10.0.0.1337 Mobile Safari/537.1+"
}, {title: "BlackBerry \u2014 PlayBook 2.1", value: "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML, like Gecko) Version/7.2.1.0 Safari/536.2+"}, {
    title: "BlackBerry \u2014 9900",
    value: "Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en-US) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.0.0.187 Mobile Safari/534.11+"
}, {title: "Chrome 31 \u2014 Mac", value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36"}, {
    title: "Chrome 31 \u2014 Windows",
    value: "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"
}, {title: "Chrome \u2014 Android Tablet", value: "Mozilla/5.0 (Linux; Android 4.1.2; Nexus 7 Build/JZ054K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19"}, {
    title: "Chrome \u2014 Android Mobile",
    value: "Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19"
}, {title: "Firefox 14 \u2014 Android Mobile", value: "Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0"}, {
    title: "Firefox 14 \u2014 Android Tablet",
    value: "Mozilla/5.0 (Android; Tablet; rv:14.0) Gecko/14.0 Firefox/14.0"
}, {title: "Firefox 4 \u2014 Mac", value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"}, {
    title: "Firefox 4 \u2014 Windows",
    value: "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"
}, {title: "Firefox 7 \u2014 Mac", value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"}, {
    title: "Firefox 7 \u2014 Windows",
    value: "Mozilla/5.0 (Windows NT 6.1; Intel Mac OS X 10.6; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"
}, {title: "Internet Explorer 10", value: "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)"}, {title: "Internet Explorer 7", value: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"}, {
    title: "Internet Explorer 8",
    value: "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)"
}, {title: "Internet Explorer 9", value: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"}, {
    title: "iPad \u2014 iOS 7",
    value: "Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A501 Safari/9537.53"
}, {title: "iPad \u2014 iOS 6", value: "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25"}, {
    title: "iPhone \u2014 iOS 7",
    value: "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A4449d Safari/9537.53"
}, {title: "iPhone \u2014 iOS 6", value: "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25"}, {
    title: "MeeGo \u2014 Nokia N9",
    value: "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13"
}, {title: "Opera 18 \u2014 Mac", value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 OPR/18.0.1284.68"}, {
    title: "Opera 18 \u2014 Windows",
    value: "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 OPR/18.0.1284.68"
}, {title: "Opera 12 \u2014 Mac", value: "Opera/9.80 (Macintosh; Intel Mac OS X 10.9.1) Presto/2.12.388 Version/12.16"}, {
    title: "Opera 12 \u2014 Windows",
    value: "Opera/9.80 (Windows NT 6.1) Presto/2.12.388 Version/12.16"
}, {
    title: "Silk \u2014 Kindle Fire (Desktop view)",
    value: "Mozilla/5.0 (Linux; U; en-us; KFTHWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true"
}, {title: "Silk \u2014 Kindle Fire (Mobile view)", value: "Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; KFTHWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Mobile Safari/535.19 Silk-Accelerated=true"}];
WebInspector.ResponsiveDesignView = function (inspectedPagePlaceholder) {
    WebInspector.VBox.call(this);
    this.setMinimumSize(150, 150);
    this.element.classList.add("overflow-hidden");
    this._responsiveDesignContainer = new WebInspector.VBox();
    this._responsiveDesignContainer.registerRequiredCSS("responsiveDesignView.css");
    this._createToolbar();
    this._mediaInspector = new WebInspector.MediaQueryInspector();
    this._mediaInspectorContainer = this._responsiveDesignContainer.element.createChild("div", "responsive-design-media-container");
    this._updateMediaQueryInspector();
    this._canvasContainer = new WebInspector.View();
    this._canvasContainer.element.classList.add("responsive-design");
    this._canvasContainer.show(this._responsiveDesignContainer.element);
    this._canvas = this._canvasContainer.element.createChild("canvas", "fill");
    this._rulerGlasspane = this._canvasContainer.element.createChild("div", "responsive-design-ruler-glasspane");
    this._rulerGlasspane.appendChild(this._mediaInspector.rulerDecorationLayer());
    this._warningMessage = this._canvasContainer.element.createChild("div", "responsive-design-warning hidden");
    this._warningMessage.createChild("div", "warning-icon-small");
    this._warningMessage.createChild("span");
    var warningCloseButton = this._warningMessage.createChild("div", "close-button");
    warningCloseButton.addEventListener("click", WebInspector.overridesSupport.clearWarningMessage.bind(WebInspector.overridesSupport), false);
    WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.OverridesWarningUpdated, this._overridesWarningUpdated, this);
    this._slidersContainer = this._canvasContainer.element.createChild("div", "vbox responsive-design-sliders-container");
    var hbox = this._slidersContainer.createChild("div", "hbox flex-auto");
    this._heightSliderContainer = this._slidersContainer.createChild("div", "hbox responsive-design-slider-height");
    this._pageContainer = hbox.createChild("div", "vbox flex-auto");
    this._widthSliderContainer = hbox.createChild("div", "vbox responsive-design-slider-width");
    this._widthSlider = this._widthSliderContainer.createChild("div", "responsive-design-slider-thumb");
    this._widthSlider.createChild("div", "responsive-design-thumb-handle");
    this._createResizer(this._widthSlider, false);
    this._heightSlider = this._heightSliderContainer.createChild("div", "responsive-design-slider-thumb");
    this._heightSlider.createChild("div", "responsive-design-thumb-handle");
    this._createResizer(this._heightSlider, true);
    this._inspectedPagePlaceholder = inspectedPagePlaceholder;
    inspectedPagePlaceholder.show(this.element);
    this._enabled = false;
    this._viewport = {scrollX: 0, scrollY: 0, contentsWidth: 0, contentsHeight: 0, pageScaleFactor: 1};
    this._drawContentsSize = true;
    this._viewportChangedThrottler = new WebInspector.Throttler(0);
    WebInspector.zoomManager.addEventListener(WebInspector.ZoomManager.Events.ZoomChanged, this._onZoomChanged, this);
    WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.EmulationStateChanged, this._emulationEnabledChanged, this);
    this._mediaInspector.addEventListener(WebInspector.MediaQueryInspector.Events.HeightUpdated, this.onResize, this);
    WebInspector.targetManager.observeTargets(this);
    this._emulationEnabledChanged();
    this._overridesWarningUpdated();
};
WebInspector.ResponsiveDesignView.SliderWidth = 19;
WebInspector.ResponsiveDesignView.RulerWidth = 22;
WebInspector.ResponsiveDesignView.prototype = {
    targetAdded: function (target) {
        if (this._target)
            return;
        this._target = target;
        target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.ViewportChanged, this._viewportChanged, this);
    }, targetRemoved: function (target) {
        if (target !== this._target)
            return;
        target.resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.ViewportChanged, this._viewportChanged, this);
    }, _invalidateCache: function () {
        delete this._cachedScale;
        delete this._cachedCssCanvasWidth;
        delete this._cachedCssCanvasHeight;
        delete this._cachedCssHeight;
        delete this._cachedCssWidth;
        delete this._cachedZoomFactor;
        delete this._cachedViewport;
        delete this._cachedDrawContentsSize;
        delete this._availableSize;
    }, _emulationEnabledChanged: function () {
        var enabled = WebInspector.overridesSupport.emulationEnabled();
        this._mediaInspector.setEnabled(enabled);
        if (enabled && !this._enabled) {
            this._invalidateCache();
            this._ignoreResize = true;
            this._enabled = true;
            this._inspectedPagePlaceholder.clearMinimumSizeAndMargins();
            this._inspectedPagePlaceholder.show(this._pageContainer);
            this._responsiveDesignContainer.show(this.element);
            delete this._ignoreResize;
            this.onResize();
        } else if (!enabled && this._enabled) {
            this._invalidateCache();
            this._ignoreResize = true;
            this._enabled = false;
            this._scale = 1;
            this._inspectedPagePlaceholder.restoreMinimumSizeAndMargins();
            this._responsiveDesignContainer.detach();
            this._inspectedPagePlaceholder.show(this.element);
            delete this._ignoreResize;
            this.onResize();
        }
    }, update: function (dipWidth, dipHeight, scale) {
        this._scale = scale;
        this._dipWidth = dipWidth ? Math.max(dipWidth, 1) : 0;
        this._dipHeight = dipHeight ? Math.max(dipHeight, 1) : 0;
        this._updateUI();
    }, updatePageResizer: function () {
        WebInspector.overridesSupport.setPageResizer(this, this._availableDipSize());
    }, _availableDipSize: function () {
        if (typeof this._availableSize === "undefined") {
            var zoomFactor = WebInspector.zoomManager.zoomFactor();
            var rect = this._canvasContainer.element.getBoundingClientRect();
            this._availableSize = new Size(Math.max(rect.width * zoomFactor - WebInspector.ResponsiveDesignView.RulerWidth, 1), Math.max(rect.height * zoomFactor - WebInspector.ResponsiveDesignView.RulerWidth, 1));
        }
        return this._availableSize;
    }, _createResizer: function (element, vertical) {
        var resizer = new WebInspector.ResizerWidget();
        resizer.addElement(element);
        resizer.setVertical(vertical);
        resizer.addEventListener(WebInspector.ResizerWidget.Events.ResizeStart, this._onResizeStart, this);
        resizer.addEventListener(WebInspector.ResizerWidget.Events.ResizeUpdate, this._onResizeUpdate, this);
        resizer.addEventListener(WebInspector.ResizerWidget.Events.ResizeEnd, this._onResizeEnd, this);
        return resizer;
    }, _onResizeStart: function (event) {
        this._drawContentsSize = false;
        var available = this._availableDipSize();
        this._slowPositionStart = null;
        this._resizeStartSize = event.target.isVertical() ? (this._dipHeight || available.height) : (this._dipWidth || available.width);
        this.dispatchEventToListeners(WebInspector.OverridesSupport.PageResizer.Events.FixedScaleRequested, true);
        this._updateUI();
    }, _onResizeUpdate: function (event) {
        if (event.data.shiftKey !== !!this._slowPositionStart)
            this._slowPositionStart = event.data.shiftKey ? event.data.currentPosition : null;
        var cssOffset = this._slowPositionStart ? (event.data.currentPosition - this._slowPositionStart) / 10 + this._slowPositionStart - event.data.startPosition : event.data.currentPosition - event.data.startPosition;
        var dipOffset = Math.round(cssOffset * WebInspector.zoomManager.zoomFactor());
        var newSize = this._resizeStartSize + dipOffset;
        newSize = Math.round(newSize / (this._scale || 1));
        newSize = Math.max(Math.min(newSize, WebInspector.OverridesSupport.MaxDeviceSize), 1);
        var requested = {};
        if (event.target.isVertical())
            requested.height = newSize; else
            requested.width = newSize;
        this.dispatchEventToListeners(WebInspector.OverridesSupport.PageResizer.Events.ResizeRequested, requested);
    }, _onResizeEnd: function (event) {
        this._drawContentsSize = true;
        this.dispatchEventToListeners(WebInspector.OverridesSupport.PageResizer.Events.FixedScaleRequested, false);
        delete this._resizeStartSize;
        this._updateUI();
    }, _drawCanvas: function (cssCanvasWidth, cssCanvasHeight) {
        if (!this._enabled)
            return;
        var canvas = this._canvas;
        var context = canvas.getContext("2d");
        canvas.style.width = cssCanvasWidth + "px";
        canvas.style.height = cssCanvasHeight + "px";
        var zoomFactor = WebInspector.zoomManager.zoomFactor();
        var dipCanvasWidth = cssCanvasWidth * zoomFactor;
        var dipCanvasHeight = cssCanvasHeight * zoomFactor;
        var deviceScaleFactor = window.devicePixelRatio;
        canvas.width = deviceScaleFactor * cssCanvasWidth;
        canvas.height = deviceScaleFactor * cssCanvasHeight;
        context.scale(canvas.width / dipCanvasWidth, canvas.height / dipCanvasHeight);
        context.font = "11px " + WebInspector.fontFamily();
        const rulerBackgroundColor = "rgb(0, 0, 0)";
        const backgroundColor = "rgb(102, 102, 102)";
        const lightLineColor = "rgb(132, 132, 132)";
        const darkLineColor = "rgb(114, 114, 114)";
        const rulerColor = "rgb(125, 125, 125)";
        const textColor = "rgb(186, 186, 186)";
        const contentsSizeColor = "rgba(0, 0, 0, 0.3)";
        var scale = (this._scale || 1) * this._viewport.pageScaleFactor;
        var rulerScale = 0.5;
        while (Math.abs(rulerScale * scale - 1) > Math.abs((rulerScale + 0.5) * scale - 1))
            rulerScale += 0.5;
        var gridStep = 50 * scale * rulerScale;
        var gridSubStep = 10 * scale * rulerScale;
        var rulerSubStep = 5 * scale * rulerScale;
        var rulerStepCount = 20;
        var rulerWidth = WebInspector.ResponsiveDesignView.RulerWidth;
        var dipGridWidth = dipCanvasWidth - rulerWidth;
        var dipGridHeight = dipCanvasHeight - rulerWidth;
        var dipScrollX = this._viewport.scrollX * scale;
        var dipScrollY = this._viewport.scrollY * scale;
        context.translate(rulerWidth, rulerWidth);
        context.fillStyle = rulerBackgroundColor;
        context.fillRect(-rulerWidth, -rulerWidth, dipGridWidth + rulerWidth, rulerWidth);
        context.fillRect(-rulerWidth, 0, rulerWidth, dipGridHeight);
        context.fillStyle = backgroundColor;
        context.fillRect(0, 0, dipGridWidth, dipGridHeight);
        context.translate(0.5, 0.5);
        context.strokeStyle = rulerColor;
        context.fillStyle = textColor;
        context.lineWidth = 1;
        context.save();
        var minXIndex = Math.ceil(dipScrollX / rulerSubStep);
        var maxXIndex = Math.floor((dipScrollX + dipGridWidth) / rulerSubStep);
        context.translate(-dipScrollX, 0);
        for (var index = minXIndex; index <= maxXIndex; index++) {
            var x = index * rulerSubStep;
            var y = -rulerWidth / 4;
            if (!(index % (rulerStepCount / 4)))
                y = -rulerWidth / 2;
            if (!(index % (rulerStepCount / 2)))
                y = -rulerWidth + 2;
            if (!(index % rulerStepCount)) {
                context.save();
                context.translate(x, 0);
                context.fillText(Math.round(x / scale), 2, -rulerWidth / 2);
                context.restore();
                y = -rulerWidth;
            }
            context.beginPath();
            context.moveTo(x, y);
            context.lineTo(x, 0);
            context.stroke();
        }
        context.restore();
        context.save();
        var minYIndex = Math.ceil(dipScrollY / rulerSubStep);
        var maxYIndex = Math.floor((dipScrollY + dipGridHeight) / rulerSubStep);
        context.translate(0, -dipScrollY);
        for (var index = minYIndex; index <= maxYIndex; index++) {
            var y = index * rulerSubStep;
            var x = -rulerWidth / 4;
            if (!(index % (rulerStepCount / 4)))
                x = -rulerWidth / 2;
            if (!(index % (rulerStepCount / 2)))
                x = -rulerWidth + 2;
            if (!(index % rulerStepCount)) {
                context.save();
                context.translate(0, y);
                context.rotate(-Math.PI / 2);
                context.fillText(Math.round(y / scale), 2, -rulerWidth / 2);
                context.restore();
                x = -rulerWidth;
            }
            context.beginPath();
            context.moveTo(x, y);
            context.lineTo(0, y);
            context.stroke();
        }
        context.restore();
        drawGrid(dipScrollX, dipScrollY, darkLineColor, gridSubStep);
        drawGrid(dipScrollX, dipScrollY, lightLineColor, gridStep);
        function drawGrid(scrollX, scrollY, color, step) {
            context.strokeStyle = color;
            var minX = Math.ceil(scrollX / step) * step;
            var maxX = Math.floor((scrollX + dipGridWidth) / step) * step - minX;
            var minY = Math.ceil(scrollY / step) * step;
            var maxY = Math.floor((scrollY + dipGridHeight) / step) * step - minY;
            context.save();
            context.translate(minX - scrollX, 0);
            for (var x = 0; x <= maxX; x += step) {
                context.beginPath();
                context.moveTo(x, 0);
                context.lineTo(x, dipGridHeight);
                context.stroke();
            }
            context.restore();
            context.save();
            context.translate(0, minY - scrollY);
            for (var y = 0; y <= maxY; y += step) {
                context.beginPath();
                context.moveTo(0, y);
                context.lineTo(dipGridWidth, y);
                context.stroke();
            }
            context.restore();
        }

        context.translate(-0.5, -0.5);
        var pageScaleAvailable = WebInspector.overridesSupport.settings.emulateMobile.get() || WebInspector.overridesSupport.settings.emulateTouch.get();
        if (this._drawContentsSize && pageScaleAvailable) {
            context.fillStyle = contentsSizeColor;
            var visibleContentsWidth = Math.max(0, Math.min(dipGridWidth, this._viewport.contentsWidth * scale - dipScrollX));
            var visibleContentsHeight = Math.max(0, Math.min(dipGridHeight, this._viewport.contentsHeight * scale - dipScrollY));
            context.fillRect(0, 0, visibleContentsWidth, visibleContentsHeight);
        }
    }, _updateUI: function () {
        if (!this._enabled || !this.isShowing())
            return;
        var zoomFactor = WebInspector.zoomManager.zoomFactor();
        var rect = this._canvas.parentElement.getBoundingClientRect();
        var availableDip = this._availableDipSize();
        var cssCanvasWidth = rect.width;
        var cssCanvasHeight = rect.height;
        this._mediaInspector.setAxisTransform(WebInspector.ResponsiveDesignView.RulerWidth / zoomFactor, this._viewport.scrollX, this._scale * this._viewport.pageScaleFactor);
        if (this._cachedZoomFactor !== zoomFactor) {
            var cssRulerWidth = WebInspector.ResponsiveDesignView.RulerWidth / zoomFactor + "px";
            this._rulerGlasspane.style.height = cssRulerWidth;
            this._rulerGlasspane.style.left = cssRulerWidth;
            this._slidersContainer.style.left = cssRulerWidth;
            this._slidersContainer.style.top = cssRulerWidth;
            this._warningMessage.style.height = cssRulerWidth;
            var cssSliderWidth = WebInspector.ResponsiveDesignView.SliderWidth / zoomFactor + "px";
            this._heightSliderContainer.style.flexBasis = cssSliderWidth;
            this._heightSliderContainer.style.marginBottom = "-" + cssSliderWidth;
            this._widthSliderContainer.style.flexBasis = cssSliderWidth;
            this._widthSliderContainer.style.marginRight = "-" + cssSliderWidth;
        }
        var cssWidth = this._dipWidth ? (this._dipWidth / zoomFactor + "px") : (availableDip.width / zoomFactor + "px");
        var cssHeight = this._dipHeight ? (this._dipHeight / zoomFactor + "px") : (availableDip.height / zoomFactor + "px");
        if (this._cachedCssWidth !== cssWidth || this._cachedCssHeight !== cssHeight) {
            this._slidersContainer.style.width = cssWidth;
            this._slidersContainer.style.height = cssHeight;
            this._inspectedPagePlaceholder.onResize();
        }
        var viewportChanged = !this._cachedViewport || this._cachedViewport.scrollX !== this._viewport.scrollX || this._cachedViewport.scrollY !== this._viewport.scrollY || this._cachedViewport.contentsWidth !== this._viewport.contentsWidth || this._cachedViewport.contentsHeight !== this._viewport.contentsHeight || this._cachedViewport.pageScaleFactor !== this._viewport.pageScaleFactor;
        if (viewportChanged || this._drawContentsSize !== this._cachedDrawContentsSize || this._cachedScale !== this._scale || this._cachedCssCanvasWidth !== cssCanvasWidth || this._cachedCssCanvasHeight !== cssCanvasHeight || this._cachedZoomFactor !== zoomFactor)
            this._drawCanvas(cssCanvasWidth, cssCanvasHeight);
        this._cachedScale = this._scale;
        this._cachedCssCanvasWidth = cssCanvasWidth;
        this._cachedCssCanvasHeight = cssCanvasHeight;
        this._cachedCssHeight = cssHeight;
        this._cachedCssWidth = cssWidth;
        this._cachedZoomFactor = zoomFactor;
        this._cachedViewport = this._viewport;
        this._cachedDrawContentsSize = this._drawContentsSize;
    }, onResize: function () {
        if (!this._enabled || this._ignoreResize)
            return;
        var oldSize = this._availableSize;
        delete this._availableSize;
        var newSize = this._availableDipSize();
        if (!newSize.isEqual(oldSize))
            this.dispatchEventToListeners(WebInspector.OverridesSupport.PageResizer.Events.AvailableSizeChanged, newSize);
        this._updateUI();
        this._inspectedPagePlaceholder.onResize();
    }, _onZoomChanged: function () {
        this._updateUI();
    }, _createToolbar: function () {
        this._toolbarElement = this._responsiveDesignContainer.element.createChild("div", "responsive-design-toolbar");
        this._createButtonsSection();
        this._toolbarElement.createChild("div", "responsive-design-separator");
        this._createDeviceSection();
        this._toolbarElement.createChild("div", "responsive-design-separator");
        this._createNetworkSection();
        this._toolbarElement.createChild("div", "responsive-design-separator");
        var moreButtonContainer = this._toolbarElement.createChild("div", "responsive-design-more-button-container");
        var moreButton = moreButtonContainer.createChild("button", "responsive-design-more-button");
        moreButton.title = WebInspector.UIString("More overrides");
        moreButton.addEventListener("click", this._showEmulationInDrawer.bind(this), false);
        moreButton.textContent = "\u2026";
    }, _createButtonsSection: function () {
        var buttonsSection = this._toolbarElement.createChild("div", "responsive-design-section responsive-design-section-buttons");
        var resetButton = new WebInspector.StatusBarButton(WebInspector.UIString("Reset all overrides."), "clear-status-bar-item");
        buttonsSection.appendChild(resetButton.element);
        resetButton.addEventListener("click", WebInspector.overridesSupport.reset, WebInspector.overridesSupport);
        this._toggleMediaInspectorButton = new WebInspector.StatusBarButton(WebInspector.UIString("Media queries."), "responsive-design-toggle-media-inspector");
        this._toggleMediaInspectorButton.toggled = WebInspector.settings.showMediaQueryInspector.get();
        this._toggleMediaInspectorButton.addEventListener("click", this._onToggleMediaInspectorButtonClick, this);
        WebInspector.settings.showMediaQueryInspector.addChangeListener(this._updateMediaQueryInspector, this);
        buttonsSection.appendChild(this._toggleMediaInspectorButton.element);
    }, _createDeviceSection: function () {
        var deviceSection = this._toolbarElement.createChild("div", "responsive-design-section responsive-design-section-device");
        var deviceElement = deviceSection.createChild("div", "responsive-design-suite responsive-design-suite-top").createChild("div");
        var fieldsetElement = deviceElement.createChild("fieldset");
        fieldsetElement.createChild("label").textContent = WebInspector.UIString("Device");
        var deviceSelectElement = WebInspector.OverridesUI.createDeviceSelect(document);
        fieldsetElement.appendChild(deviceSelectElement);
        deviceSelectElement.classList.add("responsive-design-device-select");
        var separator = deviceSection.createChild("div", "responsive-design-section-separator");
        var detailsElement = deviceSection.createChild("div", "responsive-design-suite");
        var screenElement = detailsElement.createChild("div", "");
        fieldsetElement = screenElement.createChild("fieldset");
        var emulateResolutionCheckbox = WebInspector.SettingsUI.createSettingCheckbox("", WebInspector.overridesSupport.settings.emulateResolution, true, undefined, WebInspector.UIString("Emulate screen resolution"));
        fieldsetElement.appendChild(emulateResolutionCheckbox);
        var resolutionButton = new WebInspector.StatusBarButton(WebInspector.UIString("Screen resolution"), "responsive-design-icon responsive-design-icon-resolution");
        resolutionButton.setEnabled(false);
        fieldsetElement.appendChild(resolutionButton.element);
        var resolutionFieldset = WebInspector.SettingsUI.createSettingFieldset(WebInspector.overridesSupport.settings.emulateResolution);
        fieldsetElement.appendChild(resolutionFieldset);
        resolutionFieldset.appendChild(WebInspector.SettingsUI.createSettingInputField("", WebInspector.overridesSupport.settings.deviceWidth, true, 4, "3em", WebInspector.OverridesSupport.deviceSizeValidator, true, true, WebInspector.UIString("\u2013")));
        resolutionFieldset.appendChild(document.createTextNode(" \u00D7 "));
        resolutionFieldset.appendChild(WebInspector.SettingsUI.createSettingInputField("", WebInspector.overridesSupport.settings.deviceHeight, true, 4, "3em", WebInspector.OverridesSupport.deviceSizeValidator, true, true, WebInspector.UIString("\u2013")));
        var swapButton = new WebInspector.StatusBarButton(WebInspector.UIString("Swap dimensions"), "responsive-design-icon responsive-design-icon-swap");
        swapButton.element.tabIndex = -1;
        swapButton.addEventListener("click", WebInspector.overridesSupport.swapDimensions, WebInspector.overridesSupport);
        resolutionFieldset.appendChild(swapButton.element);
        detailsElement.createChild("div", "responsive-design-suite-separator");
        var dprElement = detailsElement.createChild("div", "");
        var resolutionFieldset2 = WebInspector.SettingsUI.createSettingFieldset(WebInspector.overridesSupport.settings.emulateResolution);
        dprElement.appendChild(resolutionFieldset2);
        var dprButton = new WebInspector.StatusBarButton(WebInspector.UIString("Device pixel ratio"), "responsive-design-icon responsive-design-icon-dpr");
        dprButton.setEnabled(false);
        resolutionFieldset2.appendChild(dprButton.element);
        resolutionFieldset2.appendChild(WebInspector.SettingsUI.createSettingInputField("", WebInspector.overridesSupport.settings.deviceScaleFactor, true, 4, "2.5em", WebInspector.OverridesSupport.deviceScaleFactorValidator, true, true, WebInspector.UIString("\u2013")));
        detailsElement.createChild("div", "responsive-design-suite-separator");
        var fitToWindowElement = detailsElement.createChild("div", "");
        fieldsetElement = fitToWindowElement.createChild("fieldset");
        fieldsetElement.appendChild(WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Fit"), WebInspector.overridesSupport.settings.deviceFitWindow, true, undefined, WebInspector.UIString("Zoom to fit available space")));
    }, _createNetworkSection: function () {
        var networkSection = this._toolbarElement.createChild("div", "responsive-design-section responsive-design-section-network");
        var bandwidthElement = networkSection.createChild("div", "responsive-design-suite responsive-design-suite-top").createChild("div");
        var fieldsetElement = bandwidthElement.createChild("fieldset");
        var networkCheckbox = fieldsetElement.createChild("label");
        networkCheckbox.textContent = WebInspector.UIString("Network");
        fieldsetElement.appendChild(WebInspector.OverridesUI.createNetworkConditionsSelect(document));
        var separator = networkSection.createChild("div", "responsive-design-section-separator");
        var userAgentElement = networkSection.createChild("div", "responsive-design-suite").createChild("div");
        fieldsetElement = userAgentElement.createChild("fieldset");
        fieldsetElement.appendChild(WebInspector.SettingsUI.createSettingInputField("UA", WebInspector.overridesSupport.settings.userAgent, false, 0, "", undefined, false, false, WebInspector.UIString("No override")));
    }, _onToggleMediaInspectorButtonClick: function () {
        WebInspector.settings.showMediaQueryInspector.set(!this._toggleMediaInspectorButton.toggled);
    }, _updateMediaQueryInspector: function () {
        this._toggleMediaInspectorButton.toggled = WebInspector.settings.showMediaQueryInspector.get();
        if (this._mediaInspector.isShowing() === WebInspector.settings.showMediaQueryInspector.get())
            return;
        if (this._mediaInspector.isShowing())
            this._mediaInspector.detach(); else
            this._mediaInspector.show(this._mediaInspectorContainer);
        this.onResize();
    }, _overridesWarningUpdated: function () {
        var message = WebInspector.overridesSupport.warningMessage();
        if (this._warningMessage.querySelector("span").textContent === message)
            return;
        this._warningMessage.classList.toggle("hidden", !message);
        this._warningMessage.querySelector("span").textContent = message;
        this._invalidateCache();
        this.onResize();
    }, _showEmulationInDrawer: function () {
        WebInspector.Revealer.reveal(WebInspector.overridesSupport);
    }, _viewportChanged: function (event) {
        var viewport = (event.data);
        if (viewport) {
            this._viewport = viewport;
            this._viewportChangedThrottler.schedule(this._updateUIThrottled.bind(this));
        }
    }, _updateUIThrottled: function (finishCallback) {
        this._updateUI();
        finishCallback();
    }, __proto__: WebInspector.VBox.prototype
};
WebInspector.ToolboxDelegate = function () {
}
WebInspector.ToolboxDelegate.prototype = {
    toolboxLoaded: function (responsiveDesignView, placeholder) {
    }
}
if (window.domAutomationController) {
    var ___interactiveUiTestsMode = true;
    TestSuite = function () {
        this.controlTaken_ = false;
        this.timerId_ = -1;
    };
    TestSuite.prototype.fail = function (message) {
        if (this.controlTaken_)
            this.reportFailure_(message); else
            throw message;
    };
    TestSuite.prototype.assertEquals = function (expected, actual, opt_message) {
        if (expected !== actual) {
            var message = "Expected: '" + expected + "', but was '" + actual + "'";
            if (opt_message)
                message = opt_message + "(" + message + ")";
            this.fail(message);
        }
    };
    TestSuite.prototype.assertTrue = function (value, opt_message) {
        this.assertEquals(true, !!value, opt_message);
    };
    TestSuite.prototype.assertHasKey = function (object, key) {
        if (!object.hasOwnProperty(key))
            this.fail("Expected object to contain key '" + key + "'");
    };
    TestSuite.prototype.assertContains = function (string, substring) {
        if (string.indexOf(substring) === -1)
            this.fail("Expected to: '" + string + "' to contain '" + substring + "'");
    };
    TestSuite.prototype.takeControl = function () {
        this.controlTaken_ = true;
        var self = this;
        this.timerId_ = setTimeout(function () {
            self.reportFailure_("Timeout exceeded: 20 sec");
        }, 20000);
    };
    TestSuite.prototype.releaseControl = function () {
        if (this.timerId_ !== -1) {
            clearTimeout(this.timerId_);
            this.timerId_ = -1;
        }
        this.reportOk_();
    };
    TestSuite.prototype.reportOk_ = function () {
        window.domAutomationController.send("[OK]");
    };
    TestSuite.prototype.reportFailure_ = function (error) {
        if (this.timerId_ !== -1) {
            clearTimeout(this.timerId_);
            this.timerId_ = -1;
        }
        window.domAutomationController.send("[FAILED] " + error);
    };
    TestSuite.prototype.runTest = function (testName) {
        try {
            this[testName]();
            if (!this.controlTaken_)
                this.reportOk_();
        } catch (e) {
            this.reportFailure_(e);
        }
    };
    TestSuite.prototype.showPanel = function (panelName) {
        var button = document.getElementById("tab-" + panelName);
        button.selectTabForTest();
        this.assertEquals(WebInspector.panels[panelName], WebInspector.inspectorView.currentPanel());
    };
    TestSuite.prototype.addSniffer = function (receiver, methodName, override, opt_sticky) {
        var orig = receiver[methodName];
        if (typeof orig !== "function")
            this.fail("Cannot find method to override: " + methodName);
        var test = this;
        receiver[methodName] = function (var_args) {
            try {
                var result = orig.apply(this, arguments);
            } finally {
                if (!opt_sticky)
                    receiver[methodName] = orig;
            }
            try {
                override.apply(this, arguments);
            } catch (e) {
                test.fail("Exception in overriden method '" + methodName + "': " + e);
            }
            return result;
        };
    };
    TestSuite.prototype.testShowScriptsTab = function () {
        this.showPanel("sources");
        var test = this;
        this._waitUntilScriptsAreParsed(["debugger_test_page.html"], function () {
            test.releaseControl();
        });
        this.takeControl();
    };
    TestSuite.prototype.testScriptsTabIsPopulatedOnInspectedPageRefresh = function () {
        var test = this;
        this.assertEquals(WebInspector.panels.elements, WebInspector.inspectorView.currentPanel(), "Elements panel should be current one.");
        WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
        test.evaluateInConsole_("window.location.reload(true);", function (resultText) {
        });
        function waitUntilScriptIsParsed() {
            WebInspector.debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed);
            test.showPanel("sources");
            test._waitUntilScriptsAreParsed(["debugger_test_page.html"], function () {
                test.releaseControl();
            });
        }

        this.takeControl();
    };
    TestSuite.prototype.testContentScriptIsPresent = function () {
        this.showPanel("sources");
        var test = this;
        test._waitUntilScriptsAreParsed(["page_with_content_script.html", "simple_content_script.js"], function () {
            test.releaseControl();
        });
        this.takeControl();
    };
    TestSuite.prototype.testNoScriptDuplicatesOnPanelSwitch = function () {
        var test = this;
        var expectedScriptsCount = 2;
        var parsedScripts = [];
        this.showPanel("sources");
        function switchToElementsTab() {
            test.showPanel("elements");
            setTimeout(switchToScriptsTab, 0);
        }

        function switchToScriptsTab() {
            test.showPanel("sources");
            setTimeout(checkScriptsPanel, 0);
        }

        function checkScriptsPanel() {
            test.assertTrue(test._scriptsAreParsed(["debugger_test_page.html"]), "Some scripts are missing.");
            checkNoDuplicates();
            test.releaseControl();
        }

        function checkNoDuplicates() {
            var uiSourceCodes = test.nonAnonymousUISourceCodes_();
            for (var i = 0; i < uiSourceCodes.length; i++) {
                var scriptName = uiSourceCodes[i].url;
                for (var j = i + 1; j < uiSourceCodes.length; j++)
                    test.assertTrue(scriptName !== uiSourceCodes[j].url, "Found script duplicates: " + test.uiSourceCodesToString_(uiSourceCodes));
            }
        }

        test._waitUntilScriptsAreParsed(["debugger_test_page.html"], function () {
            checkNoDuplicates();
            setTimeout(switchToElementsTab, 0);
        });
        this.takeControl();
    };
    TestSuite.prototype.testPauseWhenLoadingDevTools = function () {
        this.showPanel("sources");
        if (WebInspector.debuggerModel.debuggerPausedDetails)
            return;
        this._waitForScriptPause(this.releaseControl.bind(this));
        this.takeControl();
    };
    TestSuite.prototype.testPauseWhenScriptIsRunning = function () {
        this.showPanel("sources");
        this.evaluateInConsole_('setTimeout("handleClick()" , 0)', didEvaluateInConsole.bind(this));
        function didEvaluateInConsole(resultText) {
            this.assertTrue(!isNaN(resultText), "Failed to get timer id: " + resultText);
            setTimeout(testScriptPause.bind(this), 300);
        }

        function testScriptPause() {
            WebInspector.panels.sources._pauseButton.element.click();
            this._waitForScriptPause(this.releaseControl.bind(this));
        }

        this.takeControl();
    };
    TestSuite.prototype.testNetworkSize = function () {
        var test = this;

        function finishResource(resource, finishTime) {
            test.assertEquals(219, resource.transferSize, "Incorrect total encoded data length");
            test.assertEquals(25, resource.resourceSize, "Incorrect total data length");
            test.releaseControl();
        }

        this.addSniffer(WebInspector.NetworkDispatcher.prototype, "_finishNetworkRequest", finishResource);
        test.evaluateInConsole_("window.location.reload(true);", function (resultText) {
        });
        this.takeControl();
    };
    TestSuite.prototype.testNetworkSyncSize = function () {
        var test = this;

        function finishResource(resource, finishTime) {
            test.assertEquals(219, resource.transferSize, "Incorrect total encoded data length");
            test.assertEquals(25, resource.resourceSize, "Incorrect total data length");
            test.releaseControl();
        }

        this.addSniffer(WebInspector.NetworkDispatcher.prototype, "_finishNetworkRequest", finishResource);
        test.evaluateInConsole_("var xhr = new XMLHttpRequest(); xhr.open(\"GET\", \"chunked\", false); xhr.send(null);", function () {
        });
        this.takeControl();
    };
    TestSuite.prototype.testNetworkRawHeadersText = function () {
        var test = this;

        function finishResource(resource, finishTime) {
            if (!resource.responseHeadersText)
                test.fail("Failure: resource does not have response headers text");
            test.assertEquals(164, resource.responseHeadersText.length, "Incorrect response headers text length");
            test.releaseControl();
        }

        this.addSniffer(WebInspector.NetworkDispatcher.prototype, "_finishNetworkRequest", finishResource);
        test.evaluateInConsole_("window.location.reload(true);", function (resultText) {
        });
        this.takeControl();
    };
    TestSuite.prototype.testNetworkTiming = function () {
        var test = this;

        function finishResource(resource, finishTime) {
            test.assertTrue(resource.timing.receiveHeadersEnd - resource.timing.connectStart >= 70, "Time between receiveHeadersEnd and connectStart should be >=70ms, but was " + "receiveHeadersEnd=" + resource.timing.receiveHeadersEnd + ", connectStart=" + resource.timing.connectStart + ".");
            test.assertTrue(resource.responseReceivedTime - resource.startTime >= 0.07, "Time between responseReceivedTime and startTime should be >=0.07s, but was " + "responseReceivedTime=" + resource.responseReceivedTime + ", startTime=" + resource.startTime + ".");
            test.assertTrue(resource.endTime - resource.startTime >= 0.14, "Time between endTime and startTime should be >=0.14s, but was " + "endtime=" + resource.endTime + ", startTime=" + resource.startTime + ".");
            test.releaseControl();
        }

        this.addSniffer(WebInspector.NetworkDispatcher.prototype, "_finishNetworkRequest", finishResource);
        test.evaluateInConsole_("window.location.reload(true);", function (resultText) {
        });
        this.takeControl();
    };
    TestSuite.prototype.testConsoleOnNavigateBack = function () {
        if (WebInspector.multitargetConsoleModel.messages().length === 1)
            firstConsoleMessageReceived.call(this); else
            WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
        function firstConsoleMessageReceived() {
            WebInspector.multitargetConsoleModel.removeEventListener(WebInspector.ConsoleModel.Events.MessageAdded, firstConsoleMessageReceived, this);
            this.evaluateInConsole_("clickLink();", didClickLink.bind(this));
        }

        function didClickLink() {
            this.assertEquals(3, WebInspector.multitargetConsoleModel.messages().length);
            this.evaluateInConsole_("history.back();", didNavigateBack.bind(this));
        }

        function didNavigateBack() {
            this.evaluateInConsole_("void 0;", didCompleteNavigation.bind(this));
        }

        function didCompleteNavigation() {
            this.assertEquals(7, WebInspector.multitargetConsoleModel.messages().length);
            this.releaseControl();
        }

        this.takeControl();
    };
    TestSuite.prototype.testReattachAfterCrash = function () {
        PageAgent.navigate("about:crash");
        PageAgent.navigate("about:blank");
        WebInspector.runtimeModel.addEventListener(WebInspector.RuntimeModel.Events.ExecutionContextCreated, this.releaseControl, this);
    };
    TestSuite.prototype.testSharedWorker = function () {
        function didEvaluateInConsole(resultText) {
            this.assertEquals("2011", resultText);
            this.releaseControl();
        }

        this.evaluateInConsole_("globalVar", didEvaluateInConsole.bind(this));
        this.takeControl();
    };
    TestSuite.prototype.testPauseInSharedWorkerInitialization = function () {
        if (WebInspector.debuggerModel.debuggerPausedDetails)
            return;
        this._waitForScriptPause(this.releaseControl.bind(this));
        this.takeControl();
    };
    TestSuite.prototype.enableTouchEmulation = function () {
        WebInspector.targetManager.mainTarget().domModel.emulateTouchEventObjects(true);
    };
    TestSuite.prototype.testDeviceMetricsOverrides = function () {
        const dumpPageMetrics = function () {
            return JSON.stringify({width: window.innerWidth, height: window.innerHeight, deviceScaleFactor: window.devicePixelRatio});
        };
        var test = this;

        function testOverrides(params, metrics, callback) {
            PageAgent.invoke_setDeviceMetricsOverride(params, getMetrics);
            function getMetrics() {
                test.evaluateInConsole_("(" + dumpPageMetrics.toString() + ")()", checkMetrics);
            }

            function checkMetrics(consoleResult) {
                test.assertEquals('"' + JSON.stringify(metrics) + '"', consoleResult, "Wrong metrics for params: " + JSON.stringify(params));
                callback();
            }
        }

        function step1() {
            testOverrides({width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: true}, {width: 1200, height: 1000, deviceScaleFactor: 1}, step2);
        }

        function step2() {
            testOverrides({width: 1200, height: 1000, deviceScaleFactor: 1, mobile: false, fitWindow: false}, {width: 1200, height: 1000, deviceScaleFactor: 1}, step3);
        }

        function step3() {
            testOverrides({width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: true}, {width: 1200, height: 1000, deviceScaleFactor: 3}, step4);
        }

        function step4() {
            testOverrides({width: 1200, height: 1000, deviceScaleFactor: 3, mobile: false, fitWindow: false}, {width: 1200, height: 1000, deviceScaleFactor: 3}, finish);
        }

        function finish() {
            test.releaseControl();
        }

        step1();
        test.takeControl();
    };
    TestSuite.prototype.waitForTestResultsInConsole = function () {
        var messages = WebInspector.multitargetConsoleModel.messages();
        for (var i = 0; i < messages.length; ++i) {
            var text = messages[i].messageText;
            if (text === "PASS")
                return; else if (/^FAIL/.test(text))
                this.fail(text);
        }
        function onConsoleMessage(event) {
            var text = event.data.messageText;
            if (text === "PASS")
                this.releaseControl(); else if (/^FAIL/.test(text))
                this.fail(text);
        }

        WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
        this.takeControl();
    };
    TestSuite.prototype.checkLogAndErrorMessages = function () {
        var messages = WebInspector.multitargetConsoleModel.messages();
        var matchesCount = 0;

        function validMessage(message) {
            if (message.text === "log" && message.level === WebInspector.ConsoleMessage.MessageLevel.Log) {
                ++matchesCount;
                return true;
            }
            if (message.text === "error" && message.level === WebInspector.ConsoleMessage.MessageLevel.Error) {
                ++matchesCount;
                return true;
            }
            return false;
        }

        for (var i = 0; i < messages.length; ++i) {
            if (validMessage(messages[i]))
                continue;
            this.fail(messages[i].text + ":" + messages[i].level);
        }
        if (matchesCount === 2)
            return;
        function onConsoleMessage(event) {
            var message = event.data;
            if (validMessage(message)) {
                if (matchesCount === 2) {
                    this.releaseControl();
                    return;
                }
            } else
                this.fail(message.text + ":" + messages[i].level);
        }

        WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, onConsoleMessage, this);
        this.takeControl();
    };
    TestSuite.prototype.uiSourceCodesToString_ = function (uiSourceCodes) {
        var names = [];
        for (var i = 0; i < uiSourceCodes.length; i++)
            names.push('"' + uiSourceCodes[i].url + '"');
        return names.join(",");
    };
    TestSuite.prototype.nonAnonymousUISourceCodes_ = function () {
        function filterOutAnonymous(uiSourceCode) {
            return !!uiSourceCode.url;
        }

        function filterOutService(uiSourceCode) {
            return !uiSourceCode.project().isServiceProject();
        }

        var uiSourceCodes = WebInspector.workspace.uiSourceCodes();
        uiSourceCodes = uiSourceCodes.filter(filterOutService);
        return uiSourceCodes.filter(filterOutAnonymous);
    };
    TestSuite.prototype.evaluateInConsole_ = function (code, callback) {
        function innerEvaluate() {
            WebInspector.console.show();
            var consoleView = WebInspector.ConsolePanel._view();
            consoleView._prompt.text = code;
            consoleView._promptElement.dispatchEvent(TestSuite.createKeyEvent("Enter"));
            this.addSniffer(WebInspector.ConsoleView.prototype, "_showConsoleMessage", function (viewMessage) {
                callback(viewMessage.toMessageElement().textContent);
            }.bind(this));
        }

        if (!WebInspector.context.flavor(WebInspector.ExecutionContext)) {
            WebInspector.context.addFlavorChangeListener(WebInspector.ExecutionContext, innerEvaluate, this);
            return;
        }
        innerEvaluate.call(this);
    };
    TestSuite.prototype._scriptsAreParsed = function (expected) {
        var uiSourceCodes = this.nonAnonymousUISourceCodes_();
        var missing = expected.slice(0);
        for (var i = 0; i < uiSourceCodes.length; ++i) {
            for (var j = 0; j < missing.length; ++j) {
                if (uiSourceCodes[i].name().search(missing[j]) !== -1) {
                    missing.splice(j, 1);
                    break;
                }
            }
        }
        return missing.length === 0;
    };
    TestSuite.prototype._waitForScriptPause = function (callback) {
        function pauseListener(event) {
            WebInspector.debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, pauseListener, this);
            callback();
        }

        WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, pauseListener, this);
    };
    TestSuite.prototype._executeCodeWhenScriptsAreParsed = function (code, expectedScripts) {
        var test = this;

        function executeFunctionInInspectedPage() {
            test.evaluateInConsole_('setTimeout("' + code + '" , 0)', function (resultText) {
                test.assertTrue(!isNaN(resultText), "Failed to get timer id: " + resultText + ". Code: " + code);
            });
        }

        test._waitUntilScriptsAreParsed(expectedScripts, executeFunctionInInspectedPage);
    };
    TestSuite.prototype._waitUntilScriptsAreParsed = function (expectedScripts, callback) {
        var test = this;

        function waitForAllScripts() {
            if (test._scriptsAreParsed(expectedScripts))
                callback(); else
                test.addSniffer(WebInspector.panels.sources.sourcesView(), "_addUISourceCode", waitForAllScripts);
        }

        waitForAllScripts();
    };
    TestSuite.createKeyEvent = function (keyIdentifier) {
        var evt = document.createEvent("KeyboardEvent");
        evt.initKeyboardEvent("keydown", true, true, null, keyIdentifier, "");
        return evt;
    };
    var uiTests = {};
    uiTests.runAllTests = function () {
        for (var name in TestSuite.prototype) {
            if (name.substring(0, 4) === "test" && typeof TestSuite.prototype[name] === "function")
                uiTests.runTest(name);
        }
    };
    uiTests.runTest = function (name) {
        if (uiTests._populatedInterface)
            new TestSuite().runTest(name); else
            uiTests._pendingTestName = name;
    };
    (function () {
        function runTests() {
            uiTests._populatedInterface = true;
            var name = uiTests._pendingTestName;
            delete uiTests._pendingTestName;
            if (name)
                new TestSuite().runTest(name);
        }

        WebInspector.notifications.addEventListener(WebInspector.NotificationService.Events.InspectorUILoadedForTests, runTests);
    })();
}