chrome的devtool源码inspectjs
来源:互联网 发布:城市地图制作软件 编辑:程序博客网 时间:2024/05/16 09:25
var allDescriptors = [{ "dependencies": ["platform", "common", "host", "ui"], "name": "ui_lazy", "scripts": []}, { "experiment": "promiseTracker", "extensions": [{ "className": "WebInspector.PromisePane", "order": "30", "type": "drawer-view", "name": "promises", "title": "Promises" }], "name": "promises", "dependencies": ["components", "ui_lazy"], "scripts": []}, { "experiment": "accessibilityInspection", "extensions": [{ "className": "WebInspector.AccessibilitySidebarView", "type": "@WebInspector.Widget", "location": "elements-panel", "title": "Accessibility" }], "name": "accessibility", "dependencies": ["elements"], "scripts": []}, { "dependencies": ["source_frame", "snippets", "extensions"], "extensions": [{ "className": "WebInspector.SourcesPanelFactory", "order": 2, "type": "@WebInspector.PanelFactory", "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.UILocation", "WebInspector.RemoteObject", "WebInspector.NetworkRequest"], "type": "@WebInspector.ContextMenu.Provider" }, { "className": "WebInspector.SourcesPanel.RevealingActionDelegate", "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.SourcesPanel.DebuggingActionDelegate", "contextTypes": ["WebInspector.SourcesPanel"], "bindings": [{ "platform": "windows,linux", "shortcut": "F10 Ctrl+'" }, { "platform": "mac", "shortcut": "F10 Meta+'" }], "type": "@WebInspector.ActionDelegate", "actionId": "debugger.step-over" }, { "className": "WebInspector.SourcesPanel.DebuggingActionDelegate", "contextTypes": ["WebInspector.SourcesPanel"], "bindings": [{ "platform": "windows,linux", "shortcut": "F11 Ctrl+;" }, { "platform": "mac", "shortcut": "F11 Meta+;" }], "type": "@WebInspector.ActionDelegate", "actionId": "debugger.step-into" }, { "className": "WebInspector.SourcesPanel.DebuggingActionDelegate", "experiment": "stepIntoAsync", "contextTypes": ["WebInspector.SourcesPanel"], "actionId": "debugger.step-into-async", "bindings": [{ "platform": "windows,linux", "shortcut": "Alt+F11 Alt+Ctrl+;" }, { "platform": "mac", "shortcut": "Alt+F11 Alt+Meta+;" }], "type": "@WebInspector.ActionDelegate" }, { "className": "WebInspector.SourcesPanel.DebuggingActionDelegate", "contextTypes": ["WebInspector.SourcesPanel"], "bindings": [{ "platform": "windows,linux", "shortcut": "Shift+F11 Shift+Ctrl+;" }, { "platform": "mac", "shortcut": "Shift+F11 Shift+Meta+;" }], "type": "@WebInspector.ActionDelegate", "actionId": "debugger.step-out" }, { "className": "WebInspector.SourcesPanel.DebuggingActionDelegate", "contextTypes": ["WebInspector.SourcesPanel"], "bindings": [{ "platform": "windows,linux", "shortcut": "Ctrl+Enter" }, { "platform": "mac", "shortcut": "Meta+Enter" }], "type": "@WebInspector.ActionDelegate", "actionId": "debugger.run-snippet" }, { "className": "WebInspector.AdvancedSearchView.ActionDelegate", "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.DebuggerLocationRevealer", "contextTypes": ["WebInspector.DebuggerModel.Location"], "type": "@WebInspector.Revealer" }, { "className": "WebInspector.SourcesPanel.UISourceCodeRevealer", "contextTypes": ["WebInspector.UISourceCode"], "type": "@WebInspector.Revealer" }, { "className": "WebInspector.SourcesPanel.DebuggerPausedDetailsRevealer", "contextTypes": ["WebInspector.DebuggerPausedDetails"], "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.RevealingActionDelegate", "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" }, { "category": "Sources", "title": "Search in content scripts", "defaultValue": false, "settingName": "searchInContentScripts", "settingType": "boolean", "type": "setting" }, { "category": "Sources", "title": "Enable JavaScript source maps", "defaultValue": true, "settingName": "jsSourceMapsEnabled", "settingType": "boolean", "type": "setting" }, { "category": "Sources", "title": "Detect indentation", "defaultValue": true, "settingName": "textEditorAutoDetectIndent", "settingType": "boolean", "type": "setting" }, { "category": "Sources", "title": "Autocompletion", "defaultValue": true, "settingName": "textEditorAutocompletion", "settingType": "boolean", "type": "setting" }, { "category": "Sources", "title": "Bracket matching", "defaultValue": true, "settingName": "textEditorBracketMatching", "settingType": "boolean", "type": "setting" }, { "category": "Sources", "title": "Show whitespace characters:", "defaultValue": "original", "settingName": "showWhitespacesInEditor", "settingType": "enum", "type": "setting", "options": [["None", "none"], ["All", "all"], ["Trailing", "trailing"]] }, { "category": "Sources", "title": "Display variable values inline while debugging", "defaultValue": true, "settingName": "inlineVariableValues", "settingType": "boolean", "type": "setting" }, { "category": "Sources", "title": "Enable CSS source maps", "defaultValue": true, "settingName": "cssSourceMapsEnabled", "settingType": "boolean", "type": "setting" }, { "title": "Auto-reload generated CSS", "defaultValue": false, "parentSettingName": "cssSourceMapsEnabled", "settingName": "cssReloadEnabled", "settingType": "boolean", "type": "setting" }], "name": "sources", "scripts": [], "skip_compilation": ["jsdifflib.js"]}, { "remote": true, "name": "emulated_devices", "dependencies": ["emulation"], "extensions": [{ "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Apple iPhone 4", "screen": { "horizontal": { "width": 480, "height": 320 }, "device-pixel-ratio": 2, "vertical": { "width": 320, "height": 480 } }, "capabilities": ["touch", "mobile"], "user-agent": "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", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Apple iPhone 5", "screen": { "horizontal": { "width": 568, "height": 320 }, "device-pixel-ratio": 2, "vertical": { "width": 320, "height": 568 } }, "capabilities": ["touch", "mobile"], "user-agent": "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", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 40, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 64, "right": 0, "bottom": 45, "left": 0 }, "orientation": "vertical", "title": "navigation bar" }, { "insets": { "top": 40, "right": 0, "bottom": 260, "left": 0 }, "orientation": "vertical", "title": "keyboard" }, { "insets": { "top": 64, "right": 0, "bottom": 260, "left": 0 }, "orientation": "vertical", "title": "navigation bar and keyboard" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }, { "insets": { "top": 44, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "navigation bar" }, { "insets": { "top": 0, "right": 0, "bottom": 206, "left": 0 }, "orientation": "horizontal", "title": "keyboard" }, { "insets": { "top": 44, "right": 0, "bottom": 206, "left": 0 }, "orientation": "horizontal", "title": "navigation bar and keyboard" }], "title": "Apple iPhone 6", "screen": { "horizontal": { "width": 667, "height": 375 }, "device-pixel-ratio": 2, "vertical": { "width": 375, "height": 667 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Apple iPhone 6 Plus", "screen": { "horizontal": { "width": 736, "height": 414 }, "device-pixel-ratio": 3, "vertical": { "width": 414, "height": 736 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "BlackBerry Z30", "screen": { "horizontal": { "width": 640, "height": 360 }, "device-pixel-ratio": 2, "vertical": { "width": 360, "height": 640 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 25, "right": 0, "bottom": 48, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 80, "right": 0, "bottom": 48, "left": 0 }, "orientation": "vertical", "title": "navigation bar" }, { "insets": { "top": 80, "right": 0, "bottom": 326, "left": 0 }, "orientation": "vertical", "title": "keyboard" }, { "insets": { "top": 25, "right": 42, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }, { "insets": { "top": 80, "right": 42, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "navigation bar" }, { "insets": { "top": 80, "right": 42, "bottom": 214, "left": 0 }, "orientation": "horizontal", "title": "keyboard" }], "title": "Google Nexus 4", "screen": { "horizontal": { "width": 640, "height": 384 }, "device-pixel-ratio": 2, "vertical": { "width": 384, "height": 640 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.122 Mobile Safari/537.36", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 25, "right": 0, "bottom": 48, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 80, "right": 0, "bottom": 48, "left": 0 }, "orientation": "vertical", "title": "navigation bar" }, { "insets": { "top": 80, "right": 0, "bottom": 312, "left": 0 }, "orientation": "vertical", "title": "keyboard" }, { "insets": { "top": 25, "right": 42, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }, { "insets": { "top": 80, "right": 42, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "navigation bar" }, { "insets": { "top": 80, "right": 42, "bottom": 202, "left": 0 }, "orientation": "horizontal", "title": "keyboard" }], "title": "Google Nexus 5", "screen": { "horizontal": { "width": 640, "height": 360 }, "device-pixel-ratio": 3, "vertical": { "width": 360, "height": 640 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (Linux; Android 4.4.4; Nexus 5 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.114 Mobile Safari/537.36", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 25, "right": 0, "bottom": 48, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 80, "right": 0, "bottom": 48, "left": 0 }, "orientation": "vertical", "title": "navigation bar" }, { "insets": { "top": 80, "right": 0, "bottom": 343, "left": 0 }, "orientation": "vertical", "title": "keyboard" }, { "insets": { "top": 25, "right": 42, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }, { "insets": { "top": 80, "right": 42, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "navigation bar" }, { "insets": { "top": 80, "right": 42, "bottom": 222, "left": 0 }, "orientation": "horizontal", "title": "keyboard" }], "title": "Google Nexus 6", "screen": { "horizontal": { "width": 732, "height": 412 }, "device-pixel-ratio": 3.5, "vertical": { "width": 412, "height": 732 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.20 Mobile Safari/537.36", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "LG Optimus L70", "screen": { "horizontal": { "width": 640, "height": 384 }, "device-pixel-ratio": 1.25, "vertical": { "width": 384, "height": 640 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.1599.103 Mobile Safari/537.36", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Nokia N9", "screen": { "horizontal": { "width": 640, "height": 360 }, "device-pixel-ratio": 1, "vertical": { "width": 360, "height": 640 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Nokia Lumia 520", "screen": { "horizontal": { "width": 533, "height": 320 }, "device-pixel-ratio": 1.4, "vertical": { "width": 320, "height": 533 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Samsung Galaxy S III", "screen": { "horizontal": { "width": 640, "height": 360 }, "device-pixel-ratio": 2, "vertical": { "width": 360, "height": 640 } }, "capabilities": ["touch", "mobile"], "user-agent": "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", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Samsung Galaxy S4", "screen": { "horizontal": { "width": 640, "height": 360 }, "device-pixel-ratio": 3, "vertical": { "width": 360, "height": 640 } }, "capabilities": ["touch", "mobile"], "user-agent": "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", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Amazon Kindle Fire HDX", "screen": { "horizontal": { "width": 2560, "height": 1600 }, "device-pixel-ratio": 2, "vertical": { "width": 1600, "height": 2560 } }, "capabilities": ["touch", "mobile"], "user-agent": "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", "type": "tablet" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Apple iPad Mini", "screen": { "horizontal": { "width": 1024, "height": 768 }, "device-pixel-ratio": 2, "vertical": { "width": 768, "height": 1024 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (iPad; CPU OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53", "type": "tablet" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Apple iPad", "screen": { "horizontal": { "width": 1024, "height": 768 }, "device-pixel-ratio": 2, "vertical": { "width": 768, "height": 1024 } }, "capabilities": ["touch", "mobile"], "user-agent": "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", "type": "tablet" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "BlackBerry PlayBook", "screen": { "horizontal": { "width": 1024, "height": 600 }, "device-pixel-ratio": 1, "vertical": { "width": 600, "height": 1024 } }, "capabilities": ["touch", "mobile"], "user-agent": "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+", "type": "tablet" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Google Nexus 10", "screen": { "horizontal": { "width": 1280, "height": 800 }, "device-pixel-ratio": 2, "vertical": { "width": 800, "height": 1280 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Safari/537.36", "type": "tablet" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Google Nexus 7", "screen": { "horizontal": { "width": 960, "height": 600 }, "device-pixel-ratio": 2, "vertical": { "width": 600, "height": 960 } }, "capabilities": ["touch", "mobile"], "user-agent": "Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Safari/537.36", "type": "tablet" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Samsung Galaxy Note 3", "screen": { "horizontal": { "width": 640, "height": 360 }, "device-pixel-ratio": 3, "vertical": { "width": 360, "height": 640 } }, "capabilities": ["touch", "mobile"], "user-agent": "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", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "vertical", "title": "default" }, { "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Samsung Galaxy Note II", "screen": { "horizontal": { "width": 640, "height": 360 }, "device-pixel-ratio": 2, "vertical": { "width": 360, "height": 640 } }, "capabilities": ["touch", "mobile"], "user-agent": "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", "type": "phone" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Laptop with touch", "screen": { "horizontal": { "width": 1280, "height": 950 }, "device-pixel-ratio": 1, "vertical": { "width": 950, "height": 1280 } }, "capabilities": ["touch"], "user-agent": "", "type": "notebook" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Laptop with HiDPI screen", "screen": { "horizontal": { "width": 1440, "height": 900 }, "device-pixel-ratio": 2, "vertical": { "width": 900, "height": 1440 } }, "capabilities": [], "user-agent": "", "type": "notebook" }, "type": "emulated-device" }, { "device": { "show-by-default": true, "modes": [{ "insets": { "top": 0, "right": 0, "bottom": 0, "left": 0 }, "orientation": "horizontal", "title": "default" }], "title": "Laptop with MDPI screen", "screen": { "horizontal": { "width": 1280, "height": 800 }, "device-pixel-ratio": 1, "vertical": { "width": 800, "height": 1280 } }, "capabilities": [], "user-agent": "", "type": "notebook" }, "type": "emulated-device" }], "scripts": []}, { "dependencies": ["components", "extensions"], "extensions": [{ "className": "WebInspector.AuditsPanelFactory", "order": 6, "type": "@WebInspector.PanelFactory", "name": "audits", "title": "Audits" }], "name": "audits", "scripts": []}, { "dependencies": ["sdk", "platform", "workspace"], "name": "bindings", "scripts": []}, { "dependencies": ["bindings"], "name": "snippets", "scripts": []}, { "dependencies": ["timeline"], "extensions": [{ "className": "WebInspector.LayersPanelFactory", "order": 7, "type": "@WebInspector.PanelFactory", "name": "layers", "title": "Layers" }, { "className": "WebInspector.LayersPanel.LayerTreeRevealer", "contextTypes": ["WebInspector.DeferredLayerTree"], "type": "@WebInspector.Revealer" }], "experiment": "layersPanel", "scripts": [], "name": "layers"}, { "dependencies": ["components", "ui_lazy"], "extensions": [{ "className": "WebInspector.ConsolePanelFactory", "order": 20, "type": "@WebInspector.PanelFactory", "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" }, { "category": "Console", "title": "Hide network messages", "defaultValue": false, "settingName": "hideNetworkMessages", "settingType": "boolean", "type": "setting" }, { "category": "Console", "title": "Log XMLHttpRequests", "defaultValue": false, "settingName": "monitoringXHREnabled", "settingType": "boolean", "type": "setting" }, { "category": "Console", "title": "Preserve log upon navigation", "defaultValue": false, "settingName": "preserveConsoleLog", "settingType": "boolean", "type": "setting" }, { "category": "Console", "title": "Show timestamps", "defaultValue": false, "settingName": "consoleTimestampsEnabled", "settingType": "boolean", "type": "setting" }], "name": "console", "scripts": []}, { "dependencies": ["source_frame", "components_lazy", "ui_lazy"], "extensions": [{ "className": "WebInspector.NetworkPanelFactory", "order": 1, "type": "@WebInspector.PanelFactory", "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" }, { "category": "Network", "title": "Show primary load waterfall", "defaultValue": false, "experiment": "showPrimaryLoadWaterfallInNetworkTimeline", "settingName": "networkShowPrimaryLoadWaterfall", "settingType": "boolean", "type": "setting" }, { "category": "Network", "title": "Color-code resource types", "defaultValue": false, "settingName": "networkColorCodeResourceTypes", "settingType": "boolean", "type": "setting" }], "name": "network", "scripts": []}, { "dependencies": ["sdk", "ui", "ui_lazy"], "name": "components_lazy", "scripts": []}, { "remote": true, "name": "cm_modes", "dependencies": ["source_frame"], "extensions": [{ "className": "WebInspector.DefaultCodeMirrorMimeMode", "mimeTypes": ["text/x-csrc", "text/x-c", "text/x-chdr", "text/x-c++src", "text/x-c++hdr", "text/x-java", "text/x-csharp", "text/x-scala", "x-shader/x-vertex", "x-shader/x-fragment"], "type": "@WebInspector.CodeMirrorMimeMode", "fileName": "clike.js" }, { "className": "WebInspector.DefaultCodeMirrorMimeMode", "mimeTypes": ["text/x-coffeescript"], "type": "@WebInspector.CodeMirrorMimeMode", "fileName": "coffeescript.js" }, { "className": "WebInspector.DefaultCodeMirrorMimeMode", "mimeTypes": ["application/x-httpd-php", "application/x-httpd-php-open", "text/x-php"], "dependencies": ["clike.js"], "type": "@WebInspector.CodeMirrorMimeMode", "fileName": "php.js" }, { "className": "WebInspector.DefaultCodeMirrorMimeMode", "mimeTypes": ["text/x-python", "text/x-cython"], "type": "@WebInspector.CodeMirrorMimeMode", "fileName": "python.js" }, { "className": "WebInspector.DefaultCodeMirrorMimeMode", "mimeTypes": ["text/x-sh"], "type": "@WebInspector.CodeMirrorMimeMode", "fileName": "shell.js" }, { "className": "WebInspector.DefaultCodeMirrorMimeMode", "mimeTypes": ["text/x-livescript"], "type": "@WebInspector.CodeMirrorMimeMode", "fileName": "livescript.js" }, { "className": "WebInspector.DefaultCodeMirrorMimeMode", "mimeTypes": ["text/x-clojure"], "type": "@WebInspector.CodeMirrorMimeMode", "fileName": "clojure.js" }], "scripts": []}, { "dependencies": [], "name": "platform", "scripts": []}, { "dependencies": ["elements"], "extensions": [{ "className": "WebInspector.AnimationControlPane.ButtonProvider", "type": "@WebInspector.ToolbarItem.Provider", "order": 2, "location": "styles-sidebarpane-toolbar" }], "name": "animation", "scripts": []}, { "dependencies": ["components"], "extensions": [{ "className": "WebInspector.CodeMirrorUtils", "type": "@WebInspector.InplaceEditor" }, { "className": "WebInspector.CodeMirrorUtils.TokenizerFactory", "type": "@WebInspector.TokenizerFactory" }, { "category": "Sources", "title": "Default indentation:", "defaultValue": " ", "settingName": "textEditorIndent", "settingType": "enum", "type": "setting", "options": [["2 spaces", " "], ["4 spaces", " "], ["8 spaces", " "], ["Tab character", "\t"]] }], "name": "source_frame", "scripts": [], "skip_compilation": ["../cm/codemirror.js", "../cm/css.js", "../cm/javascript.js", "../cm/xml.js", "../cm/htmlmixed.js", "../cm/htmlembedded.js", "../cm/matchbrackets.js", "../cm/closebrackets.js", "../cm/markselection.js", "../cm/comment.js", "../cm/overlay.js", "../cm/activeline.js"]}, { "dependencies": ["extensions", "host", "platform", "sdk", "emulation"], "extensions": [{ "className": "WebInspector.AdvancedAppProvider", "type": "@WebInspector.AppProvider", "order": 0, "condition": "can_dock" }, { "className": "WebInspector.SimpleAppProvider", "type": "@WebInspector.AppProvider", "order": 10 }, { "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.ReloadActionDelegate", "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.ReloadActionDelegate", "bindings": [{ "shortcut": "Alt+R" }], "type": "@WebInspector.ActionDelegate", "actionId": "main.debug-reload" }, { "className": "WebInspector.InspectElementModeController.ToggleSearchActionDelegate", "contextTypes": ["WebInspector.InspectElementModeController"], "bindings": [{ "platform": "windows,linux", "shortcut": "Ctrl+Shift+C" }, { "platform": "mac", "shortcut": "Meta+Shift+C" }], "type": "@WebInspector.ActionDelegate", "actionId": "main.toggle-element-search" }, { "className": "WebInspector.DockController.ToggleDockActionDelegate", "bindings": [{ "platform": "windows,linux", "shortcut": "Ctrl+Shift+D" }, { "platform": "mac", "shortcut": "Meta+Shift+D" }], "type": "@WebInspector.ActionDelegate", "actionId": "main.toggle-dock" }, { "className": "WebInspector.Main.ZoomActionDelegate", "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.ZoomActionDelegate", "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.ZoomActionDelegate", "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.RenderingOptions.View", "order": "11", "type": "drawer-view", "name": "rendering", "title": "Rendering" }, { "className": "WebInspector.InspectElementModeController.ToggleButtonProvider", "actionId": "main.toggle-element-search", "type": "@WebInspector.ToolbarItem.Provider", "location": "main-toolbar-left", "order": 0 }, { "separator": true, "type": "@WebInspector.ToolbarItem.Provider", "location": "main-toolbar-left", "order": 100 }, { "className": "WebInspector.Main.WarningErrorCounter", "type": "@WebInspector.ToolbarItem.Provider", "order": 1, "location": "main-toolbar-right" }, { "className": "WebInspector.InspectorView.ToggleDrawerButtonProvider", "type": "@WebInspector.ToolbarItem.Provider", "order": 2, "location": "main-toolbar-right" }, { "separator": true, "type": "@WebInspector.ToolbarItem.Provider", "order": 3, "location": "main-toolbar-right" }, { "className": "WebInspector.DockController.ButtonProvider", "type": "@WebInspector.ToolbarItem.Provider", "order": 5, "location": "main-toolbar-right" }, { "separator": true, "type": "@WebInspector.ToolbarItem.Provider", "order": 90, "location": "main-toolbar-right" }, { "className": "WebInspector.DockController.CloseButtonProvider", "type": "@WebInspector.ToolbarItem.Provider", "order": 100, "location": "main-toolbar-right" }, { "category": "", "title": "Disable cache (while DevTools is open)", "defaultValue": false, "settingName": "cacheDisabled", "settingType": "boolean", "type": "setting" }, { "defaultValue": { "latency": 0, "throughput": -1 }, "type": "setting", "settingName": "networkConditions", "settingType": "object" }, { "category": "", "title": "Disable JavaScript", "defaultValue": false, "settingName": "javaScriptDisabled", "settingType": "boolean", "type": "setting" }, { "category": "Appearance", "title": "Split panels vertically when docked to right", "defaultValue": true, "settingName": "splitVerticallyWhenDockedToRight", "settingType": "boolean", "type": "setting" }, { "category": "Appearance", "title-mac": "Enable Cmd + 1-9 shortcut to switch panels", "title": "Enable Ctrl + 1-9 shortcut to switch panels", "defaultValue": false, "settingName": "shortcutPanelSwitch", "settingType": "boolean", "type": "setting" }, { "category": "Appearance", "title": "Don't show emulation warnings", "defaultValue": false, "settingName": "disableOverridesWarning", "settingType": "boolean", "type": "setting" }, { "category": "Appearance", "title": "Don't show Chrome Data Saver warning", "defaultValue": false, "settingName": "disableDataSaverInfobar", "settingType": "boolean", "type": "setting" }, { "category": "Appearance", "title": "Disable paused state overlay", "defaultValue": false, "settingName": "disablePausedStateOverlay", "settingType": "boolean", "type": "setting" }, { "category": "Extensions", "className": "WebInspector.HandlerRegistry.OpenAnchorLocationSettingUI", "type": "@WebInspector.SettingUI" }, { "defaultValue": false, "type": "setting", "settingName": "showPaintRects", "settingType": "boolean" }, { "defaultValue": false, "type": "setting", "settingName": "showDebugBorders", "settingType": "boolean" }, { "defaultValue": false, "type": "setting", "settingName": "showFPSCounter", "settingType": "boolean" }, { "defaultValue": false, "type": "setting", "settingName": "continuousPainting", "settingType": "boolean" }, { "defaultValue": false, "type": "setting", "settingName": "showScrollBottleneckRects", "settingType": "boolean" }], "name": "main", "scripts": [], "skip_compilation": ["Tests.js"]}, { "dependencies": ["source_frame", "ui_lazy", "components_lazy"], "extensions": [{ "className": "WebInspector.ResourcesPanelFactory", "order": 5, "type": "@WebInspector.PanelFactory", "name": "resources", "title": "Resources" }, { "className": "WebInspector.ResourcesPanel.ResourceRevealer", "contextTypes": ["WebInspector.Resource"], "type": "@WebInspector.Revealer" }], "name": "resources", "scripts": []}, { "skip_compilation": ["../acorn/acorn.js", "../cm/headlesscodemirror.js", "../cm/css.js", "../cm/xml.js", "../cm/htmlmixed.js"], "name": "script_formatter_worker", "scripts": []}, { "dependencies": ["components", "extensions"], "extensions": [{ "className": "WebInspector.ElementsPanelFactory", "order": 0, "type": "@WebInspector.PanelFactory", "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", "WebInspector.RemoteObject"], "type": "@WebInspector.Renderer" }, { "className": "WebInspector.ElementsPanel.DOMNodeRevealer", "contextTypes": ["WebInspector.DOMNode", "WebInspector.DeferredDOMNode", "WebInspector.RemoteObject"], "type": "@WebInspector.Revealer" }, { "category": "Elements", "title": "Color format:", "defaultValue": "original", "settingName": "colorFormat", "settingType": "enum", "type": "setting", "options": [["As authored", "original"], ["HEX: #DAC0DE", "hex", true], ["RGB: rgb(128, 255, 255)", "rgb", true], ["HSL: hsl(300, 80%, 90%)", "hsl", true]] }, { "category": "Elements", "title": "Show user agent shadow DOM", "defaultValue": false, "settingName": "showUAShadowDOM", "settingType": "boolean", "type": "setting" }, { "category": "Elements", "title": "Word wrap", "defaultValue": true, "settingName": "domWordWrap", "settingType": "boolean", "type": "setting" }, { "category": "Elements", "title": "Show rulers", "defaultValue": false, "settingName": "showMetricsRulers", "settingType": "boolean", "type": "setting" }, { "category": "Elements", "title": "Highlight DOM updates", "defaultValue": true, "settingName": "highlightDOMUpdates", "settingType": "boolean", "type": "setting" }, { "className": "WebInspector.StylesSidebarPane.AddNewRuleButtonProvider", "type": "@WebInspector.ToolbarItem.Provider", "order": 0, "location": "styles-sidebarpane-toolbar" }, { "className": "WebInspector.ElementStatePaneWidget.ButtonProvider", "type": "@WebInspector.ToolbarItem.Provider", "order": 1, "location": "styles-sidebarpane-toolbar" }], "name": "elements", "scripts": []}, { "dependencies": ["common", "host", "platform"], "name": "workspace", "scripts": []}, { "dependencies": ["components", "components_lazy", "ui_lazy"], "extensions": [{ "className": "WebInspector.TimelinePanelFactory", "order": 3, "type": "@WebInspector.PanelFactory", "name": "timeline", "title": "Timeline" }, { "category": "Profiler", "title": "Hide chrome frame in Layers view", "defaultValue": false, "settingName": "frameViewerHideChromeWindow", "settingType": "boolean", "type": "setting" }, { "className": "WebInspector.LoadTimelineHandler", "type": "@WebInspector.QueryParamHandler", "name": "loadTimelineFromURL" }], "name": "timeline", "scripts": []}, { "dependencies": ["common", "platform"], "name": "host", "scripts": []}, { "dependencies": ["bindings", "components", "platform", "ui"], "extensions": [{ "className": "WebInspector.OverridesView", "order": "10", "type": "drawer-view", "name": "emulation", "title": "Emulation" }, { "className": "WebInspector.DeviceModeButtonProvider", "type": "@WebInspector.ToolbarItem.Provider", "order": 1, "condition": "can_dock", "location": "main-toolbar-left" }, { "className": "WebInspector.ToggleDeviceModeActionDelegate", "bindings": [{ "platform": "windows,linux", "shortcut": "Shift+Ctrl+M" }, { "platform": "mac", "shortcut": "Shift+Meta+M" }], "type": "@WebInspector.ActionDelegate", "actionId": "emulation.toggle-device-mode", "condition": "can_dock" }, { "className": "WebInspector.OverridesView.Revealer", "contextTypes": ["WebInspector.OverridesSupport"], "type": "@WebInspector.Revealer" }, { "className": "WebInspector.DevicesSettingsTab", "order": "30", "type": "settings-view", "name": "devices", "title": "Devices" }], "name": "emulation", "scripts": []}, { "dependencies": ["platform", "common", "host"], "name": "ui", "scripts": []}, { "skip_compilation": ["../InspectorBackendCommands.js", "../SupportedCSSProperties.js"], "dependencies": ["common", "host", "platform"], "extensions": [{ "defaultValue": "", "type": "setting", "settingName": "skipStackFramesPattern", "settingType": "regex" }, { "defaultValue": false, "type": "setting", "settingName": "skipContentScripts", "settingType": "boolean" }, { "defaultValue": false, "type": "setting", "settingName": "pauseOnExceptionEnabled", "settingType": "boolean" }, { "defaultValue": false, "type": "setting", "settingName": "pauseOnCaughtException", "settingType": "boolean" }, { "defaultValue": false, "type": "setting", "settingName": "enableAsyncStackTraces", "settingType": "boolean" }], "name": "sdk", "scripts": []}, { "name": "temp_storage_shared_worker", "scripts": []}, { "dependencies": ["components"], "extensions": [{ "className": "WebInspector.SettingsController.ActionDelegate", "bindings": [{ "shortcut": "F1 Shift+?" }], "type": "@WebInspector.ActionDelegate", "actionId": "settings.show" }, { "title": "Settings", "elementClass": "settings-toolbar-item", "actionId": "settings.show", "type": "@WebInspector.ToolbarItem.Provider", "order": 4, "location": "main-toolbar-right" }, { "title": "Settings", "elementClass": "settings-toolbar-item", "actionId": "settings.show", "type": "@WebInspector.ToolbarItem.Provider", "order": 1, "location": "elements-toolbar" }, { "category": "Sources", "className": "WebInspector.SettingsScreen.SkipStackFramePatternSettingUI", "type": "@WebInspector.SettingUI" }], "name": "settings", "scripts": []}, { "name": "heap_snapshot_worker", "scripts": []}, { "dependencies": ["components", "ui_lazy"], "extensions": [{ "className": "WebInspector.ProfilesPanelFactory", "order": 4, "type": "@WebInspector.PanelFactory", "name": "profiles", "title": "Profiles" }, { "className": "WebInspector.ProfilesPanel.ContextMenuProvider", "contextTypes": ["WebInspector.RemoteObject"], "type": "@WebInspector.ContextMenu.Provider" }, { "category": "Profiler", "title": "Show advanced heap snapshot properties", "defaultValue": false, "settingName": "showAdvancedHeapSnapshotProperties", "settingType": "boolean", "type": "setting" }, { "category": "Profiler", "title": "Record heap allocation stack traces", "defaultValue": false, "settingName": "recordAllocationStacks", "settingType": "boolean", "type": "setting" }, { "category": "Profiler", "title": "High resolution CPU profiling", "defaultValue": false, "settingName": "highResolutionCpuProfiling", "settingType": "boolean", "type": "setting" }], "name": "profiler", "scripts": []}, { "remote": true, "name": "screencast", "dependencies": ["components"], "extensions": [{ "className": "WebInspector.ScreencastAppProvider", "type": "@WebInspector.AppProvider", "order": 1 }, { "className": "WebInspector.ScreencastApp.ToolbarButtonProvider", "type": "@WebInspector.ToolbarItem.Provider", "order": 1, "location": "main-toolbar-left" }], "scripts": [], "condition": "remoteFrontend"}, { "dependencies": ["components"], "name": "extensions", "scripts": []}, { "skip_compilation": ["TestBase.js"], "dependencies": ["platform"], "name": "common", "scripts": []}, { "dependencies": ["bindings", "platform", "ui"], "extensions": [{ "category": "Console", "title": "Enable custom formatters", "defaultValue": false, "experiment": "customObjectFormatters", "settingName": "customFormatters", "settingType": "boolean", "type": "setting" }], "name": "components", "scripts": []}, { "experiment": "securityPanel", "extensions": [{ "className": "WebInspector.SecurityPanelFactory", "order": 7, "type": "@WebInspector.PanelFactory", "name": "security", "title": "Security" }], "name": "security", "dependencies": ["platform", "ui", "sdk"], "scripts": []}];var applicationDescriptor;var _loadedScripts = {};for (var k of []) ;function loadResourcePromise(url) { return new Promise(load); function load(fulfill, reject) { var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.onreadystatechange = onreadystatechange; function onreadystatechange(e) { if (xhr.readyState !== 4) return; if ([0, 200, 304].indexOf(xhr.status) === -1) reject(new Error("While loading from url " + url + " server responded with a status of " + xhr.status)); else fulfill(e.target.response); } xhr.send(null ); }}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 loadScriptsPromise(scriptNames, base) { var promises = []; var urls = []; var sources = new Array(scriptNames.length); var scriptToEval = 0; for (var i = 0; i < scriptNames.length; ++i) { var scriptName = scriptNames[i]; var sourceURL = (base || self._importScriptPathPrefix) + scriptName; var schemaIndex = sourceURL.indexOf("://") + 3; sourceURL = sourceURL.substring(0, schemaIndex) + normalizePath(sourceURL.substring(schemaIndex)); if (_loadedScripts[sourceURL]) continue;urls.push(sourceURL); promises.push(loadResourcePromise(sourceURL).then(scriptSourceLoaded.bind(null , i), scriptSourceLoaded.bind(null , i, undefined))); } return Promise.all(promises).then(undefined); function scriptSourceLoaded(scriptNumber, scriptSource) { sources[scriptNumber] = scriptSource || ""; while (typeof sources[scriptToEval] !== "undefined") { evaluateScript(urls[scriptToEval], sources[scriptToEval]); ++scriptToEval; } } function evaluateScript(sourceURL, scriptSource) { _loadedScripts[sourceURL] = true; if (!scriptSource) { console.error("Empty response arrived for script '" + sourceURL + "'"); return; } self.eval(scriptSource + "\n//# sourceURL=" + sourceURL); }}(function() { var baseUrl = self.location ? self.location.origin + self.location.pathname : ""; self._importScriptPathPrefix = baseUrl.substring(0, baseUrl.lastIndexOf("/") + 1);})();function Runtime(descriptors, coreModuleNames) { this._modules = []; this._modulesMap = {}; this._extensions = []; this._cachedTypeClasses = {}; this._descriptorsMap = {}; for (var i = 0; i < descriptors.length; ++i) this._registerModule(descriptors[i]); if (coreModuleNames) this._loadAutoStartModules(coreModuleNames);}Runtime._queryParamsObject = { __proto__: null };Runtime.cachedResources = { __proto__: null };Runtime.isReleaseMode = function() { return !!allDescriptors.length;}Runtime.startApplication = function(appName) { console.timeStamp("Runtime.startApplication"); var allDescriptorsByName = {}; for (var i = 0; Runtime.isReleaseMode() && i < allDescriptors.length; ++i) { var d = allDescriptors[i]; allDescriptorsByName[d["name"]] = d; } var applicationPromise; if (applicationDescriptor) applicationPromise = Promise.resolve(applicationDescriptor); else applicationPromise = loadResourcePromise(appName + ".json").then(JSON.parse.bind(JSON)); applicationPromise.then(parseModuleDescriptors); function parseModuleDescriptors(configuration) { var moduleJSONPromises = []; var coreModuleNames = []; for (var i = 0; i < configuration.length; ++i) { var descriptor = configuration[i]; if (descriptor["type"] === "worker") continue;var name = descriptor["name"]; var moduleJSON = allDescriptorsByName[name]; if (moduleJSON) moduleJSONPromises.push(Promise.resolve(moduleJSON)); else moduleJSONPromises.push(loadResourcePromise(name + "/module.json").then(JSON.parse.bind(JSON))); if (descriptor["type"] === "autostart") coreModuleNames.push(name); } Promise.all(moduleJSONPromises).then(instantiateRuntime); function instantiateRuntime(moduleDescriptors) { for (var i = 0; !Runtime.isReleaseMode() && i < moduleDescriptors.length; ++i) { moduleDescriptors[i]["name"] = configuration[i]["name"]; moduleDescriptors[i]["condition"] = configuration[i]["condition"]; } self.runtime = new Runtime(moduleDescriptors,coreModuleNames); } }}Runtime.queryParam = function(name) { return Runtime._queryParamsObject[name] || null ;}Runtime.constructQueryParams = function(banned) { var params = []; for (var key in Runtime._queryParamsObject) { if (!key || banned.indexOf(key) !== -1) continue;params.push(key + "=" + Runtime._queryParamsObject[key]); } return params.length ? "?" + params.join("&") : "";}Runtime._experimentsSetting = function() { try { return ( JSON.parse(self.localStorage && self.localStorage["experiments"] ? self.localStorage["experiments"] : "{}")) ; } catch (e) { console.error("Failed to parse localStorage['experiments']"); return {}; }}Runtime._some = function(promises) { var all = []; var wasRejected = []; for (var i = 0; i < promises.length; ++i) { var handlerFunction = (handler.bind(promises[i], i)); all.push(promises[i].catch(handlerFunction)); } return Promise.all(all).then(filterOutFailuresResults); function filterOutFailuresResults(results) { var filtered = []; for (var i = 0; i < results.length; ++i) { if (!wasRejected[i]) filtered.push(results[i]); } return filtered; } function handler(index, e) { wasRejected[index] = true; console.error(e.stack); }}Runtime._console = console;Runtime._originalAssert = console.assert;Runtime._assert = function(value, message) { if (value) return; Runtime._originalAssert.call(Runtime._console, value, message + " " + new Error().stack);}Runtime.prototype = { useTestBase: function() { Runtime._remoteBase = "http://localhost:8000/inspector-sources/"; }, _registerModule: function(descriptor) { var module = new Runtime.Module(this,descriptor); this._modules.push(module); this._modulesMap[descriptor["name"]] = module; }, loadModulePromise: function(moduleName) { return this._modulesMap[moduleName]._loadPromise(); }, _loadAutoStartModules: function(moduleNames) { var promises = []; for (var i = 0; i < moduleNames.length; ++i) { if (Runtime.isReleaseMode()) this._modulesMap[moduleNames[i]]._loaded = true; else promises.push(this.loadModulePromise(moduleNames[i])); } return Promise.all(promises); }, _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; return this._checkExtensionApplicability(extension, currentContextTypes ? isContextTypeKnown : null ); function isContextTypeKnown(targetType) { return currentContextTypes.has(targetType); } }, extensions: function(type, context) { return this._extensions.filter(filter).sort(orderComparator); function filter(extension) { if (extension._type !== type && extension._typeClass() !== type) return false; if (!extension.enabled()) return false; return !context || extension.isApplicable(context); } function orderComparator(extension1, extension2) { var order1 = extension1.descriptor()["order"] || 0; var order2 = extension2.descriptor()["order"] || 0; return order1 - order2; } }, extension: function(type, context) { return this.extensions(type, context)[0] || null ; }, instancesPromise: function(type, context) { var extensions = this.extensions(type, context); var promises = []; for (var i = 0; i < extensions.length; ++i) promises.push(extensions[i].instancePromise()); return Runtime._some(promises); }, instancePromise: function(type, context) { var extension = this.extension(type, context); if (!extension) return Promise.reject(new Error("No such extension: " + type + " in given context.")); return extension.instancePromise(); }, _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] || null ; }}Runtime.ModuleDescriptor = function() { this.name; this.extensions; this.dependencies; this.scripts; this.remote;}Runtime.ExtensionDescriptor = function() { this.type; this.className; this.contextTypes;}Runtime.Module = function(manager, descriptor) { this._manager = manager; this._descriptor = descriptor; this._name = descriptor.name; this._instanceMap = {}; 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; }, enabled: function() { var activatorExperiment = this._descriptor["experiment"]; if (activatorExperiment && !Runtime.experiments.isEnabled(activatorExperiment)) return false; var condition = this._descriptor["condition"]; if (condition && !Runtime.queryParam(condition)) return false; return true; }, resource: function(name) { var fullName = this._name + "/" + name; var content = Runtime.cachedResources[fullName]; if (!content) throw new Error(fullName + " not preloaded. Check module.json"); return content; }, _loadPromise: function() { if (this._loaded) return Promise.resolve(); if (!this.enabled()) return Promise.reject(new Error("Module " + this._name + " is not enabled")); if (this._pendingLoadPromise) return this._pendingLoadPromise; var dependencies = this._descriptor.dependencies; var dependencyPromises = []; for (var i = 0; dependencies && i < dependencies.length; ++i) dependencyPromises.push(this._manager._modulesMap[dependencies[i]]._loadPromise()); this._pendingLoadPromise = Promise.all(dependencyPromises).then(this._loadResources.bind(this)).then(this._loadScripts.bind(this)).then(markAsLoaded.bind(this)); return this._pendingLoadPromise; function markAsLoaded() { delete this._pendingLoadPromise; this._loaded = true; } }, _loadResources: function() { var resources = this._descriptor["resources"]; if (!resources) return Promise.resolve(); var promises = []; for (var i = 0; i < resources.length; ++i) { var url = this._modularizeURL(resources[i]); promises.push(loadResourcePromise(url).then(cacheResource.bind(this, url), cacheResource.bind(this, url, undefined))); } return Promise.all(promises).then(undefined); function cacheResource(path, content) { if (!content) { console.error("Failed to load resource: " + path); return; } var sourceURL = window.location.href; if (window.location.search) sourceURL = sourceURL.replace(window.location.search, ""); sourceURL = sourceURL.substring(0, sourceURL.lastIndexOf("/") + 1) + path; Runtime.cachedResources[path] = content + "\n/*# sourceURL=" + sourceURL + " */"; } }, _loadScripts: function() { if (!this._descriptor.scripts) return Promise.resolve(); if (Runtime.isReleaseMode()) { var base = this._descriptor.remote && Runtime._remoteBase || undefined; return loadScriptsPromise([this._name + "_module.js"], base); } return loadScriptsPromise(this._descriptor.scripts.map(this._modularizeURL, this)); }, _modularizeURL: function(resourceName) { return normalizePath(this._name + "/" + resourceName); }, _instance: function(className) { if (className in this._instanceMap) return this._instanceMap[className]; var constructorFunction = window.eval(className); if (!(constructorFunction instanceof Function)) { this._instanceMap[className] = null ; return null ; } var instance = new constructorFunction(); this._instanceMap[className] = instance; return instance; }}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; }, enabled: function() { var activatorExperiment = this.descriptor()["experiment"]; if (activatorExperiment && !Runtime.experiments.isEnabled(activatorExperiment)) return false; var condition = this.descriptor()["condition"]; if (condition && !Runtime.queryParam(condition)) return false; return this._module.enabled(); }, _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); }, instancePromise: function() { if (!this._className) return Promise.reject(new Error("No class name in extension")); var className = this._className; if (this._instance) return Promise.resolve(this._instance); return this._module._loadPromise().then(constructInstance.bind(this)); function constructInstance() { var result = this._module._instance(className); if (!result) return Promise.reject("Could not instantiate: " + className); return result; } }, title: function(platform) { return this._descriptor["title-" + platform] || this._descriptor["title"]; }}Runtime.ExperimentsSupport = function() { this._supportEnabled = Runtime.queryParam("experiments") !== null ; this._experiments = []; this._experimentNames = {}; this._enabledTransiently = {};}Runtime.ExperimentsSupport.prototype = { allConfigurableExperiments: function() { var result = []; for (var i = 0; i < this._experiments.length; i++) { var experiment = this._experiments[i]; if (!this._enabledTransiently[experiment.name]) result.push(experiment); } return result; }, supportEnabled: function() { return this._supportEnabled; }, _setExperimentsSetting: function(value) { if (!self.localStorage) return; self.localStorage["experiments"] = JSON.stringify(value); }, register: function(experimentName, experimentTitle, hidden) { Runtime._assert(!this._experimentNames[experimentName], "Duplicate registration of experiment " + experimentName); this._experimentNames[experimentName] = true; this._experiments.push(new Runtime.Experiment(this,experimentName,experimentTitle,!!hidden)); }, isEnabled: function(experimentName) { this._checkExperiment(experimentName); if (this._enabledTransiently[experimentName]) return true; if (!this.supportEnabled()) return false; return !!Runtime._experimentsSetting()[experimentName]; }, setEnabled: function(experimentName, enabled) { this._checkExperiment(experimentName); var experimentsSetting = Runtime._experimentsSetting(); experimentsSetting[experimentName] = enabled; this._setExperimentsSetting(experimentsSetting); }, setDefaultExperiments: function(experimentNames) { for (var i = 0; i < experimentNames.length; ++i) { this._checkExperiment(experimentNames[i]); this._enabledTransiently[experimentNames[i]] = true; } }, enableForTest: function(experimentName) { this._checkExperiment(experimentName); this._enabledTransiently[experimentName] = true; }, clearForTest: function() { this._experiments = []; this._experimentNames = {}; this._enabledTransiently = {}; }, cleanUpStaleExperiments: function() { var experimentsSetting = Runtime._experimentsSetting(); var cleanedUpExperimentSetting = {}; for (var i = 0; i < this._experiments.length; ++i) { var experimentName = this._experiments[i].name; if (experimentsSetting[experimentName]) cleanedUpExperimentSetting[experimentName] = true; } this._setExperimentsSetting(cleanedUpExperimentSetting); }, _checkExperiment: function(experimentName) { Runtime._assert(this._experimentNames[experimentName], "Unknown experiment " + experimentName); }}Runtime.Experiment = function(experiments, name, title, hidden) { this.name = name; this.title = title; this.hidden = hidden; this._experiments = experiments;}Runtime.Experiment.prototype = { isEnabled: function() { return this._experiments.isEnabled(this.name); }, setEnabled: function(enabled) { this._experiments.setEnabled(this.name, enabled); }}{ (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("="); var name = pair.shift(); Runtime._queryParamsObject[name] = pair.join("="); } } )();}Runtime.experiments = new Runtime.ExperimentsSupport();Runtime._remoteBase = Runtime.queryParam("remoteBase");var runtime;console = console;console.__originalAssert = console.assert;console.assert = function(value, message) { if (value) return; console.__originalAssert(value, message);}var ArrayLike;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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);}String.prototype.unescapeHTML = function() { return this.replace(/</g, "<").replace(/>/g, ">").replace(/:/g, ":").replace(/"/g, "\"").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");}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) { if (result.toLowerCase().startsWith(baseURLDomain.toLowerCase())) result = result.substr(baseURLDomain.length); } 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.hashCode = function(string) { if (!string) return 0; var result = 0; for (var i = 0; i < string.length; ++i) result = (result * 3 + string.charCodeAt(i)) | 0; return result;}String.isDigitAt = function(string, index) { var c = string.charCodeAt(index); return 48 <= c && c <= 57;}String.prototype.toBase64 = function() { function encodeBits(b) { return b < 26 ? b + 65 : b < 52 ? b + 71 : b < 62 ? b - 4 : b === 62 ? 43 : b === 63 ? 47 : 65; } var encoder = new TextEncoder(); var data = encoder.encode(this.toString()); var n = data.length; var encoded = ""; if (n === 0) return encoded; var shift; var v = 0; for (var i = 0; i < n; i++) { shift = i % 3; v |= data[i] << (16 >>> shift & 24); if (shift === 2) { encoded += String.fromCharCode(encodeBits(v >>> 18 & 63), encodeBits(v >>> 12 & 63), encodeBits(v >>> 6 & 63), encodeBits(v & 63)); v = 0; } } if (shift === 0) encoded += String.fromCharCode(encodeBits(v >>> 18 & 63), encodeBits(v >>> 12 & 63), 61, 61); else if (shift === 1) encoded += String.fromCharCode(encodeBits(v >>> 18 & 63), encodeBits(v >>> 12 & 63), encodeBits(v >>> 6 & 63), 61); return encoded;}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 "0".repeat(3 - x.toString().length) + 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)) { if (format.length === index) break; addStringToken(format.substring(index, precentIndex)); index = precentIndex + 1; if (format[index] === "%") { addStringToken("%"); ++index; continue; } if (String.isDigitAt(format, index)) { var number = parseInt(format.substring(index), 10); while (String.isDigitAt(format, 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 (String.isDigitAt(format, 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, tokenizedFormat) { if (!format || !substitutions || !substitutions.length) return { formattedResult: append(initialValue, format), unusedSubstitutions: substitutions }; function prettyFunctionName() { return "String.format(\"" + format + "\", \"" + Array.prototype.join.call(substitutions, "\", \"") + "\")"; } function warn(msg) { console.warn(prettyFunctionName() + ": " + msg); } function error(msg) { console.error(prettyFunctionName() + ": " + msg); } var result = initialValue; var tokens = tokenizedFormat || 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 spacesPadding(spacesCount) { return "\u00a0".repeat(spacesCount);}function numberToStringWithSpacesPadding(value, symbolsCount) { var numberString = value.toString(); var paddingLength = Math.max(0, symbolsCount - numberString.length); return spacesPadding(paddingLength) + numberString;}Array.from = function(iterator) { var values = []; for (var iteratorValue = iterator.next(); !iteratorValue.done; iteratorValue = iterator.next()) values.push(iteratorValue.value); return values;}Set.prototype.valuesArray = function() { return Array.from(this.values());}Map.prototype.remove = function(key) { var value = this.get(key); this.delete(key); return value;}Map.prototype.valuesArray = function() { return Array.from(this.values());}Map.prototype.keysArray = function() { return Array.from(this.keys());}var Multimap = function() { this._map = new Map();}Multimap.prototype = { set: function(key, value) { var set = this._map.get(key); if (!set) { set = new Set(); this._map.set(key, set); } set.add(value); }, get: function(key) { var result = this._map.get(key); if (!result) result = new Set(); return result; }, remove: function(key, value) { var values = this.get(key); values.delete(value); if (!values.size) this._map.delete(key); }, removeAll: function(key) { this._map.delete(key); }, keysArray: function() { return this._map.keysArray(); }, valuesArray: function() { var result = []; var keys = this.keysArray(); for (var i = 0; i < keys.length; ++i) result.pushAll(this.get(keys[i]).valuesArray()); return result; }, clear: function() { this._map.clear(); }}function loadXHR(url) { return new Promise(load); function load(successCallback, failureCallback) { function onReadyStateChanged() { if (xhr.readyState !== XMLHttpRequest.DONE) return; if (xhr.status !== 200) { xhr.onreadystatechange = null ; failureCallback(new Error(xhr.status)); return; } xhr.onreadystatechange = null ; successCallback(xhr.responseText); } var xhr = new XMLHttpRequest(); xhr.withCredentials = false; xhr.open("GET", url, true); xhr.onreadystatechange = onReadyStateChanged; xhr.send(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) {}self.setImmediate = function(callback) { Promise.resolve().then(callback); return 0;}Promise.prototype.spread = function(callback) { return this.then(spreadPromise); function spreadPromise(arg) { return callback.apply(null , arg); }}Promise.prototype.catchException = function(defaultValue) { return this.catch(function(error) { console.error(error); return defaultValue; } );};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 ; var nonTextTags = { "STYLE": 1, "SCRIPT": 1 }; while (node && (node.nodeType !== Node.TEXT_NODE || nonTextTags[node.parentElement.nodeName])) node = node.traverseNextNode(stayWithin); return node;}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"); if (typeof x === "number" || typeof y === "number") this.style.setProperty("position", "absolute"); else this.style.removeProperty("position");}Element.prototype.isScrolledToBottom = function() { return Math.abs(this.scrollTop + this.clientHeight - this.scrollHeight) <= 2;}function removeSubsequentNodes(fromNode, toNode) { for (var node = fromNode; node && node !== toNode; ) { var nodeToRemove = node; node = node.nextSibling; nodeToRemove.remove(); }}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.parentNodeOrShadowHost()) { 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) { return this.enclosingNodeOrSelfWithClassList([className], stayWithin);}Node.prototype.enclosingNodeOrSelfWithClassList = function(classNames, stayWithin) { for (var node = this; node && node !== stayWithin && node !== this.ownerDocument; node = node.parentNodeOrShadowHost()) { if (node.nodeType === Node.ELEMENT_NODE) { var containsAll = true; for (var i = 0; i < classNames.length && containsAll; ++i) { if (!node.classList.contains(classNames[i])) containsAll = false; } if (containsAll) return ( node) ; } } return null ;}Node.prototype.parentElementOrShadowHost = function() { var node = this.parentNode; if (!node) return null ; if (node.nodeType === Node.ELEMENT_NODE) return ( node) ; if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) return ( node.host) ; return null ;}Node.prototype.parentNodeOrShadowHost = function() { return this.parentNode || this.host || null ;}Node.prototype.getComponentSelection = function() { var parent = this.parentNode; while (parent && parent.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) parent = parent.parentNode; return parent instanceof ShadowRoot ? parent.getSelection() : this.window().getSelection();}Node.prototype.isComponentSelectionCollapsed = function() { var selection = this.getComponentSelection(); return selection && selection.rangeCount ? selection.getRangeAt(0).collapsed : true;}Node.prototype.getDeepSelection = function() { var activeElement = this.ownerDocument.activeElement; var shadowRoot = null ; while (activeElement && activeElement.shadowRoot) { shadowRoot = activeElement.shadowRoot; activeElement = shadowRoot.activeElement; } return shadowRoot ? shadowRoot.getSelection() : this.window().getSelection();}Node.prototype.window = function() { return this.ownerDocument.defaultView;}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 = this.getComponentSelection(); if (!selection.rangeCount || !selection.isCollapsed) return false; var selectionRange = selection.getRangeAt(0); return selectionRange.startContainer.isSelfOrDescendant(this);}function createElement(tagName, customElementType) { return document.createElement(tagName, customElementType || "");}function createEvent(type, bubbles, cancelable) { var event = document.createEvent("Event"); event.initEvent(type, bubbles, cancelable); return event;}function createTextNode(data) { return document.createTextNode(data);}Document.prototype.createElementWithClass = function(elementName, className, customElementType) { var element = this.createElement(elementName, customElementType || ""); if (className) element.className = className; return element;}function createElementWithClass(elementName, className, customElementType) { return document.createElementWithClass(elementName, className, customElementType);}Document.prototype.createSVGElement = function(childType, className) { var element = this.createElementNS("http://www.w3.org/2000/svg", childType); if (className) element.setAttribute("class", className); return element;}function createSVGElement(childType, className) { return document.createSVGElement(childType, className);}function createDocumentFragment() { return document.createDocumentFragment();}Element.prototype.createChild = function(elementName, className, customElementType) { var element = this.ownerDocument.createElementWithClass(elementName, className, customElementType); 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 };}Element.prototype.createSVGChild = function(childType, className) { var child = this.ownerDocument.createSVGElement(childType, className); this.appendChild(child); return child;}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.getComponentSelection(); 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 = this.getComponentSelection(); 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.parentNodeOrShadowHost(); } return leftOffset;}Node.prototype.deepTextContent = function() { return this.childTextNodes().map(function(node) { return node.textContent; } ).join("");}Node.prototype.childTextNodes = function() { var node = this.traverseNextTextNode(this); var result = []; var nonTextTags = { "STYLE": 1, "SCRIPT": 1 }; while (node) { if (!nonTextTags[node.parentElement.nodeName]) result.push(node); node = node.traverseNextTextNode(this); } return result;}Node.prototype.isAncestor = function(node) { if (!node) return false; var currentNode = node.parentNodeOrShadowHost(); while (currentNode) { if (this === currentNode) return true; currentNode = currentNode.parentNodeOrShadowHost(); } 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) { if (this.shadowRoot) return this.shadowRoot; var distributedNodes = this.getDistributedNodes ? this.getDistributedNodes() : []; if (distributedNodes.length) return distributedNodes[0]; if (this.firstChild) return this.firstChild; var node = this; while (node) { if (stayWithin && node === stayWithin) return null ; var sibling = nextSibling(node); if (sibling) return sibling; node = insertionPoint(node) || node.parentNodeOrShadowHost(); } function nextSibling(node) { var parent = insertionPoint(node); if (!parent) return node.nextSibling; var distributedNodes = parent.getDistributedNodes ? parent.getDistributedNodes() : []; var position = Array.prototype.indexOf.call(distributedNodes, node); if (position + 1 < distributedNodes.length) return distributedNodes[position + 1]; return null ; } function insertionPoint(node) { var insertionPoints = node.getDestinationInsertionPoints ? node.getDestinationInsertionPoints() : []; return insertionPoints.length > 0 ? insertionPoints[insertionPoints.length - 1] : null ; } return null ;}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.parentNodeOrShadowHost();}Node.prototype.setTextContentTruncatedIfNeeded = function(text, placeholder) { const maxTextContentLength = 10000; if (typeof text === "string" && text.length > maxTextContentLength) { this.textContent = typeof placeholder === "string" ? placeholder : text.trimMiddle(maxTextContentLength); return true; } this.textContent = text; return false;}Event.prototype.deepElementFromPoint = function() { var node = this.target; while (node && node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE && node.nodeType !== Node.DOCUMENT_NODE) node = node.parentNode; if (!node) return null ; node = node.elementFromPoint(this.pageX, this.pageY); while (node && node.shadowRoot) node = node.shadowRoot.elementFromPoint(this.pageX, this.pageY); return node;}Event.prototype.deepActiveElement = function() { var activeElement = this.target && this.target.ownerDocument ? this.target.ownerDocument.activeElement : null ; while (activeElement && activeElement.shadowRoot) activeElement = activeElement.shadowRoot.activeElement; return activeElement;}Document.prototype.deepElementFromPoint = function(x, y) { var node = this.elementFromPoint(x, y); while (node && node.shadowRoot) node = node.shadowRoot.elementFromPoint(x, y); return node;}function isEnterKey(event) { return event.keyCode !== 229 && event.keyIdentifier === "Enter";}function isEscKey(event) { return event.keyCode === 27;}function consumeEvent(e) { e.consume();}function runOnWindowLoad(callback) { function windowLoaded() { window.removeEventListener("DOMContentLoaded", windowLoaded, false); callback(); } if (document.readyState === "complete" || document.readyState === "interactive") callback(); else window.addEventListener("DOMContentLoaded", windowLoaded, false);};var WorkerRuntime = {};WorkerRuntime.startSharedWorker = function(moduleName, workerName) { if (Runtime.isReleaseMode()) { try { var worker = new SharedWorker(moduleName + "_module.js",workerName); return Promise.resolve(worker); } catch (e) { return Promise.reject(e); } } return loadResourcePromise(moduleName + "/module.json").then(start, start.bind(null , undefined)); function start(content) { if (!content) throw new Error("Worker is not defined: " + moduleName + " " + new Error().stack); var scripts = JSON.parse(content)["scripts"]; if (scripts.length !== 1) throw new Error("WorkerRuntime.startSharedWorker supports modules with only one script!"); return new SharedWorker(moduleName + "/" + scripts[0],workerName); }}WorkerRuntime.startWorker = function(moduleName) { if (Runtime.isReleaseMode()) return Promise.resolve(new Worker(moduleName + "_module.js")); var loader = function() { self.onmessage = function(event) { self.onmessage = null ; var scripts = event.data; for (var i = 0; i < scripts.length; ++i) { var source = scripts[i]["source"]; self.eval(source + "\n//# sourceURL=" + scripts[i]["url"]); } } ; } ; return loadResourcePromise(moduleName + "/module.json").then(start, start.bind(null , undefined)); function start(content) { if (!content) throw new Error("Worker is not defined: " + moduleName + " " + new Error().stack); var message = []; var scripts = JSON.parse(content)["scripts"]; var promise = Promise.resolve(); for (var i = 0; i < scripts.length; ++i) { var url = self._importScriptPathPrefix + moduleName + "/" + scripts[i]; var parts = url.split("://"); url = parts.length === 1 ? url : parts[0] + "://" + normalizePath(parts[1]); promise = promise.then(promiseGetter(loadResourcePromise(moduleName + "/" + scripts[i]))).then(pushSource.bind(null , url), pushSource.bind(null , null , null )); } return promise.then(createWorker); function promiseGetter(promise) { return function() { return promise; } ; } function pushSource(url, source) { if (!url) { console.error("Failed to load " + url); return; } message.push({ source: source, url: url }); } function createWorker() { var blob = new Blob(["(" + loader.toString() + ")()\n//# sourceURL=" + moduleName],{ type: "text/javascript" }); var workerURL = window.URL.createObjectURL(blob); try { var worker = new Worker(workerURL); worker.postMessage(message); return worker; } finally { window.URL.revokeObjectURL(workerURL); } } }}WorkerRuntime.Worker = function(moduleName, workerName) { this._workerPromise = workerName ? WorkerRuntime.startSharedWorker(moduleName, (workerName)) : WorkerRuntime.startWorker(moduleName);}WorkerRuntime.Worker.prototype = { postMessage: function(message) { this._workerPromise.then(postToWorker.bind(this)); function postToWorker(worker) { if (!this._disposed) worker.postMessage(message); } }, dispose: function() { this._disposed = true; this._workerPromise.then(terminate); function terminate(worker) { worker.terminate(); } }, terminate: function() { this.dispose(); }, set onmessage(listener) { this._workerPromise.then(setOnMessage); function setOnMessage(worker) { worker.onmessage = listener; } }, set onerror(listener) { this._workerPromise.then(setOnError); function setOnError(worker) { worker.onerror = listener; } }, get port() { return new WorkerRuntime.Worker.FuturePort(this); }}WorkerRuntime.Worker.FuturePort = function(worker) { this._worker = worker;}WorkerRuntime.Worker.FuturePort.prototype = { set onmessage(listener) { this._worker._workerPromise.then(setOnMessage); function setOnMessage(worker) { worker.port.onmessage = listener; } }, set onerror(listener) { this._worker._workerPromise.then(setOnError); function setOnError(worker) { worker.port.onerror = listener; } }};self.WebInspector = {};WebInspector.TextDictionary = function() { this._words = {};}WebInspector.TextDictionary.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 = {}; }};WebInspector.Object = function() {}WebInspector.Object.prototype = { addEventListener: function(eventType, listener, thisObject) { if (!listener) console.assert(false); if (!this._listeners) this._listeners = new Map(); if (!this._listeners.has(eventType)) this._listeners.set(eventType, []); this._listeners.get(eventType).push({ thisObject: thisObject, listener: listener }); }, removeEventListener: function(eventType, listener, thisObject) { console.assert(listener); if (!this._listeners || !this._listeners.has(eventType)) return; var listeners = this._listeners.get(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) this._listeners.delete(eventType); }, removeAllListeners: function() { delete this._listeners; }, hasEventListeners: function(eventType) { if (!this._listeners || !this._listeners.has(eventType)) return false; return true; }, dispatchEventToListeners: function(eventType, eventData) { if (!this._listeners || !this._listeners.has(eventType)) return false; var event = new WebInspector.Event(this,eventType,eventData); var listeners = this._listeners.get(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 = { InspectorAgentEnabledForTests: "InspectorAgentEnabledForTests", SelectedNodeChanged: "SelectedNodeChanged"}WebInspector.notifications = new WebInspector.NotificationService();;WebInspector.Color = function(rgba, format, originalText) { this._rgba = rgba; this._originalText = originalText || null ; this._originalTextIsValid = !!this._originalText; this._format = format; 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; this._originalTextIsValid = false; } if (this._rgba[i] > 1) { this._rgba[i] = 1; this._originalTextIsValid = false; } }}WebInspector.Color.Format = { Original: "original", Nickname: "nickname", HEX: "hex", ShortHEX: "shorthex", RGB: "rgb", RGBA: "rgba", HSL: "hsl", HSLA: "hsla"}WebInspector.Color.parse = function(text) { var value = text.toLowerCase().replace(/\s+/g, ""); var simple = /^(?:#([0-9a-f]{3}|[0-9a-f]{6})|rgb\(((?:-?\d+%?,){2}-?\d+%?)\)|(\w+)|hsl\((-?\d+\.?\d*(?:,-?\d+\.?\d*%){2})\))$/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 = text; 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\(((?:-?\d+%?,){3}-?\d+(?:\.\d+)?)\)|hsla\((-?\d+\.?\d*(?:,-?\d+\.?\d*%){2},-?\d+(?:\.\d+)?)\))$/; 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.Format.RGBA);}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; }, canonicalHSLA: function() { var hsla = this.hsla(); return [Math.round(hsla[0] * 360), Math.round(hsla[1] * 100), Math.round(hsla[2] * 100), hsla[3]]; }, 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; }, asString: function(format) { if (format === this._format && this._originalTextIsValid) return this._originalText; 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(4); for (var i = 0; i < 3; ++i) rgba[i] = Math.round(this._rgba[i] * 255); rgba[3] = 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]; if (rgba.length !== 4) rgba = rgba.concat(1); 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,WebInspector.Color.Format.RGBA); }, setAlpha: function(alpha) { var rgba = this._rgba.slice(); rgba[3] = alpha; return new WebInspector.Color(rgba,WebInspector.Color.Format.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 Math.min(1, 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], "aqua": [0, 255, 255], "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], "fuchsia": [255, 0, 255], "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.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.Point = function(x, y) { this.x = x; this.y = y;}WebInspector.Geometry.Point.prototype = { distanceTo: function(p) { return Math.sqrt(Math.pow(p.x - this.x, 2) + Math.pow(p.y - this.y, 2)); }, toString: function() { return Math.round(this.x * 100) / 100 + ", " + Math.round(this.y * 100) / 100; }}WebInspector.Geometry.CubicBezier = function(point1, point2) { this.controlPoints = [point1, point2];}WebInspector.Geometry.CubicBezier.KeywordValues = { "linear": "cubic-bezier(0, 0, 1, 1)", "ease": "cubic-bezier(0.25, 0.1, 0.25, 1)", "ease-in": "cubic-bezier(0.42, 0, 1, 1)", "ease-in-out": "cubic-bezier(0.42, 0, 0.58, 1)", "ease-out": "cubic-bezier(0, 0, 0.58, 1)"}WebInspector.Geometry.CubicBezier.parse = function(text) { var keywordValues = WebInspector.Geometry.CubicBezier.KeywordValues; var value = text.toLowerCase().replace(/\s+/g, ""); if (Object.keys(keywordValues).indexOf(value) != -1) return WebInspector.Geometry.CubicBezier.parse(keywordValues[value]); var bezierRegex = /^cubic-bezier\(([^,]+),([^,]+),([^,]+),([^,]+)\)$/; var match = value.match(bezierRegex); if (match) { var control1 = new WebInspector.Geometry.Point(parseFloat(match[1]),parseFloat(match[2])); var control2 = new WebInspector.Geometry.Point(parseFloat(match[3]),parseFloat(match[4])); return new WebInspector.Geometry.CubicBezier(control1,control2); } return null ;}WebInspector.Geometry.CubicBezier.prototype = { evaluateAt: function(t) { function evaluate(v1, v2, t) { return 3 * (1 - t) * (1 - t) * t * v1 + 3 * (1 - t) * t * t * v2 + Math.pow(t, 3); } var x = evaluate(this.controlPoints[0].x, this.controlPoints[1].x, t); var y = evaluate(this.controlPoints[0].y, this.controlPoints[1].y, t); return new WebInspector.Geometry.Point(x,y); }, asCSSText: function() { var raw = "cubic-bezier(" + this.controlPoints.join(", ") + ")"; var keywordValues = WebInspector.Geometry.CubicBezier.KeywordValues; for (var keyword in keywordValues) { if (raw === keywordValues[keyword]) return keyword; } return raw; }}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;}WebInspector.Geometry.boundsForTransformedPoints = function(matrix, points, aggregateBounds) { if (!aggregateBounds) aggregateBounds = { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity }; if (points.length % 3) console.assert("Invalid size of points array"); for (var p = 0; p < points.length; p += 3) { var vector = new WebInspector.Geometry.Vector(points[p],points[p + 1],points[p + 2]); vector = WebInspector.Geometry.multiplyVectorByMatrixAndNormalize(vector, matrix); aggregateBounds.minX = Math.min(aggregateBounds.minX, vector.x); aggregateBounds.maxX = Math.max(aggregateBounds.maxX, vector.x); aggregateBounds.minY = Math.min(aggregateBounds.minY, vector.y); aggregateBounds.maxY = Math.max(aggregateBounds.maxY, vector.y); } return aggregateBounds;}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));};function Insets(left, top, right, bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom;}Insets.prototype = { isEqual: function(insets) { return !!insets && this.left === insets.left && this.top === insets.top && this.right == insets.right && this.bottom == insets.bottom; }}function Constraints(minimum, preferred) { this.minimum = minimum || new Size(0,0); this.preferred = preferred || this.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));};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() { this.showPromise(); }, showPromise: function() { if (this._uiDelegate) return this._uiDelegate.showConsole(); return Promise.reject(); }, __proto__: WebInspector.Object.prototype}WebInspector.console = new WebInspector.Console();;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.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+.-]*):\/\/([^\s\/:]*)(?::([\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._decodeIfPossible = function(url) { var decodedURL = url; try { decodedURL = decodeURI(url); } catch (e) {} return decodedURL;}WebInspector.ParsedURL.splitURLIntoPathComponents = function(url) { var decodedURL = WebInspector.ParsedURL._decodeIfPossible(url); var parsedURL = new WebInspector.ParsedURL(decodedURL); 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"; }, lastPathComponentWithFragment: function() { return this.lastPathComponent + (this.fragment ? "#" + this.fragment : ""); }}WebInspector.ParsedURL.splitLineAndColumn = function(string) { var lineColumnRegEx = /(?::(\d+))?(?::(\d+))?$/; var lineColumnMatch = lineColumnRegEx.exec(string); var lineNumber; var columnNumber; console.assert(lineColumnMatch); if (typeof (lineColumnMatch[1]) === "string") { lineNumber = parseInt(lineColumnMatch[1], 10); lineNumber = isNaN(lineNumber) ? undefined : lineNumber - 1; } if (typeof (lineColumnMatch[2]) === "string") { columnNumber = parseInt(lineColumnMatch[2], 10); columnNumber = isNaN(columnNumber) ? undefined : columnNumber - 1; } return { url: string.substring(0, string.length - lineColumnMatch[0].length), lineNumber: lineNumber, columnNumber: columnNumber };}String.prototype.asParsedURL = function() { var parsedURL = new WebInspector.ParsedURL(this.toString()); if (parsedURL.isValid) return parsedURL; return null ;};WebInspector.Progress = function() {}WebInspector.Progress.prototype = { setTotalWork: function(totalWork) {}, setTitle: function(title) {}, setWorked: function(worked, title) {}, worked: function(worked) {}, done: function() {}, isCanceled: function() { return false; },}WebInspector.CompositeProgress = function(parent) { this._parent = parent; this._children = []; this._childrenDone = 0; this._parent.setTotalWork(1); this._parent.setWorked(0);}WebInspector.CompositeProgress.prototype = { _childDone: function() { if (++this._childrenDone !== this._children.length) return; this._parent.done(); }, 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); }}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(); }, 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)); }}WebInspector.ProgressProxy = function(delegate, doneCallback) { this._delegate = delegate; this._doneCallback = doneCallback;}WebInspector.ProgressProxy.prototype = { isCanceled: function() { return this._delegate ? this._delegate.isCanceled() : false; }, setTitle: function(title) { if (this._delegate) this._delegate.setTitle(title); }, done: function() { if (this._delegate) this._delegate.done(); if (this._doneCallback) this._doneCallback(); }, setTotalWork: function(totalWork) { if (this._delegate) this._delegate.setTotalWork(totalWork); }, setWorked: function(worked, title) { if (this._delegate) this._delegate.setWorked(worked, title); }, worked: function(worked) { if (this._delegate) this._delegate.worked(worked); }};WebInspector.ResourceType = function(name, title, categoryTitle, shortCategoryTitle, color, isTextType) { this._name = name; this._title = title; this._categoryTitle = categoryTitle; this._shortCategoryTitle = shortCategoryTitle; this._color = color; this._isTextType = isTextType;}WebInspector.ResourceType.prototype = { name: function() { return this._name; }, title: function() { return this._title; }, categoryTitle: function() { return this._categoryTitle; }, shortCategoryTitle: function() { return this._shortCategoryTitle; }, 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 = { XHR: new WebInspector.ResourceType("xhr","XHR","XHR","XHR","rgb(231,231,10)",true), Script: new WebInspector.ResourceType("script","Script","Scripts","JS","rgb(255,121,0)",true), Stylesheet: new WebInspector.ResourceType("stylesheet","Stylesheet","Stylesheets","CSS","rgb(157,231,119)",true), Image: new WebInspector.ResourceType("image","Image","Images","Img","rgb(164,60,255)",false), Media: new WebInspector.ResourceType("media","Media","Media","Media","rgb(164,60,255)",false), Font: new WebInspector.ResourceType("font","Font","Fonts","Font","rgb(255,82,62)",false), Document: new WebInspector.ResourceType("document","Document","Documents","Doc","rgb(47,102,236)",true), TextTrack: new WebInspector.ResourceType("texttrack","TextTrack","TextTracks","TextTracks","rgb(164,60,255)",true), WebSocket: new WebInspector.ResourceType("websocket","WebSocket","WebSockets","WS","rgb(186,186,186)",false), Other: new WebInspector.ResourceType("other","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", "less": "text/x-less", "php": "text/x-php", "phtml": "application/x-httpd-php", "py": "text/x-python", "sh": "text/x-sh", "scss": "text/x-scss", "vtt": "text/vtt", "ls": "text/x-livescript", "cljs": "text/x-clojure", "cljc": "text/x-clojure", "cljx": "text/x-clojure"};WebInspector.Settings = function(prefs) { this._settingsStorage = prefs; this._eventSupport = new WebInspector.Object(); this._registry = new Map(); this._moduleSettings = new Map(); self.runtime.extensions("setting").forEach(this._registerModuleSetting.bind(this));}WebInspector.Settings.prototype = { _registerModuleSetting: function(extension) { var descriptor = extension.descriptor(); var settingName = descriptor["settingName"]; var settingType = descriptor["settingType"]; var defaultValue = descriptor["defaultValue"]; var isLocal = !!descriptor["local"]; var setting = settingType === "regex" ? this.createRegExpSetting(settingName, defaultValue, undefined, isLocal) : this.createSetting(settingName, defaultValue, isLocal); this._moduleSettings.set(settingName, setting); }, moduleSetting: function(settingName) { var setting = this._moduleSettings.get(settingName); if (!setting) throw new Error("No setting registered: " + settingName); return setting; }, settingForTest: function(settingName) { var setting = this._registry.get(settingName); if (!setting) throw new Error("No setting registered: " + settingName); return setting; }, createSetting: function(key, defaultValue, isLocal) { if (!this._registry.get(key)) this._registry.set(key, new WebInspector.Setting(this,key,defaultValue,this._eventSupport,isLocal ? (window.localStorage || {}) : this._settingsStorage)); return ( this._registry.get(key)) ; }, createLocalSetting: function(key, defaultValue) { return this.createSetting(key, defaultValue, true); }, createRegExpSetting: function(key, defaultValue, regexFlags, isLocal) { if (!this._registry.get(key)) this._registry.set(key, new WebInspector.RegExpSetting(this,key,defaultValue,this._eventSupport,isLocal ? (window.localStorage || {}) : this._settingsStorage,regexFlags)); return ( this._registry.get(key)) ; }, clearAll: function() { if (window.localStorage) window.localStorage.clear(); for (var key in this._settingsStorage) delete this._settingsStorage[key]; var versionSetting = WebInspector.settings.createSetting(WebInspector.VersionController._currentVersionName, 0); versionSetting.set(WebInspector.VersionController.currentVersion); }}WebInspector.Setting = function(settings, name, defaultValue, eventSupport, storage) { this._settings = settings; 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._name in this._storage) { try { this._value = JSON.parse(this._storage[this._name]); } catch (e) { this.remove(); } } return this._value; }, set: function(value) { this._value = value; try { var settingString = JSON.stringify(value); try { this._storage[this._name] = settingString; } catch (e) { this._printSettingsSavingError(e.message, this._name, settingString); } } catch (e) { WebInspector.console.error("Cannot stringify setting with name: " + this._name + ", error: " + e.message); } this._eventSupport.dispatchEventToListeners(this._name, value); }, remove: function() { this._settings._registry.delete(this._name); this._settings._moduleSettings.delete(this._name); delete this._storage[this._name]; }, _printSettingsSavingError: function(message, name, value) { var errorMessage = "Error saving setting with name: " + this._name + ", value length: " + value.length + ". Error: " + message; console.error(errorMessage); WebInspector.console.error(errorMessage); WebInspector.console.log("Ten largest settings: "); var sizes = { __proto__: null }; for (var key in this._storage) sizes[key] = this._storage[key].length; var keys = Object.keys(sizes); function comparator(key1, key2) { return sizes[key2] - sizes[key1]; } keys.sort(comparator); for (var i = 0; i < 10 && i < keys.length; ++i) WebInspector.console.log("Setting: '" + keys[i] + "', size: " + sizes[keys[i]]); }}WebInspector.RegExpSetting = function(settings, name, defaultValue, eventSupport, storage, regexFlags) { WebInspector.Setting.call(this, settings, 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.VersionController = function() {}WebInspector.VersionController._currentVersionName = "inspectorVersion";WebInspector.VersionController.currentVersion = 14;WebInspector.VersionController.prototype = { updateVersion: function() { var localStorageVersion = window.localStorage ? window.localStorage[WebInspector.VersionController._currentVersionName] : 0; var versionSetting = WebInspector.settings.createSetting(WebInspector.VersionController._currentVersionName, 0); var currentVersion = WebInspector.VersionController.currentVersion; var oldVersion = parseInt(localStorageVersion || "0", 10) || versionSetting.get(); if (oldVersion === 0) { versionSetting.set(currentVersion); return; } 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.createLocalSetting("breakpoints", []), 500000); }, _updateVersionFrom1To2: function() { WebInspector.settings.createSetting("previouslyViewedFiles", []).set([]); }, _updateVersionFrom2To3: function() { WebInspector.settings.createSetting("fileSystemMapping", {}).set({}); WebInspector.settings.createSetting("fileMappingEntries", []).remove(); }, _updateVersionFrom3To4: function() { var advancedMode = WebInspector.settings.createSetting("showHeaSnapshotObjectsHiddenProperties", false); WebInspector.moduleSetting("showAdvancedHeapSnapshotProperties").set(advancedMode.get()); advancedMode.remove(); }, _updateVersionFrom4To5: function() { var settingNames = { "FileSystemViewSidebarWidth": "fileSystemViewSplitViewState", "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" }; var empty = {}; for (var oldName in settingNames) { var newName = settingNames[oldName]; var oldNameH = oldName + "H"; var newValue = null ; var oldSetting = WebInspector.settings.createSetting(oldName, empty); if (oldSetting.get() !== empty) { newValue = newValue || {}; newValue.vertical = {}; newValue.vertical.size = oldSetting.get(); oldSetting.remove(); } var oldSettingH = WebInspector.settings.createSetting(oldNameH, empty); if (oldSettingH.get() !== empty) { newValue = newValue || {}; newValue.horizontal = {}; newValue.horizontal.size = oldSettingH.get(); oldSettingH.remove(); } if (newValue) WebInspector.settings.createSetting(newName, {}).set(newValue); } }, _updateVersionFrom5To6: function() { var settingNames = { "debuggerSidebarHidden": "sourcesPanelSplitViewState", "navigatorHidden": "sourcesPanelNavigatorSplitViewState", "WebInspector.Drawer.showOnLoad": "Inspector.drawerSplitViewState" }; for (var oldName in settingNames) { var oldSetting = WebInspector.settings.createSetting(oldName, null ); if (oldSetting.get() === null ) { oldSetting.remove(); continue; } var newName = settingNames[oldName]; var invert = "WebInspector.Drawer.showOnLoad" === oldName; var hidden = oldSetting.get() !== invert; oldSetting.remove(); var showMode = hidden ? "OnlyMain" : "Both"; var newSetting = WebInspector.settings.createSetting(newName, {}); 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() { var settingNames = { "sourcesPanelNavigatorSplitViewState": "sourcesPanelNavigatorSplitViewState", "elementsPanelSplitViewState": "elementsPanelSplitViewState", "stylesPaneSplitViewState": "stylesPaneSplitViewState", "sourcesPanelDebuggerSidebarSplitViewState": "sourcesPanelDebuggerSidebarSplitViewState" }; var empty = {}; for (var name in settingNames) { var setting = WebInspector.settings.createSetting(name, empty); var value = setting.get(); if (value === empty) 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() {}, _updateVersionFrom8To9: function() { var settingNames = ["skipStackFramesPattern", "workspaceFolderExcludePattern"]; for (var i = 0; i < settingNames.length; ++i) { var setting = WebInspector.settings.createSetting(settingNames[i], ""); var value = setting.get(); if (!value) return; if (typeof value === "string") value = [value]; for (var j = 0; j < value.length; ++j) { if (typeof value[j] === "string") value[j] = { pattern: value[j] }; } setting.set(value); } }, _updateVersionFrom9To10: function() { if (!window.localStorage) return; for (var key in window.localStorage) { if (key.startsWith("revision-history")) window.localStorage.removeItem(key); } }, _updateVersionFrom10To11: function() { var oldSettingName = "customDevicePresets"; var newSettingName = "customEmulatedDeviceList"; var oldSetting = WebInspector.settings.createSetting(oldSettingName, undefined); var list = oldSetting.get(); if (!Array.isArray(list)) return; var newList = []; for (var i = 0; i < list.length; ++i) { var value = list[i]; var device = {}; device["title"] = value["title"]; device["type"] = "unknown"; device["user-agent"] = value["userAgent"]; device["capabilities"] = []; if (value["touch"]) device["capabilities"].push("touch"); if (value["mobile"]) device["capabilities"].push("mobile"); device["screen"] = {}; device["screen"]["vertical"] = { width: value["width"], height: value["height"] }; device["screen"]["horizontal"] = { width: value["height"], height: value["width"] }; device["screen"]["device-pixel-ratio"] = value["deviceScaleFactor"]; device["modes"] = []; device["show-by-default"] = true; device["show"] = "Default"; newList.push(device); } if (newList.length) WebInspector.settings.createSetting(newSettingName, []).set(newList); oldSetting.remove(); }, _updateVersionFrom11To12: function() { this._migrateSettingsFromLocalStorage(); }, _updateVersionFrom12To13: function() { this._migrateSettingsFromLocalStorage(); WebInspector.settings.createSetting("timelineOverviewMode", "").remove(); }, _updateVersionFrom13To14: function() { var defaultValue = { "throughput": -1, "latency": 0 }; WebInspector.settings.createSetting("networkConditions", defaultValue).set(defaultValue); }, _migrateSettingsFromLocalStorage: function() { var localSettings = ["advancedSearchConfig", "breakpoints", "consoleHistory", "domBreakpoints", "eventListenerBreakpoints", "fileSystemMapping", "lastSelectedSourcesSidebarPaneTab", "previouslyViewedFiles", "savedURLs", "watchExpressions", "workspaceExcludedFolders", "xhrBreakpoints"].keySet(); if (!window.localStorage) return; for (var key in window.localStorage) { if (key in localSettings) continue;var value = window.localStorage[key]; window.localStorage.removeItem(key); WebInspector.settings._settingsStorage[key] = value; } }, _clearBreakpointsWhenTooMany: function(breakpointsSetting, maxBreakpointsCount) { if (breakpointsSetting.get().length > maxBreakpointsCount) breakpointsSetting.set([]); }}WebInspector.settings;WebInspector.moduleSetting = function(settingName) { return WebInspector.settings.moduleSetting(settingName);}WebInspector.settingForTest = function(settingName) { return WebInspector.settings.settingForTest(settingName);};WebInspector.StaticContentProvider = function(contentType, content, contentURL) { this._content = content; this._contentType = contentType; this._contentURL = contentURL || "";}WebInspector.StaticContentProvider.searchInContent = function(content, query, caseSensitive, isRegex, callback) { function performSearch() { callback(WebInspector.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex)); } setTimeout(performSearch.bind(null ), 0);}WebInspector.StaticContentProvider.prototype = { contentURL: function() { return this._contentURL; }, contentType: function() { return this._contentType; }, requestContent: function(callback) { callback(this._content); }, searchInContent: function(query, caseSensitive, isRegex, callback) { WebInspector.StaticContentProvider.searchInContent(this._content, query, caseSensitive, isRegex, callback); }};WebInspector.OutputStream = function() {}WebInspector.OutputStream.prototype = { write: function(data, callback) {}, close: function() {}}WebInspector.StringOutputStream = function() { this._data = "";}WebInspector.StringOutputStream.prototype = { write: function(chunk, callback) { this._data += chunk; }, close: function() {}, data: function() { return this._data; }};WebInspector.TestBase = function(domAutomationController) { this.domAutomationController_ = domAutomationController; this.controlTaken_ = false; this.timerId_ = -1;};WebInspector.TestBase.prototype.fail = function(message) { if (this.controlTaken_) this.reportFailure_(message); else throw message;};WebInspector.TestBase.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); }};WebInspector.TestBase.prototype.assertTrue = function(value, opt_message) { this.assertEquals(true, !!value, opt_message);};WebInspector.TestBase.prototype.takeControl = function() { this.controlTaken_ = true; var self = this; this.timerId_ = setTimeout(function() { self.reportFailure_("Timeout exceeded: 20 sec"); } , 20000);};WebInspector.TestBase.prototype.releaseControl = function() { if (this.timerId_ !== -1) { clearTimeout(this.timerId_); this.timerId_ = -1; } this.reportOk_();};WebInspector.TestBase.prototype.reportOk_ = function() { this.domAutomationController_.send("[OK]");};WebInspector.TestBase.prototype.reportFailure_ = function(error) { if (this.timerId_ !== -1) { clearTimeout(this.timerId_); this.timerId_ = -1; } this.domAutomationController_.send("[FAILED] " + error);};WebInspector.TestBase.prototype.runTest = function(testName) { try { this[testName](); if (!this.controlTaken_) this.reportOk_(); } catch (e) { this.reportFailure_(e); }};WebInspector.TestBase.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; } ;};WebInspector.TestBase.prototype.waitForThrottler = function(throttler, callback) { var test = this; var scheduleShouldFail = true; test.addSniffer(throttler, "schedule", onSchedule); function hasSomethingScheduled() { return throttler._isRunningProcess || throttler._process; } function checkState() { if (!hasSomethingScheduled()) { scheduleShouldFail = false; callback(); return; } test.addSniffer(throttler, "_processCompletedForTests", checkState); } function onSchedule() { if (scheduleShouldFail) test.fail("Unexpected Throttler.schedule"); } checkState();};;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); }, relativeTo: function(line, column) { var relative = this.clone(); if (this.startLine == line) relative.startColumn -= column; if (this.endLine == line) relative.endColumn -= column; relative.startLine -= line; relative.endLine -= line; return relative; }, toSourceRange: function(text) { var start = (this.startLine ? text.lineEndings()[this.startLine - 1] + 1 : 0) + this.startColumn; var end = (this.endLine ? text.lineEndings()[this.endLine - 1] + 1 : 0) + this.endColumn; return new WebInspector.SourceRange(start,end - start); }, 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); }, replaceInText: function(text, replacement) { var sourceRange = this.toSourceRange(text); return text.substring(0, sourceRange.offset) + replacement + text.substring(sourceRange.offset + sourceRange.length); }}WebInspector.SourceRange = function(offset, length) { this.offset = offset; this.length = length;};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, wordCallback) { var startWord = -1; for (var i = 0; i < text.length; ++i) { if (!isWordChar(text.charAt(i))) { if (startWord !== -1) wordCallback(text.substring(startWord, i)); startWord = -1; } else if (startWord === -1) startWord = i; } if (startWord !== -1) wordCallback(text.substring(startWord)); }, 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.TextUtils.BalancedJSONTokenizer = function(callback, findMultiple) { this._callback = callback; this._index = 0; this._balance = 0; this._buffer = ""; this._findMultiple = findMultiple || false; this._closingDoubleQuoteRegex = /[^\\](?:\\\\)*"/g;}WebInspector.TextUtils.BalancedJSONTokenizer.prototype = { write: function(chunk) { this._buffer += chunk; var lastIndex = this._buffer.length; var buffer = this._buffer; for (var index = this._index; index < lastIndex; ++index) { var character = buffer[index]; if (character === "\"") { this._closingDoubleQuoteRegex.lastIndex = index; if (!this._closingDoubleQuoteRegex.test(buffer)) break; index = this._closingDoubleQuoteRegex.lastIndex - 1; } else if (character === "{") { ++this._balance; } else if (character === "}") { if (--this._balance === 0) { this._lastBalancedIndex = index + 1; if (!this._findMultiple) break; } } } this._index = index; this._reportBalanced(); }, _reportBalanced: function() { if (!this._lastBalancedIndex) return; this._callback(this._buffer.slice(0, this._lastBalancedIndex)); this._buffer = this._buffer.slice(this._lastBalancedIndex); this._index -= this._lastBalancedIndex; this._lastBalancedIndex = 0; }, remainder: function() { return this._buffer; }}WebInspector.TokenizerFactory = function() {}WebInspector.TokenizerFactory.prototype = { createTokenizer: function(mimeType) {}};WebInspector.Throttler = function(timeout) { this._timeout = timeout; this._isRunningProcess = false; this._asSoonAsPossible = false; this._process = null ;}WebInspector.Throttler.prototype = { _processCompleted: function(error) { if (error) console.error(error); this._isRunningProcess = false; if (this._process) this._innerSchedule(false); this._processCompletedForTests(); }, _processCompletedForTests: function() {}, _onTimeout: function() { delete this._processTimeout; this._asSoonAsPossible = false; this._isRunningProcess = true; var process = this._process; this._process = null ; try { process(this._processCompleted.bind(this)); } catch (e) { if (this._isRunningProcess) this._processCompleted(e); } }, schedule: function(process, asSoonAsPossible) { this._process = process; var hasScheduledTasks = !!this._processTimeout || this._isRunningProcess; asSoonAsPossible = !!asSoonAsPossible || !hasScheduledTasks; var forceTimerUpdate = asSoonAsPossible && !this._asSoonAsPossible; this._asSoonAsPossible = this._asSoonAsPossible || asSoonAsPossible; this._innerSchedule(forceTimerUpdate); }, _innerSchedule: function(forceTimerUpdate) { if (this._isRunningProcess) return; if (this._processTimeout && !forceTimerUpdate) 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.UIString = function(string, vararg) { return String.vsprintf(WebInspector.localize(string), Array.prototype.slice.call(arguments, 1));}WebInspector.UIString.capitalize = function(string, vararg) { if (WebInspector._useLowerCaseMenuTitles === undefined) throw "WebInspector.setLocalizationPlatform() has not been called"; var localized = WebInspector.localize(string); var capitalized; if (WebInspector._useLowerCaseMenuTitles) capitalized = localized.replace(/\^(.)/g, "$1"); else capitalized = localized.replace(/\^(.)/g, function(str, char) { return char.toUpperCase(); } ); return String.vsprintf(capitalized, Array.prototype.slice.call(arguments, 1));}WebInspector.setLocalizationPlatform = function(platform) { WebInspector._useLowerCaseMenuTitles = platform === "windows";}WebInspector.localize = function(string) { return string;}WebInspector.UIStringFormat = function(format) { this._localizedFormat = WebInspector.localize(format); this._tokenizedFormat = String.tokenizeFormatString(this._localizedFormat, String.standardFormatters);}WebInspector.UIStringFormat._append = function(a, b) { return a + b;}WebInspector.UIStringFormat.prototype = { format: function(vararg) { return String.format(this._localizedFormat, arguments, String.standardFormatters, "", WebInspector.UIStringFormat._append, this._tokenizedFormat).formattedResult; }};WebInspector.Renderer = function() {}WebInspector.Renderer.prototype = { render: function(object) {}}WebInspector.Renderer.renderPromise = function(object) { if (!object) return Promise.reject(new Error("Can't render " + object)); return self.runtime.instancePromise(WebInspector.Renderer, object).then(render); function render(renderer) { return renderer.render(object); }}WebInspector.Revealer = function() {}WebInspector.Revealer.reveal = function(revealable, lineNumber) { WebInspector.Revealer.revealPromise(revealable, lineNumber);}WebInspector.Revealer.revealPromise = function(revealable, lineNumber) { if (!revealable) return Promise.reject(new Error("Can't reveal " + revealable)); return self.runtime.instancesPromise(WebInspector.Revealer, revealable).then(reveal); function reveal(revealers) { var promises = []; for (var i = 0; i < revealers.length; ++i) promises.push(revealers[i].reveal((revealable), lineNumber)); return Promise.race(promises); }}WebInspector.Revealer.prototype = { reveal: function(object, lineNumber) {}}WebInspector.App = function() {}WebInspector.App.prototype = { presentUI: function(document) {}}WebInspector.AppProvider = function() {}WebInspector.AppProvider.prototype = { createApp: function() {}}WebInspector.QueryParamHandler = function() {}WebInspector.QueryParamHandler.prototype = { handleQueryParam: function(value) {}};function InspectorFrontendHostAPI() {}InspectorFrontendHostAPI.ContextMenuDescriptor;InspectorFrontendHostAPI.LoadNetworkResourceResult;InspectorFrontendHostAPI.Events = { AddExtensions: "addExtensions", AppendedToURL: "appendedToURL", CanceledSaveURL: "canceledSaveURL", ContextMenuCleared: "contextMenuCleared", ContextMenuItemSelected: "contextMenuItemSelected", DeviceCountUpdated: "deviceCountUpdated", DevicesUpdated: "devicesUpdated", DispatchMessage: "dispatchMessage", DispatchMessageChunk: "dispatchMessageChunk", EnterInspectElementMode: "enterInspectElementMode", FileSystemsLoaded: "fileSystemsLoaded", FileSystemRemoved: "fileSystemRemoved", FileSystemAdded: "fileSystemAdded", IndexingTotalWorkCalculated: "indexingTotalWorkCalculated", IndexingWorked: "indexingWorked", IndexingDone: "indexingDone", KeyEventUnhandled: "keyEventUnhandled", RevealSourceLine: "revealSourceLine", SavedURL: "savedURL", SearchCompleted: "searchCompleted", SetInspectedTabId: "setInspectedTabId", SetUseSoftMenu: "setUseSoftMenu", ShowConsole: "showConsole"}InspectorFrontendHostAPI.EventDescriptors = [[InspectorFrontendHostAPI.Events.AddExtensions, ["extensions"]], [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.DispatchMessageChunk, ["messageChunk", "messageSize"]], [InspectorFrontendHostAPI.Events.EnterInspectElementMode, []], [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"]], [InspectorFrontendHostAPI.Events.RevealSourceLine, ["url", "lineNumber", "columnNumber"]], [InspectorFrontendHostAPI.Events.SavedURL, ["url"]], [InspectorFrontendHostAPI.Events.SearchCompleted, ["requestId", "fileSystemPath", "files"]], [InspectorFrontendHostAPI.Events.SetInspectedTabId, ["tabId"]], [InspectorFrontendHostAPI.Events.SetUseSoftMenu, ["useSoftMenu"]], [InspectorFrontendHostAPI.Events.ShowConsole, []]];InspectorFrontendHostAPI.prototype = { addFileSystem: function() {}, append: function(url, content) {}, loadCompleted: function() {}, indexPath: function(requestId, fileSystemPath) {}, getSelectionBackgroundColor: function() {}, getSelectionForegroundColor: function() {}, setInspectedPageBounds: function(bounds) {}, setWhitelistedShortcuts: function(shortcuts) {}, inspectElementCompleted: function() {}, openInNewTab: function(url) {}, removeFileSystem: function(fileSystemPath) {}, requestFileSystems: function() {}, save: function(url, content, forceSaveAs) {}, searchInPath: function(requestId, fileSystemPath, query) {}, stopIndexing: function(requestId) {}, bringToFront: function() {}, closeWindow: function() {}, copyText: function(text) {}, inspectedURLChanged: function(url) {}, isolatedFileSystem: function(fileSystemId, registeredName) {}, loadNetworkResource: function(url, headers, streamId, callback) {}, getPreferences: function(callback) {}, setPreference: function(name, value) {}, removePreference: function(name) {}, clearPreferences: function() {}, upgradeDraggedFileSystemPermissions: function(fileSystem) {}, platform: function() {}, recordEnumeratedHistogram: function(actionName, actionCode, bucketSize) {}, sendMessageToBackend: function(message) {}, setDevicesUpdatesEnabled: function(enabled) {}, setInjectedScriptForOrigin: function(origin, script) {}, setIsDocked: function(isDocked, callback) {}, zoomFactor: function() {}, zoomIn: function() {}, zoomOut: function() {}, resetZoom: function() {}, showContextMenuAtPoint: function(x, y, items, document) {}, isUnderTest: function() {}, isHostedMode: function() {}};WebInspector.InspectorFrontendHostStub = function() { function stopEventPropagation(event) { var zoomModifier = WebInspector.isMac() ? event.metaKey : event.ctrlKey; if (zoomModifier && (event.keyCode === 187 || event.keyCode === 189)) event.stopPropagation(); } document.addEventListener("keydown", stopEventPropagation, true);}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"; }, loadCompleted: function() {}, bringToFront: function() { this._windowVisible = true; }, closeWindow: function() { this._windowVisible = false; }, setIsDocked: function(isDocked, callback) { setTimeout(callback, 0); }, setInspectedPageBounds: function(bounds) {}, inspectElementCompleted: function() {}, 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) {}, recordEnumeratedHistogram: function(actionName, actionCode, bucketSize) {}, requestFileSystems: function() {}, addFileSystem: function() {}, removeFileSystem: function(fileSystemPath) {}, isolatedFileSystem: function(fileSystemId, registeredName) { return null ; }, loadNetworkResource: function(url, headers, streamId, callback) { loadResourcePromise(url).then(function(text) { WebInspector.ResourceLoader.streamWrite(streamId, text); callback({ statusCode: 200 }); } ).catch(function() { callback({ statusCode: 404 }); } ); }, getPreferences: function(callback) { var prefs = {}; for (var name in window.localStorage) prefs[name] = window.localStorage[name]; callback(prefs); }, setPreference: function(name, value) { window.localStorage[name] = value; }, removePreference: function(name) { delete window.localStorage[name]; }, clearPreferences: function() { window.localStorage.clear(); }, upgradeDraggedFileSystemPermissions: function(fileSystem) {}, indexPath: function(requestId, fileSystemPath) {}, stopIndexing: function(requestId) {}, searchInPath: function(requestId, fileSystemPath, query) {}, zoomFactor: function() { return 1; }, zoomIn: function() {}, zoomOut: function() {}, resetZoom: function() {}, setWhitelistedShortcuts: function(shortcuts) {}, isUnderTest: function() { return false; }, setDevicesUpdatesEnabled: function(enabled) {}, showContextMenuAtPoint: function(x, y, items, document) { throw "Soft context menu should be used"; }, isHostedMode: function() { return true; }};var InspectorFrontendHost = window.InspectorFrontendHost || null ;(function() { function initializeInspectorFrontendHost() { 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._debugFrontend = !!Runtime.queryParam("debugFrontend") || (window["InspectorTest"] && window["InspectorTest"]["debugTest"]); 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 = { _dispatch: function(name, signature, runOnceLoaded) { var params = Array.prototype.slice.call(arguments, 3); if (this._debugFrontend) setImmediate(innerDispatch); else innerDispatch(); function innerDispatch() { if (signature.length < 2) { try { InspectorFrontendHost.events.dispatchEventToListeners(name, params[0]); } catch (e) { console.error(e + " " + e.stack); } return; } var data = {}; for (var i = 0; i < signature.length; ++i) data[signature[i]] = params[i]; try { InspectorFrontendHost.events.dispatchEventToListeners(name, data); } catch (e) { console.error(e + " " + e.stack); } } }, streamWrite: function(id, chunk) { WebInspector.ResourceLoader.streamWrite(id, chunk); } } initializeInspectorFrontendHost(); window.InspectorFrontendAPI = new InspectorFrontendAPIImpl(); WebInspector.setLocalizationPlatform(InspectorFrontendHost.platform());})();InspectorFrontendHost.events;;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.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.ResourceLoader = {}WebInspector.ResourceLoader._lastStreamId = 0;WebInspector.ResourceLoader._boundStreams = {};WebInspector.ResourceLoader._bindOutputStream = function(stream) { WebInspector.ResourceLoader._boundStreams[++WebInspector.ResourceLoader._lastStreamId] = stream; return WebInspector.ResourceLoader._lastStreamId;}WebInspector.ResourceLoader._discardOutputStream = function(id) { WebInspector.ResourceLoader._boundStreams[id].close(); delete WebInspector.ResourceLoader._boundStreams[id];}WebInspector.ResourceLoader.streamWrite = function(id, chunk) { WebInspector.ResourceLoader._boundStreams[id].write(chunk);}WebInspector.ResourceLoader.load = function(url, headers, callback) { var stream = new WebInspector.StringOutputStream(); WebInspector.ResourceLoader.loadAsStream(url, headers, stream, mycallback); function mycallback(statusCode, headers) { callback(statusCode, headers, stream.data()); }}WebInspector.ResourceLoader.targetUserAgent = "";WebInspector.ResourceLoader.loadUsingTargetUA = function(url, headers, callback) { if (!WebInspector.ResourceLoader.targetUserAgent) { WebInspector.ResourceLoader.load(url, headers, callback); return; } var headersWithUA = {}; if (headers) { for (var header in headers) headersWithUA[header] = headers[header]; } headersWithUA["User-Agent"] = WebInspector.ResourceLoader.targetUserAgent; WebInspector.ResourceLoader.load(url, headersWithUA, callback);}WebInspector.ResourceLoader.loadAsStream = function(url, headers, stream, callback) { var streamId = WebInspector.ResourceLoader._bindOutputStream(stream); var parsedURL = new WebInspector.ParsedURL(url); if (parsedURL.isDataURL()) { loadXHR(url).then(dataURLDecodeSuccessful).catch(dataURLDecodeFailed); return; } var rawHeaders = []; if (headers) { for (var key in headers) rawHeaders.push(key + ": " + headers[key]); } InspectorFrontendHost.loadNetworkResource(url, rawHeaders.join("\r\n"), streamId, finishedCallback); function finishedCallback(response) { if (callback) callback(response.statusCode, response.headers || {}); WebInspector.ResourceLoader._discardOutputStream(streamId); } function dataURLDecodeSuccessful(text) { WebInspector.ResourceLoader.streamWrite(streamId, text); finishedCallback(({ statusCode: 200 })); } function dataURLDecodeFailed() { finishedCallback(({ statusCode: 404 })); }};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, AnimationsPlaybackRateChanged: 11, RevisionApplied: 12, FileSystemDirectoryContentReceived: 13, StyleRuleEdited: 14, CommandEvaluatedInConsolePanel: 15}WebInspector.UserMetrics._PanelCodes = { elements: 1, resources: 2, network: 3, sources: 4, timeline: 5, profiles: 6, audits: 7, console: 8, layers: 9}WebInspector.UserMetrics.prototype = { panelShown: function(panelName) { var code = WebInspector.UserMetrics._PanelCodes[panelName] || 0; var size = Object.keys(WebInspector.UserMetrics._PanelCodes).length + 1; InspectorFrontendHost.recordEnumeratedHistogram("DevTools.PanelShown", code, size); }}WebInspector.UserMetrics._Recorder = function(actionCode) { this._actionCode = actionCode;}WebInspector.UserMetrics._Recorder.prototype = { record: function() { var size = Object.keys(WebInspector.UserMetrics._ActionCodes).length + 1; InspectorFrontendHost.recordEnumeratedHistogram("DevTools.ActionTaken", this._actionCode, size); }}WebInspector.userMetrics = new WebInspector.UserMetrics();;WebInspector.Widget = function(isWebComponent) { this.contentElement = createElementWithClass("div", "widget"); if (isWebComponent) { this.element = createElementWithClass("div", "vbox flex-auto"); this._shadowRoot = WebInspector.createShadowRootWithCoreStyles(this.element); this._shadowRoot.appendChild(this.contentElement); } else { this.element = this.contentElement; } this._isWebComponent = isWebComponent; this.element.__widget = this; this._visible = true; this._isRoot = false; this._isShowing = false; this._children = []; this._hideOnDetach = false; this._notificationDepth = 0;}WebInspector.Widget.createStyleElement = function(cssFile) { var content = Runtime.cachedResources[cssFile] || ""; if (!content) console.error(cssFile + " not preloaded. Check module.json"); var styleElement = createElement("style"); styleElement.type = "text/css"; styleElement.textContent = content; return styleElement;}WebInspector.Widget.prototype = { markAsRoot: function() { WebInspector.Widget.__assert(!this.element.parentElement, "Attempt to mark as root attached node"); this._isRoot = true; }, parentWidget: function() { return this._parentWidget; }, children: function() { return this._children; }, childWasDetached: function(widget) {}, isShowing: function() { return this._isShowing; }, _shouldHideOnDetach: function() { if (this._hideOnDetach) return true; for (var child of this._children) { if (child._shouldHideOnDetach()) return true; } return false; }, setHideOnDetach: function() { this._hideOnDetach = true; }, _inNotification: function() { return !!this._notificationDepth || (this._parentWidget && this._parentWidget._inNotification()); }, _parentIsShowing: function() { if (this._isRoot) return true; return this._parentWidget && this._parentWidget.isShowing(); }, _callOnVisibleChildren: function(method) { var copy = this._children.slice(); for (var i = 0; i < copy.length; ++i) { if (copy[i]._parentWidget === this && copy[i]._visible) method.call(copy[i]); } }, _processWillShow: function() { 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._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.Widget.__assert(parentElement, "Attempt to attach widget with no parent element"); if (this.element.parentElement !== parentElement) { if (this.element.parentElement) this.detach(); var currentParent = parentElement; while (currentParent && !currentParent.__widget) currentParent = currentParent.parentElementOrShadowHost(); if (currentParent) { this._parentWidget = currentParent.__widget; this._parentWidget._children.push(this); this._isRoot = false; } else WebInspector.Widget.__assert(this._isRoot, "Attempt to attach widget to orphan node"); } else if (this._visible) { return; } this._visible = true; if (this._parentIsShowing()) this._processWillShow(); this.element.classList.remove("hidden"); if (this.element.parentElement !== parentElement) { WebInspector.Widget._incrementWidgetCounter(parentElement, this.element); if (insertBefore) WebInspector.Widget._originalInsertBefore.call(parentElement, this.element, insertBefore); else WebInspector.Widget._originalAppendChild.call(parentElement, this.element); } if (this._parentIsShowing()) this._processWasShown(); if (this._parentWidget && this._hasNonZeroConstraints()) this._parentWidget.invalidateConstraints(); else this._processOnResize(); }, detach: function(overrideHideOnDetach) { var parentElement = this.element.parentElement; if (!parentElement) return; if (this._parentIsShowing()) this._processWillHide(); if (!overrideHideOnDetach && this._shouldHideOnDetach()) { this.element.classList.add("hidden"); this._visible = false; if (this._parentIsShowing()) this._processWasHidden(); if (this._parentWidget && this._hasNonZeroConstraints()) this._parentWidget.invalidateConstraints(); return; } WebInspector.Widget._decrementWidgetCounter(parentElement, this.element); WebInspector.Widget._originalRemoveChild.call(parentElement, this.element); this._visible = false; if (this._parentIsShowing()) this._processWasHidden(); if (this._parentWidget) { var childIndex = this._parentWidget._children.indexOf(this); WebInspector.Widget.__assert(childIndex >= 0, "Attempt to remove non-child widget"); this._parentWidget._children.splice(childIndex, 1); this._parentWidget.childWasDetached(this); var parent = this._parentWidget; this._parentWidget = null ; if (this._hasNonZeroConstraints()) parent.invalidateConstraints(); } else WebInspector.Widget.__assert(this._isRoot, "Removing non-root widget from DOM"); }, detachChildWidgets: 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._isWebComponent ? this._shadowRoot : this.element).appendChild(WebInspector.Widget.createStyleElement(cssFile)); }, printWidgetHierarchy: function() { var lines = []; this._collectWidgetHierarchy("", lines); console.log(lines.join("\n")); }, _collectWidgetHierarchy: function(prefix, lines) { lines.push(prefix + "[" + this.element.className + "]" + (this._children.length ? " {" : "")); for (var i = 0; i < this._children.length; ++i) this._children[i]._collectWidgetHierarchy(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(this.element.ownerDocument.activeElement)) return; WebInspector.setCurrentFocusElement(element); }, hasFocus: function() { var activeElement = this.element.ownerDocument.activeElement; return activeElement && activeElement.isSelfOrDescendant(this.element); }, measurePreferredSize: function() { var document = this.element.ownerDocument; WebInspector.Widget._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.Widget._originalRemoveChild.call(document.body, this.element); return result; }, calculateConstraints: function() { return new Constraints(); }, 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._parentWidget) this._parentWidget.invalidateConstraints(); else this.doLayout(); }, __proto__: WebInspector.Object.prototype}WebInspector.Widget._originalAppendChild = Element.prototype.appendChild;WebInspector.Widget._originalInsertBefore = Element.prototype.insertBefore;WebInspector.Widget._originalRemoveChild = Element.prototype.removeChild;WebInspector.Widget._originalRemoveChildren = Element.prototype.removeChildren;WebInspector.Widget._incrementWidgetCounter = function(parentElement, childElement) { var count = (childElement.__widgetCounter || 0) + (childElement.__widget ? 1 : 0); if (!count) return; while (parentElement) { parentElement.__widgetCounter = (parentElement.__widgetCounter || 0) + count; parentElement = parentElement.parentElementOrShadowHost(); }}WebInspector.Widget._decrementWidgetCounter = function(parentElement, childElement) { var count = (childElement.__widgetCounter || 0) + (childElement.__widget ? 1 : 0); if (!count) return; while (parentElement) { parentElement.__widgetCounter -= count; parentElement = parentElement.parentElementOrShadowHost(); }}WebInspector.Widget.__assert = function(condition, message) { if (!condition) { console.trace(); throw new Error(message); }}WebInspector.VBox = function(isWebComponent) { WebInspector.Widget.call(this, isWebComponent); this.contentElement.classList.add("vbox");};WebInspector.VBox.prototype = { calculateConstraints: function() { var constraints = new Constraints(); function updateForChild() { var child = this.constraints(); constraints = constraints.widthToMax(child); constraints = constraints.addHeight(child); } this._callOnVisibleChildren(updateForChild); return constraints; }, __proto__: WebInspector.Widget.prototype};WebInspector.HBox = function(isWebComponent) { WebInspector.Widget.call(this, isWebComponent); this.contentElement.classList.add("hbox");};WebInspector.HBox.prototype = { calculateConstraints: function() { var constraints = new Constraints(); function updateForChild() { var child = this.constraints(); constraints = constraints.addWidth(child); constraints = constraints.heightToMax(child); } this._callOnVisibleChildren(updateForChild); return constraints; }, __proto__: WebInspector.Widget.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.Widget.__assert(!child.__widget || child.parentElement === this, "Attempt to add widget via regular DOM operation."); return WebInspector.Widget._originalAppendChild.call(this, child);}Element.prototype.insertBefore = function(child, anchor) { WebInspector.Widget.__assert(!child.__widget || child.parentElement === this, "Attempt to add widget via regular DOM operation."); return WebInspector.Widget._originalInsertBefore.call(this, child, anchor);}Element.prototype.removeChild = function(child) { WebInspector.Widget.__assert(!child.__widgetCounter && !child.__widget, "Attempt to remove element containing widget via regular DOM operation"); return WebInspector.Widget._originalRemoveChild.call(this, child);}Element.prototype.removeChildren = function() { WebInspector.Widget.__assert(!this.__widgetCounter, "Attempt to remove element containing widget via regular DOM operation"); WebInspector.Widget._originalRemoveChildren.call(this);};function TreeOutline(nonFocusable) { this._createRootElement(); this.selectedTreeElement = null ; this.expandTreeElementsWhenArrowing = false; this._comparator = null ; this._contentElement = this._rootElement._childrenListNode; this._contentElement.addEventListener("keydown", this._treeKeyDown.bind(this), true); this.setFocusable(!nonFocusable); this.element = this._contentElement;}TreeOutline.Events = { ElementAttached: "ElementAttached", ElementExpanded: "ElementExpanded", ElementCollapsed: "ElementCollapsed"}TreeOutline.prototype = { _createRootElement: function() { this._rootElement = new TreeElement(); this._rootElement.treeOutline = this; this._rootElement.root = true; this._rootElement.selectable = false; this._rootElement.expanded = true; this._rootElement._childrenListNode.classList.remove("children"); }, rootElement: function() { return this._rootElement; }, firstChild: function() { return this._rootElement.firstChild(); }, appendChild: function(child) { this._rootElement.appendChild(child); }, insertChild: function(child, index) { this._rootElement.insertChild(child, index); }, removeChild: function(child) { this._rootElement.removeChild(child); }, removeChildren: function() { this._rootElement.removeChildren(); }, treeElementFromPoint: function(x, y) { var node = this._contentElement.ownerDocument.deepElementFromPoint(x, y); if (!node) return null ; var listNode = node.enclosingNodeOrSelfWithNodeNameInArray(["ol", "li"]); if (listNode) return listNode.parentTreeElement || listNode.treeElement; return null ; }, treeElementFromEvent: function(event) { return event ? this.treeElementFromPoint(event.pageX, event.pageY) : null ; }, setComparator: function(comparator) { this._comparator = comparator; }, setFocusable: function(focusable) { if (focusable) this._contentElement.setAttribute("tabIndex", 0); else this._contentElement.removeAttribute("tabIndex"); }, focus: function() { this._contentElement.focus(); }, _bindTreeElement: function(element) { if (element.treeOutline) console.error("Binding element for the second time: " + new Error().stack); element.treeOutline = this; element.onbind(); }, _unbindTreeElement: function(element) { if (!element.treeOutline) console.error("Unbinding element that was not bound: " + new Error().stack); element.deselect(); element.onunbind(); element.treeOutline = null ; }, _treeKeyDown: function(event) { if (event.target !== this._contentElement) 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._expandable) { handled = true; if (this.selectedTreeElement.expanded) { nextSelectedElement = this.selectedTreeElement.firstChild(); 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); }, __proto__: WebInspector.Object.prototype}function TreeOutlineInShadow(className) { TreeOutline.call(this); var innerElement = this.element; innerElement.classList.add("tree-outline"); if (className) innerElement.classList.add(className); this.element = createElement("div"); this._shadowRoot = WebInspector.createShadowRootWithCoreStyles(this.element); this._shadowRoot.appendChild(WebInspector.Widget.createStyleElement("ui/treeoutline.css")); this._shadowRoot.appendChild(innerElement); this._renderSelection = true;}TreeOutlineInShadow.prototype = { registerRequiredCSS: function(cssFile) { this._shadowRoot.appendChild(WebInspector.Widget.createStyleElement(cssFile)); }, __proto__: TreeOutline.prototype}function TreeElement(title, expandable) { this.treeOutline = null ; this.parent = null ; this.previousSibling = null ; this.nextSibling = null ; this._listItemNode = createElement("li"); this._listItemNode.treeElement = this; if (title) this.title = title; if (typeof title === "string") this.tooltip = title; this._listItemNode.addEventListener("mousedown", this._handleMouseDown.bind(this), false); this._listItemNode.addEventListener("selectstart", this._treeElementSelectStart.bind(this), false); this._listItemNode.addEventListener("click", this._treeElementToggled.bind(this), false); this._listItemNode.addEventListener("dblclick", this._handleDoubleClick.bind(this), false); this._childrenListNode = createElement("ol"); this._childrenListNode.parentTreeElement = this; this._childrenListNode.classList.add("children"); this._hidden = false; this._selectable = true; this.expanded = false; this.selected = false; this.setExpandable(expandable || false);}TreeElement._ArrowToggleWidth = 10;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; }, hasAncestorOrSelf: function(ancestor) { return this === ancestor || this.hasAncestor(ancestor); }, children: function() { return this._children || []; }, childCount: function() { return this._children ? this._children.length : 0; }, firstChild: function() { return this._children ? this._children[0] : null ; }, lastChild: function() { return this._children ? this._children[this._children.length - 1] : null ; }, childAt: function(index) { return this._children ? this._children[index] : null ; }, indexOfChild: function(child) { return this._children ? this._children.indexOf(child) : -1; }, appendChild: function(child) { if (!this._children) this._children = []; var insertionIndex; if (this.treeOutline && this.treeOutline._comparator) insertionIndex = insertionIndexForObjectInListSortedByFunction(child, this._children, this.treeOutline._comparator); else insertionIndex = this._children.length; this.insertChild(child, insertionIndex); }, insertChild: function(child, index) { if (!this._children) this._children = []; if (!child) throw ("child can't be undefined or null"); console.assert(!child.parent, "Attempting to insert a child that is already in the tree, reparenting is not supported."); 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.setExpandable(true); child.parent = this; if (this.treeOutline) this.treeOutline._bindTreeElement(child); for (var current = child.firstChild(); this.treeOutline && current; current = current.traverseNextTreeElement(false, child, true)) this.treeOutline._bindTreeElement(current); child.onattach(); child._ensureSelection(); if (this.treeOutline) this.treeOutline.dispatchEventToListeners(TreeOutline.Events.ElementAttached, child); var nextSibling = child.nextSibling ? child.nextSibling._listItemNode : null ; this._childrenListNode.insertBefore(child._listItemNode, nextSibling); this._childrenListNode.insertBefore(child._childrenListNode, nextSibling); if (child.selected) child.select(); if (child.expanded) child.expand(); }, 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 (this.treeOutline && this.treeOutline.selectedTreeElement && this.treeOutline.selectedTreeElement.hasAncestorOrSelf(child)) { if (child.nextSibling) child.nextSibling.select(true); else if (child.previousSibling) child.previousSibling.select(true); else if (parent) parent.select(true); } if (child.previousSibling) child.previousSibling.nextSibling = child.nextSibling; if (child.nextSibling) child.nextSibling.previousSibling = child.previousSibling; child.parent = null ; if (this.treeOutline) this.treeOutline._unbindTreeElement(child); for (var current = child.firstChild(); this.treeOutline && current; current = current.traverseNextTreeElement(false, child, true)) this.treeOutline._unbindTreeElement(current); child._detach(); }, removeChild: function(child) { if (!child) throw ("child can't be undefined or null"); if (child.parent !== this) return; var childIndex = this._children.indexOf(child); if (childIndex === -1) throw ("child not found in this node's children"); this.removeChildAtIndex(childIndex); }, removeChildren: function() { if (!this.root && this.treeOutline && this.treeOutline.selectedTreeElement && this.treeOutline.selectedTreeElement.hasAncestorOrSelf(this)) this.select(true); for (var i = 0; this._children && i < this._children.length; ++i) { var child = this._children[i]; child.previousSibling = null child.nextSibling = null ; child.parent = null ; if (this.treeOutline) this.treeOutline._unbindTreeElement(child); for (var current = child.firstChild(); this.treeOutline && current; current = current.traverseNextTreeElement(false, child, true)) this.treeOutline._unbindTreeElement(current); child._detach(); } this._children = []; }, 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; if (typeof this._title === "string") this._listItemNode.textContent = this._title; else { this._listItemNode.removeChildren(); if (this._title) this._listItemNode.appendChild(this._title); this._ensureSelection(); } }, set tooltip(x) { if (x) this._listItemNode.setAttribute("title", x); else this._listItemNode.removeAttribute("title"); }, isExpandable: function() { return this._expandable; }, setExpandable: function(expandable) { if (this._expandable === expandable) return; this._expandable = expandable; this._listItemNode.classList.toggle("parent", expandable); if (!expandable) this.collapse(); }, get hidden() { return this._hidden; }, set hidden(x) { if (this._hidden === x) return; this._hidden = x; this._listItemNode.classList.toggle("hidden", x); this._childrenListNode.classList.toggle("hidden", x); }, invalidateChildren: function() { if (this._children) { this.removeChildren(); this._children = null ; } }, _ensureSelection: function() { if (!this.treeOutline || !this.treeOutline._renderSelection) return; if (!this._selectionElement) this._selectionElement = createElementWithClass("div", "selection"); this._listItemNode.insertBefore(this._selectionElement, this.listItemElement.firstChild); }, _treeElementSelectStart: function(event) { event.currentTarget._selectionStarted = true; }, _treeElementToggled: function(event) { var element = event.currentTarget; if (element._selectionStarted) { delete element._selectionStarted; var selection = element.getComponentSelection(); if (selection && !selection.isCollapsed && element.isSelfOrAncestor(selection.anchorNode) && element.isSelfOrAncestor(selection.focusNode)) return; } if (element.treeElement !== this) return; var toggleOnClick = this.toggleOnClick && !this.selectable; var isInTriangle = this.isEventWithinDisclosureTriangle(event); if (!toggleOnClick && !isInTriangle) return; if (event.target && event.target.enclosingNodeOrSelfWithNodeName("a")) return; if (this.expanded) { if (event.altKey) this.collapseRecursively(); else this.collapse(); } else { if (event.altKey) this.expandRecursively(); else this.expand(); } event.consume(); }, _handleMouseDown: function(event) { var element = event.currentTarget; if (!element) return; delete element._selectionStarted; if (!this.selectable) return; if (element.treeElement !== this) return; if (this.isEventWithinDisclosureTriangle(event)) return; this.selectOnMouseDown(event); }, _handleDoubleClick: function(event) { var element = event.currentTarget; if (!element || element.treeElement !== this) return; var handled = this.ondblclick(event); if (handled) return; if (this._expandable && !this.expanded) this.expand(); }, _detach: function() { this._listItemNode.remove(); this._childrenListNode.remove(); }, collapse: function() { if (!this.expanded) return; this._listItemNode.classList.remove("expanded"); this._childrenListNode.classList.remove("expanded"); this.expanded = false; this.oncollapse(); if (this.treeOutline) this.treeOutline.dispatchEventToListeners(TreeOutline.Events.ElementCollapsed, this); }, collapseRecursively: function() { var item = this; while (item) { if (item.expanded) item.collapse(); item = item.traverseNextTreeElement(false, this, true); } }, expand: function() { if (!this._expandable || (this.expanded && this._children)) return; this.expanded = true; this._populateIfNeeded(); this._listItemNode.classList.add("expanded"); this._childrenListNode.classList.add("expanded"); this.onexpand(); if (this.treeOutline) this.treeOutline.dispatchEventToListeners(TreeOutline.Events.ElementExpanded, this); }, 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; } }, reveal: function() { var currentAncestor = this.parent; while (currentAncestor && !currentAncestor.root) { if (!currentAncestor.expanded) currentAncestor.expand(); currentAncestor = currentAncestor.parent; } this.listItemElement.scrollIntoViewIfNeeded(); this.onreveal(); }, revealed: function() { var currentAncestor = this.parent; while (currentAncestor && !currentAncestor.root) { if (!currentAncestor.expanded) return false; currentAncestor = currentAncestor.parent; } return true; }, selectOnMouseDown: function(event) { if (this.select(false, true)) event.consume(true); }, select: function(omitFocus, selectedByUser) { if (!this.treeOutline || !this.selectable || this.selected) return false; if (this.treeOutline.selectedTreeElement) this.treeOutline.selectedTreeElement.deselect(); this.treeOutline.selectedTreeElement = null ; if (this.treeOutline._rootElement === this) return false; this.selected = true; if (!omitFocus) this.treeOutline.focus(); if (!this.treeOutline) return false; this.treeOutline.selectedTreeElement = this; this._listItemNode.classList.add("selected"); if (this._selectionElement) this._selectionElement.style.height = this._listItemNode.offsetHeight + "px"; return this.onselect(selectedByUser); }, revealAndSelect: function(omitFocus) { this.reveal(); this.select(omitFocus); }, deselect: function(supressOnDeselect) { if (!this.treeOutline || this.treeOutline.selectedTreeElement !== this || !this.selected) return; this.selected = false; this.treeOutline.selectedTreeElement = null ; this._listItemNode.classList.remove("selected"); }, _populateIfNeeded: function() { if (this._expandable && !this._children) { this._children = []; this.onpopulate(); } }, onpopulate: function() {}, onenter: function() { return false; }, ondelete: function() { return false; }, onspace: function() { return false; }, onbind: function() {}, onunbind: function() {}, onattach: function() {}, onexpand: function() {}, oncollapse: function() {}, ondblclick: function(e) { return false; }, onreveal: function() {}, onselect: function(selectedByUser) { return false; }, traverseNextTreeElement: function(skipUnrevealed, stayWithin, dontPopulate, info) { if (!dontPopulate) this._populateIfNeeded(); if (info) info.depthChange = 0; var element = skipUnrevealed ? (this.revealed() ? this.firstChild() : null ) : this.firstChild(); 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 || element.root) return null ; return ( skipUnrevealed ? (element.revealed() ? element.nextSibling : null ) : element.nextSibling) ; }, traversePreviousTreeElement: function(skipUnrevealed, dontPopulate) { var element = skipUnrevealed ? (this.revealed() ? this.previousSibling : null ) : this.previousSibling; if (!dontPopulate && element) element._populateIfNeeded(); while (element && (skipUnrevealed ? (element.revealed() && element.expanded ? element.lastChild() : null ) : element.lastChild())) { if (!dontPopulate) element._populateIfNeeded(); element = (skipUnrevealed ? (element.revealed() && element.expanded ? element.lastChild() : null ) : element.lastChild()); } if (element) return element; if (!this.parent || this.parent.root) return null ; return this.parent; }, isEventWithinDisclosureTriangle: function(event) { var paddingLeftValue = window.getComputedStyle(this._listItemNode).paddingLeft; console.assert(paddingLeftValue.endsWith("px")); var computedLeftPadding = parseFloat(paddingLeftValue); var left = this._listItemNode.totalOffsetLeft() + computedLeftPadding; return event.pageX >= left && event.pageX <= left + TreeElement._ArrowToggleWidth && this._expandable; }};WebInspector.ActionRegistry = function() { this._actionsById = new Map(); 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.set(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).valuesArray().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.instancePromise().then(handleAction); function handleAction(actionDelegate) { (actionDelegate).handleAction(WebInspector.context, actionId); } }}WebInspector.ActionDelegate = function() {}WebInspector.ActionDelegate.prototype = { handleAction: function(context, actionId) {}}WebInspector.actionRegistry;;WebInspector.ShortcutRegistry = function(actionRegistry, document) { this._actionRegistry = actionRegistry; this._defaultKeyToActions = new Multimap(); this._defaultActionToShortcut = new Multimap(); this._registerBindings(document);}WebInspector.ShortcutRegistry.prototype = { applicableActions: function(key) { return this._actionRegistry.applicableActions(this._defaultActionsForKey(key).valuesArray(), WebInspector.context); }, _defaultActionsForKey: function(key) { return this._defaultKeyToActions.get(String(key)); }, shortcutDescriptorsForAction: function(actionId) { return this._defaultActionToShortcut.get(actionId).valuesArray(); }, 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 (!actionIds.length) return; if (WebInspector.GlassPane.DefaultFocusedViewStack.length > 1) { if (event && !isPossiblyInputKey()) event.consume(true); return; } if (!isPossiblyInputKey()) { if (event) event.consume(true); processNextAction.call(this); } else { this._pendingActionTimer = setTimeout(processNextAction.bind(this), 0); } function processNextAction() { delete this._pendingActionTimer; var actionId = actionIds.shift(); if (!actionId) return; this._actionRegistry.execute(actionId).then(processNextAction.bind(this)); } function isPossiblyInputKey() { if (!event || !WebInspector.isEditing() || /^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); } }, registerShortcut: function(actionId, shortcut) { var descriptor = WebInspector.KeyboardShortcut.makeDescriptorFromBindingShortcut(shortcut); if (!descriptor) return; this._defaultActionToShortcut.set(actionId, descriptor); this._defaultKeyToActions.set(String(descriptor.key), actionId); }, dismissPendingShortcutAction: function() { if (this._pendingActionTimer) { clearTimeout(this._pendingActionTimer); delete this._pendingActionTimer; } }, _registerBindings: function(document) { document.addEventListener("input", this.dismissPendingShortcutAction.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.ColorSwatch = function() {}WebInspector.ColorSwatch.create = function() { if (!WebInspector.ColorSwatch._constructor) WebInspector.ColorSwatch._constructor = registerCustomElement("span", "color-swatch", WebInspector.ColorSwatch.prototype); return ( new WebInspector.ColorSwatch._constructor()) ;}WebInspector.ColorSwatch.prototype = { color: function() { return this._color; }, setColorText: function(colorText) { this._color = WebInspector.Color.parse(colorText); console.assert(this._color, "Color text could not be parsed."); this._format = this._color.format(); this._colorValueElement.textContent = this._color.asString(this._format); this._swatchInner.style.backgroundColor = colorText; }, format: function() { return this._format; }, setFormat: function(format) { this._format = format; this._colorValueElement.textContent = this._color.asString(this._format); }, toggleNextFormat: function() { do { this._format = WebInspector.ColorSwatch._nextColorFormat(this._color, this._format); var currentValue = this._color.asString(this._format); } while (currentValue === this._colorValueElement.textContent);this._colorValueElement.textContent = currentValue; }, iconElement: function() { return this._iconElement; }, createdCallback: function() { var root = WebInspector.createShadowRootWithCoreStyles(this); root.appendChild(WebInspector.Widget.createStyleElement("ui/colorSwatch.css")); this._iconElement = root.createChild("span", "color-swatch"); this._iconElement.title = WebInspector.UIString("Shift-click to change color format."); this._swatchInner = this._iconElement.createChild("span", "color-swatch-inner"); this._swatchInner.addEventListener("dblclick", consumeEvent, false); this._swatchInner.addEventListener("mousedown", consumeEvent, false); this._swatchInner.addEventListener("click", this._handleClick.bind(this), true); root.createChild("content"); this._colorValueElement = this.createChild("span"); this.setColorText("white"); }, _handleClick: function(event) { if (!event.shiftKey) return; event.target.parentNode.parentNode.host.toggleNextFormat(); event.consume(true); }, __proto__: HTMLSpanElement.prototype}WebInspector.ColorSwatch._nextColorFormat = function(color, curFormat) { var cf = WebInspector.Color.Format; switch (curFormat) { case cf.Original: return !color.hasAlpha() ? cf.RGB : cf.RGBA; case cf.RGB: case cf.RGBA: return !color.hasAlpha() ? cf.HSL : cf.HSLA; case cf.HSL: case cf.HSLA: if (color.nickname()) return cf.Nickname; if (!color.hasAlpha()) return color.canBeShortHex() ? cf.ShortHEX : cf.HEX; else return cf.Original; case cf.ShortHEX: return cf.HEX; case cf.HEX: return cf.Original; case cf.Nickname: if (!color.hasAlpha()) return color.canBeShortHex() ? cf.ShortHEX : cf.HEX; else return cf.Original; default: return cf.RGBA; }};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.set(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.set(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 new Set(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.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._pendingPromises = []; this._pendingTargets = []; this._event = event; this._x = event.x; this._y = event.y; 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.installHandler = function(doc) { doc.body.addEventListener("contextmenu", handler, false); function handler(event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendApplicableItems((event.deepElementFromPoint())); contextMenu.show(); }}WebInspector.ContextMenu.prototype = { nextId: function() { return this._id++; }, show: function() { Promise.all(this._pendingPromises).then(populateAndShow.bind(this)); WebInspector.ContextMenu._pendingMenu = this; function populateAndShow(appendCallResults) { if (WebInspector.ContextMenu._pendingMenu !== this) return; delete WebInspector.ContextMenu._pendingMenu; for (var i = 0; i < appendCallResults.length; ++i) { var providers = appendCallResults[i]; var target = this._pendingTargets[i]; for (var j = 0; j < providers.length; ++j) { var provider = (providers[j]); this.appendSeparator(); provider.appendApplicableItems(this._event, this, target); this.appendSeparator(); } } this._pendingPromises = []; this._pendingTargets = []; this._innerShow(); } this._event.consume(true); }, _innerShow: function() { var menuObject = this._buildDescriptors(); WebInspector._contextMenu = this; if (WebInspector.ContextMenu._useSoftMenu || InspectorFrontendHost.isHostedMode()) { var softMenu = new WebInspector.SoftContextMenu(menuObject,this._itemSelected.bind(this)); softMenu.show(this._event.target.ownerDocument, this._x, this._y); } else { InspectorFrontendHost.showContextMenuAtPoint(this._x, this._y, menuObject, this._event.target.ownerDocument); InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuCleared, this._menuCleared, this); InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ContextMenuItemSelected, this._onItemSelected, this); } }, _setHandler: function(id, handler) { if (handler) this._handlers[id] = handler; }, _buildDescriptors: 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) { this._pendingPromises.push(self.runtime.instancesPromise(WebInspector.ContextMenu.Provider, target)); this._pendingTargets.push(target); }, __proto__: WebInspector.ContextSubMenuItem.prototype}WebInspector.ContextMenu.Provider = function() {}WebInspector.ContextMenu.Provider.prototype = { appendApplicableItems: function(event, contextMenu, target) {}};WebInspector.Dialog = function(relativeToElement, delegate) { this._delegate = delegate; this._relativeToElement = relativeToElement; this._glassPane = new WebInspector.GlassPane((relativeToElement.ownerDocument)); 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 || WebInspector.Dialog.modalHostView().element,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 = createElement("div");}WebInspector.DialogDelegate.prototype = { show: function(element) { element.appendChild(this.element); this.element.classList.add("dialog-contents"); element.classList.add("dialog"); }, 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.DOMSyntaxHighlighter = function(mimeType, stripExtraWhitespace) { this._mimeType = mimeType; this._stripExtraWhitespace = stripExtraWhitespace;}WebInspector.DOMSyntaxHighlighter.prototype = { createSpan: function(content, className) { var span = createElement("span"); span.className = "cm-" + className; if (this._stripExtraWhitespace && className !== "whitespace") content = content.replace(/^[\n\r]*/, "").replace(/\s*$/, ""); span.createTextChild(content); return span; }, syntaxHighlightNode: function(node) { var lines = node.textContent.split("\n"); var plainTextStart; var line; return self.runtime.instancePromise(WebInspector.TokenizerFactory).then(processTokens.bind(this)); function processTokens(tokenizerFactory) { node.removeChildren(); var tokenize = tokenizerFactory.createTokenizer(this._mimeType); for (var i = lines[0].length ? 0 : 1; i < lines.length; ++i) { line = lines[i]; plainTextStart = 0; tokenize(line, processToken.bind(this)); if (plainTextStart < line.length) { var plainText = line.substring(plainTextStart, line.length); node.createTextChild(plainText); } if (i < lines.length - 1) node.createTextChild("\n"); } } function processToken(token, tokenType, column, newColumn) { if (!tokenType) return; if (column > plainTextStart) { var plainText = line.substring(plainTextStart, column); node.createTextChild(plainText); } node.appendChild(this.createSpan(token, tokenType)); plainTextStart = newColumn; } }};WebInspector.DropDownMenu = function(element) { this._items = []; element.addEventListener("mousedown", this._onMouseDown.bind(this));}WebInspector.DropDownMenu.Item;WebInspector.DropDownMenu.Events = { ItemSelected: "ItemSelected"}WebInspector.DropDownMenu.prototype = { _onMouseDown: function(event) { if (event.which !== 1) return; var menu = new WebInspector.ContextMenu(event); for (var item of this._items) menu.appendCheckboxItem(item.title, this._itemHandler.bind(this, item.id), item.id === this._selectedItemId); menu.show(); }, _itemHandler: function(id) { this.dispatchEventToListeners(WebInspector.DropDownMenu.Events.ItemSelected, id); }, addItem: function(id, title) { this._items.push({ id: id, title: title }); }, selectItem: function(id) { this._selectedItemId = id; }, clear: function() { this._items = []; delete this._selectedItemId; }, __proto__: WebInspector.Object.prototype};WebInspector.DropTarget = function(element, transferTypes, messageText, handleDrop) { element.addEventListener("dragenter", this._onDragEnter.bind(this), true); element.addEventListener("dragover", this._onDragOver.bind(this), true); this._element = element; this._transferTypes = transferTypes; this._messageText = messageText; this._handleDrop = handleDrop; this._enabled = true;}WebInspector.DropTarget.Types = { Files: "Files", URIList: "text/uri-list"}WebInspector.DropTarget.prototype = { setEnabled: function(enabled) { this._enabled = enabled; }, _onDragEnter: function(event) { if (this._enabled && this._hasMatchingType(event)) event.consume(true); }, _hasMatchingType: function(event) { for (var type of this._transferTypes) { if (event.dataTransfer.types.indexOf(type) !== -1) return true; } return false; }, _onDragOver: function(event) { if (!this._enabled || !this._hasMatchingType(event)) return; event.dataTransfer.dropEffect = "copy"; event.consume(true); if (this._dragMaskElement) return; this._dragMaskElement = this._element.createChild("div", ""); var shadowRoot = WebInspector.createShadowRootWithCoreStyles(this._dragMaskElement); shadowRoot.appendChild(WebInspector.Widget.createStyleElement("ui/dropTarget.css")); shadowRoot.createChild("div", "drop-target-message").textContent = this._messageText; this._dragMaskElement.addEventListener("drop", this._onDrop.bind(this), true); this._dragMaskElement.addEventListener("dragleave", this._onDragLeave.bind(this), true); }, _onDrop: function(event) { event.consume(true); this._removeMask(); if (this._enabled) this._handleDrop(event.dataTransfer); }, _onDragLeave: function(event) { event.consume(true); this._removeMask(); }, _removeMask: function() { this._dragMaskElement.remove(); delete this._dragMaskElement; }};WebInspector.EmptyWidget = function(text) { WebInspector.VBox.call(this); this.registerRequiredCSS("ui/emptyWidget.css"); this.element.classList.add("empty-view"); this.textElement = this.element.createChild("span"); this._text = text;}WebInspector.EmptyWidget.prototype = { wasShown: function() { this.textElement.textContent = this._text; }, set text(text) { this._text = text; if (this.isShowing()) this.textElement.textContent = this._text; }, __proto__: WebInspector.VBox.prototype};WebInspector.FilterBar = function(name, visibleByDefault) { this._filtersShown = false; this._element = createElementWithClass("div", "filter-bar hidden"); this._filterButton = new WebInspector.ToolbarButton(WebInspector.UIString("Filter"),"filter-toolbar-item",3); this._filterButton.element.addEventListener("click", this._handleFilterButtonClick.bind(this), false); this._filters = []; this._stateSetting = WebInspector.settings.createSetting("filterBar-" + name + "-toggled", !!visibleByDefault); this._setState(this._stateSetting.get());}WebInspector.FilterBar.FilterBarState = { Inactive: "inactive", Active: "active", Shown: "shown"};WebInspector.FilterBar.prototype = { 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.setState(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._element.classList.toggle("hidden", !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 = createElement("div"); this._filterElement.className = "filter-text-filter"; this._filterInputElement = (this._filterElement.createChild("input", "filter-input-field")); 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"); var label = createCheckboxLabel(WebInspector.UIString("Regex")); this._regexCheckBox = label.checkboxElement; this._regexCheckBox.id = "text-filter-regex"; this._regexCheckBox.addEventListener("change", this._onInput.bind(this), false); this._filterElement.appendChild(label); this._regexLabel = this._filterElement.textElement; }}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 = createElementWithClass("div", "filter-bitset-filter"); 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, items[i].title); 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, title) { var typeFilterElement = this._filtersElement.createChild("li", name); typeFilterElement.typeName = name; typeFilterElement.createTextChild(label); if (title) typeFilterElement.title = title; 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 = createElement("div"); this._filterElement.className = "filter-combobox-filter"; this._options = options; this._filterComboBox = new WebInspector.ToolbarComboBox(this._filterChanged.bind(this)); for (var i = 0; i < options.length; ++i) { var filterOption = options[i]; var option = 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 = createElementWithClass("div", "filter-checkbox-filter"); this._activeWhenChecked = !!activeWhenChecked; this._label = createCheckboxLabel(title); this._filterElement.appendChild(this._label); this._checkboxElement = this._label.checkboxElement; if (setting) WebInspector.SettingsUI.bindCheckbox(this._checkboxElement, setting); else this._checkboxElement.checked = true; this._checkboxElement.addEventListener("change", this._fireUpdated.bind(this), false);}WebInspector.CheckboxFilterUI.prototype = { isActive: function() { return this._activeWhenChecked === this._checkboxElement.checked; }, checked: function() { return this._checkboxElement.checked; }, element: function() { return this._filterElement; }, _fireUpdated: function() { this.dispatchEventToListeners(WebInspector.FilterUI.Events.FilterChanged, null ); }, setColor: function(backgroundColor, borderColor) { this._label.backgroundColor = backgroundColor; this._label.borderColor = borderColor; }, __proto__: WebInspector.Object.prototype};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.HelpScreen = function(title) { WebInspector.VBox.call(this); this.markAsRoot(); this.registerRequiredCSS("ui/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.helpContentElement = mainWindow.createChild("div", "help-content"); captionWindow.createChild("h1", "help-window-title").textContent = title; }}WebInspector.HelpScreen._visibleScreen = null ;WebInspector.HelpScreen.prototype = { createCloseButton: function() { var closeButton = createElementWithClass("div", "help-close-button", "dt-close-button"); closeButton.gray = true; 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.Dialog.modalHostView().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.HistoryInput = function() {}WebInspector.HistoryInput.create = function() { if (!WebInspector.HistoryInput._constructor) WebInspector.HistoryInput._constructor = registerCustomElement("input", "history-input", WebInspector.HistoryInput.prototype); return ( new WebInspector.HistoryInput._constructor()) ;}WebInspector.HistoryInput.prototype = { createdCallback: function() { this._history = [""]; this._historyPosition = 0; this.addEventListener("keydown", this._onKeyDown.bind(this), false); this.addEventListener("input", this._onInput.bind(this), false); }, _onInput: function(event) { if (this._history.length === this._historyPosition + 1) this._history[this._history.length - 1] = this.value; }, _onKeyDown: function(event) { if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Up.code) { this._historyPosition = Math.max(this._historyPosition - 1, 0); this.value = this._history[this._historyPosition]; this.dispatchEvent(createEvent("input", true, true)); event.consume(true); } else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Down.code) { this._historyPosition = Math.min(this._historyPosition + 1, this._history.length - 1); this.value = this._history[this._historyPosition]; this.dispatchEvent(createEvent("input", true, true)); event.consume(true); } else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Enter.code) { this._saveToHistory(); } }, _saveToHistory: function() { if (this._history.length > 1 && this._history[this._history.length - 2] === this.value) return; this._history[this._history.length - 1] = this.value; this._historyPosition = this._history.length - 1; this._history.push(""); }, __proto__: HTMLInputElement.prototype};WebInspector.Infobar = function(type, disableSetting) { this.element = createElementWithClass("div"); this._shadowRoot = WebInspector.createShadowRootWithCoreStyles(this.element); this._shadowRoot.appendChild(WebInspector.Widget.createStyleElement("ui/infobar.css")); this._contentElement = this._shadowRoot.createChild("div", "infobar infobar-" + type); this._contentElement.createChild("label", "icon", "dt-icon-label").type = type + "-icon"; this._contentElement.createChild("div", "content").createChild("content"); this._disableSetting = null ; if (disableSetting) { this._disableSetting = disableSetting; disableSetting.addChangeListener(this._updateVisibility, this); var disableButton = this._contentElement.createChild("div", "disable-button"); disableButton.textContent = WebInspector.UIString("Never show"); disableButton.addEventListener("click", disableSetting.set.bind(disableSetting, true), false); } this._closeButton = this._contentElement.createChild("div", "close-button", "dt-close-button"); this._closeButton.addEventListener("click", this.close.bind(this), false); this._closeCallback = null ; this.setVisible(false);}WebInspector.Infobar.Type = { Warning: "warning", Info: "info"}WebInspector.Infobar.prototype = { setVisible: function(visible) { this._visible = visible; if (this._disableSetting) visible = visible && !this._disableSetting.get(); this.element.classList.toggle("hidden", !visible); }, _updateVisibility: function() { this.setVisible(this._visible); }, close: function() { this.setVisible(false); if (this._closeCallback) this._closeCallback.call(null ); }, setCloseCallback: function(callback) { this._closeCallback = callback; }};WebInspector.InplaceEditor = function() {}WebInspector.InplaceEditor.Controller;WebInspector.InplaceEditor.startEditing = function(element, config) { if (!WebInspector.InplaceEditor._defaultInstance) WebInspector.InplaceEditor._defaultInstance = new WebInspector.InplaceEditor(); return WebInspector.InplaceEditor._defaultInstance.startEditing(element, config);}WebInspector.InplaceEditor.startMultilineEditing = function(element, config) { return self.runtime.instancePromise(WebInspector.InplaceEditor).then(startEditing); function startEditing(inplaceEditor) { var controller = (inplaceEditor).startEditing(element, config); if (!controller) return Promise.reject(new Error("Editing is already in progress")); return controller; }}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 (config.blurHandler && !config.blurHandler(element, e)) return; 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"); return ""; } 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 result = defaultFinishHandler(event); if (!result && config.postKeydownFinishHandler) result = config.postKeydownFinishHandler(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), setWidth: function() {} }; this.augmentEditingHandle(editingContext, handle); return handle; }}WebInspector.InplaceEditor.Config = function(commitHandler, cancelHandler, context, blurHandler) { this.commitHandler = commitHandler; this.cancelHandler = cancelHandler; this.context = context; this.blurHandler = blurHandler; this.pasteHandler; this.multiline; this.postKeydownFinishHandler;}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; }, setPostKeydownFinishHandler: function(postKeydownFinishHandler) { this.postKeydownFinishHandler = postKeydownFinishHandler; }};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.Alt : this.Shift; }};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" } }, Shift: { code: 16, name: { mac: "\u21e7", other: "Shift" } }, 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" }, LeftSquareBracket: { code: 219, name: "[" }, RightSquareBracket: { code: 221, name: "]" }, 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; var keyCode = keyboardEvent.keyCode || keyboardEvent["__keyCode"]; return WebInspector.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode, modifiers);}WebInspector.KeyboardShortcut.makeKeyFromEventIgnoringModifiers = function(keyboardEvent) { var keyCode = keyboardEvent.keyCode || keyboardEvent["__keyCode"]; return WebInspector.KeyboardShortcut._makeKeyFromCodeAndModifiers(keyCode, WebInspector.KeyboardShortcut.Modifiers.None);}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.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() {}, searchableView: function() { return null ; }, 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; }, showInfobar: function(infobar) { infobar.setCloseCallback(this._onInfobarClosed.bind(this, infobar)); if (this.element.firstChild) this.element.insertBefore(infobar.element, this.element.firstChild); else this.element.appendChild(infobar.element); infobar.setVisible(true); this.doResize(); }, _onInfobarClosed: function(infobar) { infobar.element.remove(); this.doResize(); }, __proto__: WebInspector.VBox.prototype}WebInspector.PanelWithSidebar = function(name, defaultWidth) { WebInspector.Panel.call(this, name); this._panelSplitWidget = new WebInspector.SplitWidget(true,false,this._panelName + "PanelSplitViewState",defaultWidth || 200); this._panelSplitWidget.show(this.element); this._mainWidget = new WebInspector.VBox(); this._panelSplitWidget.setMainWidget(this._mainWidget); this._sidebarWidget = new WebInspector.VBox(); this._sidebarWidget.setMinimumSize(100, 25); this._panelSplitWidget.setSidebarWidget(this._sidebarWidget); this._sidebarWidget.element.classList.add("sidebar");}WebInspector.PanelWithSidebar.prototype = { panelSidebarElement: function() { return this._sidebarWidget.element; }, mainElement: function() { return this._mainWidget.element; }, splitWidget: function() { return this._panelSplitWidget; }, __proto__: WebInspector.Panel.prototype}WebInspector.PanelDescriptor = function() {}WebInspector.PanelDescriptor.prototype = { name: function() {}, title: function() {}, panel: function() {}}WebInspector.PanelFactory = function() {}WebInspector.PanelFactory.prototype = { createPanel: 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.instancePromise().then(createPanel); function createPanel(panelFactory) { return (panelFactory).createPanel(); } }};WebInspector.Popover = function(popoverHelper) { WebInspector.Widget.call(this); this.markAsRoot(); this.element.className = WebInspector.Popover._classNamePrefix; this._containerElement = 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._classNamePrefix = "popover custom-popup-vertical-scroll custom-popup-horizontal-scroll";WebInspector.Popover.prototype = { showForAnchor: 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 document = anchor instanceof Element ? anchor.ownerDocument : contentElement.ownerDocument; var window = document.defaultView; var preferredSize = view ? view.measurePreferredSize() : WebInspector.measurePreferredSize(this._contentElement); this._preferredWidth = preferredWidth || preferredSize.width; this._preferredHeight = preferredHeight || preferredSize.height; window.addEventListener("resize", this._hideBound, false); document.body.appendChild(this._containerElement); WebInspector.Widget.prototype.show.call(this, this._containerElement); if (view) view.show(this._contentDiv); else this._contentDiv.appendChild(this._contentElement); this.positionElement(anchor, this._preferredWidth, this._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() { this._containerElement.ownerDocument.defaultView.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.toggle("fixed-height", this._hasFixedHeight); }, setNoMargins: function(noMargins) { this._hasNoMargins = noMargins; this._contentDiv.classList.toggle("no-margin", this._hasNoMargins); }, positionElement: function(anchorElement, preferredWidth, preferredHeight, arrowDirection) { const borderWidth = this._hasNoMargins ? 0 : 8; const scrollerWidth = this._hasFixedHeight ? 0 : 11; const arrowHeight = this._hasNoMargins ? 8 : 15; const arrowOffset = 10; const borderRadius = 4; const arrowRadius = 6; preferredWidth = preferredWidth || this._preferredWidth; preferredHeight = preferredHeight || this._preferredHeight; 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; this._popupArrowElement.removeAttribute("style"); if (anchorBox.x + newElementPosition.width < totalWidth) { newElementPosition.x = Math.max(borderRadius, anchorBox.x - borderRadius - arrowOffset); horizontalAlignment = "left"; this._popupArrowElement.style.left = arrowOffset + "px"; } else if (newElementPosition.width + borderRadius * 2 < totalWidth) { newElementPosition.x = totalWidth - newElementPosition.width - borderRadius - 2 * borderWidth; 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 - newElementPosition.x - borderRadius - arrowRadius + anchorBox.width / 2) + "px"; } this.element.className = WebInspector.Popover._classNamePrefix + " " + verticalAlignment + "-" + horizontalAlignment + "-arrow"; this.element.positionAt(newElementPosition.x, newElementPosition.y - borderWidth, container); this.element.style.width = newElementPosition.width + borderWidth * 2 + "px"; this.element.style.height = newElementPosition.height + borderWidth * 2 + "px"; }, __proto__: WebInspector.Widget.prototype}WebInspector.PopoverHelper = function(panelElement, getAnchor, showPopover, onHide, disableOnClick) { 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.ProgressIndicator = function() { this.element = createElementWithClass("div", "progress-indicator"); this._shadowRoot = WebInspector.createShadowRootWithCoreStyles(this.element); this._shadowRoot.appendChild(WebInspector.Widget.createStyleElement("ui/progressIndicator.css")); this._contentElement = this._shadowRoot.createChild("div", "progress-indicator-shadow-container"); this._labelElement = this._contentElement.createChild("div", "title"); this._progressElement = this._contentElement.createChild("progress"); this._progressElement.value = 0; this._stopButton = this._contentElement.createChild("button", "progress-indicator-shadow-stop-button"); this._stopButton.addEventListener("click", this.cancel.bind(this)); this._isCanceled = false; this._worked = 0;}WebInspector.ProgressIndicator.prototype = { show: function(parent) { parent.appendChild(this.element); }, done: function() { if (this._isDone) return; this._isDone = true; this.element.remove(); }, cancel: function() { this._isCanceled = true; }, 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)); }};WebInspector.ResizerWidget = function() { WebInspector.Object.call(this); this._isEnabled = true; this._elements = []; this._installDragOnMouseDownBound = this._installDragOnMouseDown.bind(this); this._cursor = "nwse-resize";};WebInspector.ResizerWidget.Events = { ResizeStart: "ResizeStart", ResizeUpdate: "ResizeUpdate", ResizeEnd: "ResizeEnd"};WebInspector.ResizerWidget.prototype = { isEnabled: function() { return this._isEnabled; }, setEnabled: function(enabled) { this._isEnabled = enabled; this.updateElementCursors(); }, 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); this._updateElementCursor(element); }, removeElement: function(element) { if (this._elements.indexOf(element) === -1) return; this._elements.remove(element); element.removeEventListener("mousedown", this._installDragOnMouseDownBound, false); element.style.removeProperty("cursor"); }, updateElementCursors: function() { this._elements.forEach(this._updateElementCursor.bind(this)); }, _updateElementCursor: function(element) { if (this._isEnabled) element.style.setProperty("cursor", this.cursor()); else element.style.removeProperty("cursor"); }, cursor: function() { return this._cursor; }, setCursor: function(cursor) { this._cursor = cursor; this.updateElementCursors(); }, _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.cursor(), event); }, _dragStart: function(event) { if (!this._isEnabled) return false; this._startX = event.pageX; this._startY = event.pageY; this.sendDragStart(this._startX, this._startY); return true; }, sendDragStart: function(x, y) { this.dispatchEventToListeners(WebInspector.ResizerWidget.Events.ResizeStart, { startX: x, currentX: x, startY: y, currentY: y }); }, _drag: function(event) { if (!this._isEnabled) { this._dragEnd(event); return true; } this.sendDragMove(this._startX, event.pageX, this._startY, event.pageY, event.shiftKey); event.preventDefault(); return false; }, sendDragMove: function(startX, currentX, startY, currentY, shiftKey) { this.dispatchEventToListeners(WebInspector.ResizerWidget.Events.ResizeUpdate, { startX: startX, currentX: currentX, startY: startY, currentY: currentY, shiftKey: shiftKey }); }, _dragEnd: function(event) { this.dispatchEventToListeners(WebInspector.ResizerWidget.Events.ResizeEnd); delete this._startX; delete this._startY; }, __proto__: WebInspector.Object.prototype};WebInspector.SimpleResizerWidget = function() { WebInspector.ResizerWidget.call(this); this._isVertical = true;};WebInspector.SimpleResizerWidget.prototype = { isVertical: function() { return this._isVertical; }, setVertical: function(vertical) { this._isVertical = vertical; this.updateElementCursors(); }, cursor: function() { return this._isVertical ? "ns-resize" : "ew-resize"; }, sendDragStart: function(x, y) { var position = this._isVertical ? y : x; this.dispatchEventToListeners(WebInspector.ResizerWidget.Events.ResizeStart, { startPosition: position, currentPosition: position }); }, sendDragMove: function(startX, currentX, startY, currentY, shiftKey) { if (this._isVertical) this.dispatchEventToListeners(WebInspector.ResizerWidget.Events.ResizeUpdate, { startPosition: startY, currentPosition: currentY, shiftKey: shiftKey }); else this.dispatchEventToListeners(WebInspector.ResizerWidget.Events.ResizeUpdate, { startPosition: startX, currentPosition: currentX, shiftKey: shiftKey }); }, __proto__: WebInspector.ResizerWidget.prototype};;WebInspector.RootView = function() { WebInspector.VBox.call(this); this.markAsRoot(); this.element.classList.add("root-view"); this.element.setAttribute("spellcheck", false);}WebInspector.RootView.prototype = { attachToDocument: function(document) { document.defaultView.addEventListener("resize", this.doResize.bind(this), false); this._window = document.defaultView; this.doResize(); this.show(document.body); }, doResize: function() { if (this._window) { var size = this.constraints().minimum; var zoom = WebInspector.zoomManager.zoomFactor(); var right = Math.min(0, this._window.innerWidth - size.width / zoom); this.element.style.marginRight = right + "px"; var bottom = Math.min(0, this._window.innerHeight - size.height / zoom); this.element.style.marginBottom = bottom + "px"; } WebInspector.VBox.prototype.doResize.call(this); }, __proto__: WebInspector.VBox.prototype};WebInspector.SearchableView = function(searchable, settingName) { WebInspector.VBox.call(this, true); this.registerRequiredCSS("ui/searchableView.css"); this._searchProvider = searchable; this._setting = settingName ? WebInspector.settings.createSetting(settingName, {}) : null ; this.element.addEventListener("keydown", this._onKeyDown.bind(this), false); this.contentElement.createChild("content"); this._footerElementContainer = this.contentElement.createChild("div", "search-bar hidden"); this._footerElementContainer.style.order = 100; var toolbar = new WebInspector.Toolbar(this._footerElementContainer); if (this._searchProvider.supportsCaseSensitiveSearch()) { this._caseSensitiveButton = new WebInspector.ToolbarTextButton(WebInspector.UIString("Case sensitive"),"case-sensitive-search-toolbar-item","Aa",2); this._caseSensitiveButton.addEventListener("click", this._toggleCaseSensitiveSearch, this); toolbar.appendToolbarItem(this._caseSensitiveButton); } if (this._searchProvider.supportsRegexSearch()) { this._regexButton = new WebInspector.ToolbarTextButton(WebInspector.UIString("Regex"),"regex-search-toolbar-item",".*",2); this._regexButton.addEventListener("click", this._toggleRegexSearch, this); toolbar.appendToolbarItem(this._regexButton); } 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 = WebInspector.HistoryInput.create(); this._searchInputElement.classList.add("search-replace"); this._searchControlElement.appendChild(this._searchInputElement); 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", "search-action-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", "search-action-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", "search-action-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", "search-action-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._replaceLabelElement = createCheckboxLabel(WebInspector.UIString("Replace")); this._replaceCheckboxElement = this._replaceLabelElement.checkboxElement; 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._replaceElement.appendChild(this._replaceLabelElement); var cancelButtonElement = this._firstRowElement.createChild("td").createChild("button", "search-action-button"); cancelButtonElement.textContent = WebInspector.UIString("Cancel"); cancelButtonElement.tabIndex = -1; cancelButtonElement.addEventListener("click", this.closeSearch.bind(this), false); this._minimalSearchQuerySize = 3; this._registerShortcuts(); this._loadSetting();}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 = { _toggleCaseSensitiveSearch: function() { this._caseSensitiveButton.setToggled(!this._caseSensitiveButton.toggled()); this._saveSetting(); this._performSearch(false, true); }, _toggleRegexSearch: function() { this._regexButton.setToggled(!this._regexButton.toggled()); this._saveSetting(); this._performSearch(false, true); }, _saveSetting: function() { if (!this._setting) return; var settingValue = this._setting.get() || {}; settingValue.caseSensitive = this._caseSensitiveButton.toggled(); settingValue.isRegex = this._regexButton.toggled(); this._setting.set(settingValue); }, _loadSetting: function() { var settingValue = this._setting ? (this._setting.get() || {}) : {}; if (this._searchProvider.supportsCaseSensitiveSearch()) this._caseSensitiveButton.setToggled(!!settingValue.caseSensitive); if (this._searchProvider.supportsRegexSearch()) this._regexButton.setToggled(!!settingValue.isRegex); }, 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.Widget.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; }, setPlaceholder: function(placeholder) { this._searchInputElement.placeholder = placeholder; }, 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() && 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 = ""; }, refreshSearch: function() { if (!this._searchIsVisible) return; this.resetSearch(); this._performSearch(false, false); }, 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 = this._searchInputElement.getComponentSelection(); 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; var searchConfig = this._currentSearchConfig(); this._searchProvider.performSearch(searchConfig, shouldJump, jumpBackwards); }, _currentSearchConfig: function() { var query = this._searchInputElement.value; var caseSensitive = this._caseSensitiveButton ? this._caseSensitiveButton.toggled() : false; var isRegex = this._regexButton ? this._regexButton.toggled() : false; return new WebInspector.SearchableView.SearchConfig(query,caseSensitive,isRegex); }, _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() { var searchConfig = this._currentSearchConfig(); (this._searchProvider).replaceSelectionWith(searchConfig, this._replaceInputElement.value); delete this._currentQuery; this._performSearch(true, true); }, _replaceAll: function() { var searchConfig = this._currentSearchConfig(); (this._searchProvider).replaceAllWith(searchConfig, this._replaceInputElement.value); }, _onInput: function(event) { if (this._valueChangedTimeoutId) clearTimeout(this._valueChangedTimeoutId); var timeout = this._searchInputElement.value.length < 3 ? 200 : 0; this._valueChangedTimeoutId = setTimeout(this._onValueChanged.bind(this), timeout); }, _onValueChanged: function() { delete this._valueChangedTimeoutId; this._performSearch(false, true); }, __proto__: WebInspector.VBox.prototype}WebInspector.Searchable = function() {}WebInspector.Searchable.prototype = { searchCanceled: function() {}, performSearch: function(searchConfig, shouldJump, jumpBackwards) {}, jumpToNextSearchResult: function() {}, jumpToPreviousSearchResult: function() {}, supportsCaseSensitiveSearch: function() {}, supportsRegexSearch: function() {}}WebInspector.Replaceable = function() {}WebInspector.Replaceable.prototype = { replaceSelectionWith: function(searchConfig, replacement) {}, replaceAllWith: function(searchConfig, replacement) {}}WebInspector.SearchableView.SearchConfig = function(query, caseSensitive, isRegex) { this.query = query; this.caseSensitive = caseSensitive; this.isRegex = isRegex;}WebInspector.SearchableView.SearchConfig.prototype = { toSearchRegex: function(global) { var modifiers = this.caseSensitive ? "" : "i"; if (global) modifiers += "g"; var query = this.isRegex ? "/" + this.query + "/" : this.query; var regex; try { if (/^\/.+\/$/.test(query)) { regex = new RegExp(query.substring(1, query.length - 1),modifiers); regex.__fromRegExpQuery = true; } } catch (e) {} if (!regex) regex = createPlainTextSearchRegex(query, modifiers); return regex; }};WebInspector.Section = function(title, subtitle) { this.element = createElementWithClass("div", "section"); this.element._section = this; this.registerRequiredCSS("ui/section.css"); this.headerElement = createElementWithClass("div", "header monospace"); this.titleElement = createElementWithClass("div", "title"); this.subtitleElement = createElementWithClass("div", "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; if (subtitle) { this._subtitle = subtitle; this.subtitleElement.textContent = 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; }, get expanded() { return this._expanded; }, repopulate: function() { this._populated = false; if (this._expanded) { this.onpopulate(); this._populated = true; } }, onpopulate: function() {}, 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"); }, registerRequiredCSS: function(cssFile) { this.element.insertBefore(WebInspector.Widget.createStyleElement(cssFile), this.headerElement); }, handleClick: function(event) { if (this._doNotExpandOnTitleClick) return; if (this._expanded) this.collapse(); else this.expand(); event.consume(); }, doNotExpandOnTitleClick: function() { this._doNotExpandOnTitleClick = true; }}WebInspector.PropertiesSection = function(title, subtitle) { WebInspector.Section.call(this, title, subtitle); this.registerRequiredCSS("ui/propertiesSection.css"); this.propertiesTreeOutline = new TreeOutline(true); this.propertiesElement = this.propertiesTreeOutline.element; this.propertiesElement.classList.add("properties", "properties-tree", "monospace"); this.propertiesTreeOutline.setFocusable(false); this.propertiesTreeOutline.section = this; this.element.appendChild(this.propertiesElement);}WebInspector.PropertiesSection.prototype = { __proto__: WebInspector.Section.prototype};WebInspector.SettingsUI = {}WebInspector.SettingsUI.createSettingCheckbox = function(name, setting, omitParagraphElement, tooltip) { var label = createCheckboxLabel(name); if (tooltip) label.title = tooltip; var input = label.checkboxElement; input.name = name; WebInspector.SettingsUI.bindCheckbox(input, setting); if (omitParagraphElement) return label; var p = 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 = 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 = createElement("p"); var fieldsetElement = p.createChild("fieldset"); fieldsetElement.createChild("label").textContent = name; fieldsetElement.appendChild(element); return p;}WebInspector.SettingsUI.createSettingFieldset = function(setting) { var fieldset = 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.SettingUI = function() {}WebInspector.SettingUI.prototype = { settingElement: function() {}};WebInspector.SidebarSectionTreeElement = function(title) { TreeElement.call(this, title.escapeHTML(), true); 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, expandable) { TreeElement.call(this, "", expandable); if (expandable) this.disclosureButton = createElementWithClass("button", "disclosure-button"); this.iconElement = createElementWithClass("div", "icon"); this.statusElement = createElementWithClass("div", "status"); this.titlesElement = 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.isExpandable() && 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.SoftContextMenu = function(items, itemSelectedCallback, parentMenu) { this._items = items; this._itemSelectedCallback = itemSelectedCallback; this._parentMenu = parentMenu;}WebInspector.SoftContextMenu.prototype = { show: function(document, x, y) { if (this._contextMenuElement) this._discardMenu(true); if (!this._items.length) return; this._document = document; this._x = x; this._y = y; this._time = new Date().getTime(); this._contextMenuElement = createElementWithClass("div", "soft-context-menu"); var root = WebInspector.createShadowRootWithCoreStyles(this._contextMenuElement); root.appendChild(WebInspector.Widget.createStyleElement("ui/softContextMenu.css")); var menuElement = root.createChild("div"); this._contextMenuElement.tabIndex = 0; this._contextMenuElement.style.top = y + "px"; this._contextMenuElement.style.left = x + "px"; menuElement.addEventListener("mouseup", consumeEvent, false); menuElement.addEventListener("keydown", this._menuKeyDown.bind(this), false); for (var i = 0; i < this._items.length; ++i) menuElement.appendChild(this._createMenuItem(this._items[i])); if (!this._parentMenu) { this._glassPaneElement = createElementWithClass("div", "soft-context-menu-glass-pane fill"); 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 = 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("mouseleave", this._menuItemMouseLeave.bind(this), false); menuItemElement._actionId = item.id; return menuItemElement; }, _createSubMenu: function(item) { var menuItemElement = 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("mouseleave", this._menuItemMouseLeave.bind(this), false); return menuItemElement; }, _createSeparator: function() { var separatorElement = 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._document, 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); }, _menuItemMouseLeave: function(event) { if (!this._subMenu || !event.relatedTarget) { this._highlightMenuItem(null ); return; } var relatedTarget = event.relatedTarget; if (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; this._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.SplitWidget = function(isVertical, secondIsSidebar, settingName, defaultSidebarWidth, defaultSidebarHeight, constraintsInDip) { WebInspector.Widget.call(this, true); this.element.classList.add("split-widget"); this.registerRequiredCSS("ui/splitWidget.css"); this.contentElement.classList.add("shadow-split-widget"); this._mainElement = this.contentElement.createChild("div", "shadow-split-widget-contents shadow-split-widget-main vbox"); this._mainElement.createChild("content").select = ".insertion-point-main"; this._sidebarElement = this.contentElement.createChild("div", "shadow-split-widget-contents shadow-split-widget-sidebar vbox"); this._sidebarElement.createChild("content").select = ".insertion-point-sidebar"; this._resizerElement = this.contentElement.createChild("div", "shadow-split-widget-resizer"); this._resizerWidget = new WebInspector.SimpleResizerWidget(); 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._setting = settingName ? WebInspector.settings.createSetting(settingName, {}) : null ; this.setSecondIsSidebar(secondIsSidebar); this._innerSetVertical(isVertical); this._showMode = WebInspector.SplitWidget.ShowMode.Both; this.installResizer(this._resizerElement);}WebInspector.SplitWidget.SettingForOrientation;WebInspector.SplitWidget.ShowMode = { Both: "Both", OnlyMain: "OnlyMain", OnlySidebar: "OnlySidebar"}WebInspector.SplitWidget.Events = { SidebarSizeChanged: "SidebarSizeChanged", ShowModeChanged: "ShowModeChanged"}WebInspector.SplitWidget.MinPadding = 20;WebInspector.SplitWidget.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.contentElement.classList.toggle("vbox", !isVertical); this.contentElement.classList.toggle("hbox", isVertical); this._isVertical = isVertical; delete this._resizerElementSize; this._sidebarSizeDIP = -1; this._restoreSidebarSizeFromSettings(); if (this._shouldSaveShowMode) this._restoreAndApplyShowModeFromSettings(); this._updateShowHideSidebarButton(); this._resizerWidget.setVertical(!isVertical); this.invalidateConstraints(); }, _updateLayout: function(animate) { delete this._totalSizeCSS; delete this._totalSizeOtherDimensionCSS; this._mainElement.style.removeProperty("width"); this._mainElement.style.removeProperty("height"); this._sidebarElement.style.removeProperty("width"); this._sidebarElement.style.removeProperty("height"); this._innerSetSidebarSizeDIP(this._preferredSidebarSizeDIP(), !!animate); }, setMainWidget: function(widget) { if (this._mainWidget) this._mainWidget.detach(); this._mainWidget = widget; if (widget) { widget.element.classList.add("insertion-point-main"); widget.element.classList.remove("insertion-point-sidebar"); if (this._showMode === WebInspector.SplitWidget.ShowMode.OnlyMain || this._showMode === WebInspector.SplitWidget.ShowMode.Both) widget.show(this.element); } }, setSidebarWidget: function(widget) { if (this._sidebarWidget) this._sidebarWidget.detach(); this._sidebarWidget = widget; if (widget) { widget.element.classList.add("insertion-point-sidebar"); widget.element.classList.remove("insertion-point-main"); if (this._showMode === WebInspector.SplitWidget.ShowMode.OnlySidebar || this._showMode === WebInspector.SplitWidget.ShowMode.Both) widget.show(this.element); } }, mainWidget: function() { return this._mainWidget; }, sidebarWidget: function() { return this._sidebarWidget; }, childWasDetached: function(widget) { if (this._detaching) return; if (this._mainWidget === widget) delete this._mainWidget; if (this._sidebarWidget === widget) delete this._sidebarWidget; }, isSidebarSecond: function() { return this._secondIsSidebar; }, enableShowModeSaving: function() { this._shouldSaveShowMode = true; this._restoreAndApplyShowModeFromSettings(); }, showMode: function() { return this._showMode; }, setSecondIsSidebar: function(secondIsSidebar) { this.contentElement.classList.toggle("shadow-split-widget-first-is-sidebar", !secondIsSidebar); this._secondIsSidebar = secondIsSidebar; }, sidebarSide: function() { if (this._showMode !== WebInspector.SplitWidget.ShowMode.Both) return null ; return this._isVertical ? (this._secondIsSidebar ? "right" : "left") : (this._secondIsSidebar ? "bottom" : "top"); }, resizerElement: function() { return this._resizerElement; }, hideMain: function(animate) { this._showOnly(this._sidebarWidget, this._mainWidget, this._sidebarElement, this._mainElement, animate); this._updateShowMode(WebInspector.SplitWidget.ShowMode.OnlySidebar); }, hideSidebar: function(animate) { this._showOnly(this._mainWidget, this._sidebarWidget, this._mainElement, this._sidebarElement, animate); this._updateShowMode(WebInspector.SplitWidget.ShowMode.OnlyMain); }, _showOnly: function(sideToShow, sideToHide, shadowToShow, shadowToHide, animate) { this._cancelAnimation(); function callback() { if (sideToShow) { if (sideToShow === this._mainWidget) this._mainWidget.show(this.element, this._sidebarWidget ? this._sidebarWidget.element : null ); else this._sidebarWidget.show(this.element); } if (sideToHide) { this._detaching = true; sideToHide.detach(); delete this._detaching; } this._resizerElement.classList.add("hidden"); shadowToShow.classList.remove("hidden"); shadowToShow.classList.add("maximized"); shadowToHide.classList.add("hidden"); shadowToHide.classList.remove("maximized"); this._removeAllLayoutProperties(); this.doResize(); } if (animate) this._animate(true, callback.bind(this)); else callback.call(this); this._sidebarSizeDIP = -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.SplitWidget.ShowMode.Both) animate = false; this._cancelAnimation(); this._mainElement.classList.remove("maximized", "hidden"); this._sidebarElement.classList.remove("maximized", "hidden"); this._resizerElement.classList.remove("hidden"); if (this._sidebarWidget) this._sidebarWidget.show(this.element); if (this._mainWidget) this._mainWidget.show(this.element, this._sidebarWidget ? this._sidebarWidget.element : null ); this.setSecondIsSidebar(this._secondIsSidebar); this._sidebarSizeDIP = -1; this.setResizable(true); this._updateShowMode(WebInspector.SplitWidget.ShowMode.Both); this._updateLayout(animate); }, setResizable: function(resizable) { this._resizerWidget.setEnabled(resizable); }, isResizable: function() { return this._resizerWidget.isEnabled(); }, setSidebarSize: function(size) { var sizeDIP = WebInspector.zoomManager.cssToDIP(size); this._savedSidebarSizeDIP = sizeDIP; this._saveSetting(); this._innerSetSidebarSizeDIP(sizeDIP, false, true); }, sidebarSize: function() { var sizeDIP = Math.max(0, this._sidebarSizeDIP); return WebInspector.zoomManager.dipToCSS(sizeDIP); }, _totalSizeDIP: function() { if (!this._totalSizeCSS) { this._totalSizeCSS = this._isVertical ? this.contentElement.offsetWidth : this.contentElement.offsetHeight; this._totalSizeOtherDimensionCSS = this._isVertical ? this.contentElement.offsetHeight : this.contentElement.offsetWidth; } return WebInspector.zoomManager.cssToDIP(this._totalSizeCSS); }, _updateShowMode: function(showMode) { this._showMode = showMode; this._saveShowModeToSettings(); this._updateShowHideSidebarButton(); this.dispatchEventToListeners(WebInspector.SplitWidget.Events.ShowModeChanged, showMode); this.invalidateConstraints(); }, _innerSetSidebarSizeDIP: function(sizeDIP, animate, userAction) { if (this._showMode !== WebInspector.SplitWidget.ShowMode.Both || !this.isShowing()) return; sizeDIP = this._applyConstraints(sizeDIP, userAction); if (this._sidebarSizeDIP === sizeDIP) return; if (!this._resizerElementSize) this._resizerElementSize = this._isVertical ? this._resizerElement.offsetWidth : this._resizerElement.offsetHeight; this._removeAllLayoutProperties(); var sidebarSizeValue = WebInspector.zoomManager.dipToCSS(sizeDIP) + "px"; var mainSizeValue = (this._totalSizeCSS - WebInspector.zoomManager.dipToCSS(sizeDIP)) + "px"; this._sidebarElement.style.flexBasis = sidebarSizeValue; if (this._isVertical) { this._sidebarElement.style.width = sidebarSizeValue; this._mainElement.style.width = mainSizeValue; this._sidebarElement.style.height = this._totalSizeOtherDimensionCSS + "px"; this._mainElement.style.height = this._totalSizeOtherDimensionCSS + "px"; } else { this._sidebarElement.style.height = sidebarSizeValue; this._mainElement.style.height = mainSizeValue; this._sidebarElement.style.width = this._totalSizeOtherDimensionCSS + "px"; this._mainElement.style.width = this._totalSizeOtherDimensionCSS + "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._sidebarSizeDIP = sizeDIP; if (animate) { this._animate(false); } else { this.doResize(); this.dispatchEventToListeners(WebInspector.SplitWidget.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 marginFrom = reverse ? "0" : "-" + WebInspector.zoomManager.dipToCSS(this._sidebarSizeDIP) + "px"; var marginTo = reverse ? "-" + WebInspector.zoomManager.dipToCSS(this._sidebarSizeDIP) + "px" : "0"; this.contentElement.style.setProperty(animatedMarginPropertyName, marginFrom); if (!reverse) { suppressUnused(this._mainElement.offsetWidth); suppressUnused(this._sidebarElement.offsetWidth); } if (!reverse) this._sidebarWidget.doResize(); this.contentElement.style.setProperty("transition", animatedMarginPropertyName + " " + animationTime + "ms linear"); var boundAnimationFrame; var startTime; function animationFrame() { delete this._animationFrameHandle; if (!startTime) { this.contentElement.style.setProperty(animatedMarginPropertyName, marginTo); startTime = window.performance.now(); } else if (window.performance.now() < startTime + animationTime) { if (this._mainWidget) this._mainWidget.doResize(); } else { this._cancelAnimation(); if (this._mainWidget) this._mainWidget.doResize(); this.dispatchEventToListeners(WebInspector.SplitWidget.Events.SidebarSizeChanged, this.sidebarSize()); return; } this._animationFrameHandle = this.contentElement.window().requestAnimationFrame(boundAnimationFrame); } boundAnimationFrame = animationFrame.bind(this); this._animationFrameHandle = this.contentElement.window().requestAnimationFrame(boundAnimationFrame); }, _cancelAnimation: function() { this.contentElement.style.removeProperty("margin-top"); this.contentElement.style.removeProperty("margin-right"); this.contentElement.style.removeProperty("margin-bottom"); this.contentElement.style.removeProperty("margin-left"); this.contentElement.style.removeProperty("transition"); if (this._animationFrameHandle) { this.contentElement.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._sidebarWidget ? this._sidebarWidget.constraints() : new Constraints(); var minSidebarSize = this.isVertical() ? constraints.minimum.width : constraints.minimum.height; if (!minSidebarSize) minSidebarSize = WebInspector.SplitWidget.MinPadding; minSidebarSize *= zoomFactor; var preferredSidebarSize = this.isVertical() ? constraints.preferred.width : constraints.preferred.height; if (!preferredSidebarSize) preferredSidebarSize = WebInspector.SplitWidget.MinPadding; preferredSidebarSize *= zoomFactor; if (sidebarSize < preferredSidebarSize) preferredSidebarSize = Math.max(sidebarSize, minSidebarSize); preferredSidebarSize += zoomFactor; constraints = this._mainWidget ? this._mainWidget.constraints() : new Constraints(); var minMainSize = this.isVertical() ? constraints.minimum.width : constraints.minimum.height; if (!minMainSize) minMainSize = WebInspector.SplitWidget.MinPadding; minMainSize *= zoomFactor; var preferredMainSize = this.isVertical() ? constraints.preferred.width : constraints.preferred.height; if (!preferredMainSize) preferredMainSize = WebInspector.SplitWidget.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.SplitWidget.ShowMode.OnlyMain) return this._mainWidget ? this._mainWidget.constraints() : new Constraints(); if (this._showMode === WebInspector.SplitWidget.ShowMode.OnlySidebar) return this._sidebarWidget ? this._sidebarWidget.constraints() : new Constraints(); var mainConstraints = this._mainWidget ? this._mainWidget.constraints() : new Constraints(); var sidebarConstraints = this._sidebarWidget ? this._sidebarWidget.constraints() : new Constraints(); var min = WebInspector.SplitWidget.MinPadding; if (this._isVertical) { mainConstraints = mainConstraints.widthToMax(min).addWidth(1); sidebarConstraints = sidebarConstraints.widthToMax(min); return mainConstraints.addWidth(sidebarConstraints).heightToMax(sidebarConstraints); } else { mainConstraints = mainConstraints.heightToMax(min).addHeight(1); sidebarConstraints = sidebarConstraints.heightToMax(min); return mainConstraints.widthToMax(sidebarConstraints).addHeight(sidebarConstraints); } }, _onResizeStart: function(event) { this._resizeStartSizeDIP = this._sidebarSizeDIP; }, _onResizeUpdate: function(event) { var offset = event.data.currentPosition - event.data.startPosition; var offsetDIP = WebInspector.zoomManager.cssToDIP(offset); var newSizeDIP = this._secondIsSidebar ? this._resizeStartSizeDIP - offsetDIP : this._resizeStartSizeDIP + offsetDIP; var constrainedSizeDIP = this._applyConstraints(newSizeDIP, true); this._savedSidebarSizeDIP = constrainedSizeDIP; this._saveSetting(); this._innerSetSidebarSizeDIP(constrainedSizeDIP, false, true); if (this.isVertical()) this._savedVerticalMainSize = this._totalSizeDIP() - this._sidebarSizeDIP; else this._savedHorizontalMainSize = this._totalSizeDIP() - this._sidebarSizeDIP; }, _onResizeEnd: function(event) { delete this._resizeStartSizeDIP; }, 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); }, _settingForOrientation: function() { var state = this._setting ? this._setting.get() : {}; return this._isVertical ? state.vertical : state.horizontal; }, _preferredSidebarSizeDIP: function() { var size = this._savedSidebarSizeDIP; 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._savedSidebarSizeDIP = settingForOrientation ? settingForOrientation.size : 0; }, _restoreAndApplyShowModeFromSettings: function() { var orientationState = this._settingForOrientation(); this._savedShowMode = orientationState && orientationState.showMode ? orientationState.showMode : this._showMode; this._showMode = this._savedShowMode; switch (this._savedShowMode) { case WebInspector.SplitWidget.ShowMode.Both: this.showBoth(); break; case WebInspector.SplitWidget.ShowMode.OnlyMain: this.hideSidebar(); break; case WebInspector.SplitWidget.ShowMode.OnlySidebar: this.hideMain(); break; } }, _saveShowModeToSettings: function() { this._savedShowMode = this._showMode; this._saveSetting(); }, _saveSetting: function() { if (!this._setting) return; var state = this._setting.get(); var orientationState = (this._isVertical ? state.vertical : state.horizontal) || {}; orientationState.size = this._savedSidebarSizeDIP; if (this._shouldSaveShowMode) orientationState.showMode = this._savedShowMode; if (this._isVertical) state.vertical = orientationState; else state.horizontal = orientationState; this._setting.set(state); }, _forceUpdateLayout: function() { this._sidebarSizeDIP = -1; this._updateLayout(); }, _onZoomChanged: function(event) { this._forceUpdateLayout(); }, displayShowHideSidebarButton: function(title, className) { console.assert(this.isVertical(), "Buttons for split widget with horizontal split are not supported yet."); this._showHideSidebarButtonTitle = WebInspector.UIString(title); this._showHideSidebarButton = this._mainElement.createChild("button", "sidebar-show-hide-button " + (className || "")); this._showHideSidebarButton.addEventListener("click", buttonClicked.bind(this), false); this._updateShowHideSidebarButton(); function buttonClicked(event) { if (this._showMode !== WebInspector.SplitWidget.ShowMode.Both) this.showBoth(true); else this.hideSidebar(true); } return this._showHideSidebarButton; }, _updateShowHideSidebarButton: function() { if (!this._showHideSidebarButton) return; var sidebarHidden = this._showMode === WebInspector.SplitWidget.ShowMode.OnlyMain; this._showHideSidebarButton.classList.toggle("toggled-show", sidebarHidden); this._showHideSidebarButton.classList.toggle("toggled-hide", !sidebarHidden); this._showHideSidebarButton.classList.toggle("top-sidebar-show-hide-button", !this.isVertical() && !this.isSidebarSecond()); this._showHideSidebarButton.classList.toggle("right-sidebar-show-hide-button", this.isVertical() && this.isSidebarSecond()); this._showHideSidebarButton.classList.toggle("bottom-sidebar-show-hide-button", !this.isVertical() && this.isSidebarSecond()); this._showHideSidebarButton.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.Widget.prototype};WebInspector.StackView = function(isVertical) { WebInspector.VBox.call(this); this._isVertical = isVertical; this._currentSplitWidget = null ;}WebInspector.StackView.prototype = { appendView: function(view, sidebarSizeSettingName, defaultSidebarWidth, defaultSidebarHeight) { var splitWidget = new WebInspector.SplitWidget(this._isVertical,true,sidebarSizeSettingName,defaultSidebarWidth,defaultSidebarHeight); splitWidget.setMainWidget(view); splitWidget.hideSidebar(); if (!this._currentSplitWidget) { splitWidget.show(this.element); } else { this._currentSplitWidget.setSidebarWidget(splitWidget); this._currentSplitWidget.showBoth(); } this._currentSplitWidget = splitWidget; return splitWidget; }, detachChildWidgets: function() { WebInspector.Widget.prototype.detachChildWidgets.call(this); this._currentSplitWidget = null ; }, __proto__: WebInspector.VBox.prototype};WebInspector.Toolbar = function(parentElement) { this._items = []; this.element = parentElement ? parentElement.createChild("div", "toolbar") : createElementWithClass("div", "toolbar"); this._shadowRoot = WebInspector.createShadowRootWithCoreStyles(this.element); this._shadowRoot.appendChild(WebInspector.Widget.createStyleElement("ui/toolbar.css")); this._contentElement = this._shadowRoot.createChild("div", "toolbar-shadow"); this._contentElement.createChild("content");}WebInspector.Toolbar.prototype = { makeVertical: function() { this._contentElement.classList.add("vertical"); }, setEnabled: function(enabled) { for (var item of this._items) item.setEnabled(enabled); }, appendToolbarItem: function(item) { this._items.push(item); item._toolbar = this; this._contentElement.insertBefore(item.element, this._contentElement.lastChild); this._hideSeparatorDupes(); }, appendSeparator: function() { this.appendToolbarItem(new WebInspector.ToolbarSeparator()); }, removeToolbarItems: function() { for (var item of this._items) delete item._toolbar; this._items = []; this._contentElement.removeChildren(); this._contentElement.createChild("content"); }, setColor: function(color) { var style = createElement("style"); style.textContent = "button.toolbar-item .glyph { background-color: " + color + " !important }"; this._shadowRoot.appendChild(style); }, setToggledColor: function(color) { var style = createElement("style"); style.textContent = "button.toolbar-item.toggled-on .glyph { background-color: " + color + " !important }"; this._shadowRoot.appendChild(style); }, _hideSeparatorDupes: function() { var previousIsSeparator = true; var lastSeparator; for (var i = 1; i < this._items.length; ++i) { if (this._items[i] instanceof WebInspector.ToolbarSeparator) { this._items[i].setVisible(!previousIsSeparator); previousIsSeparator = true; lastSeparator = this._items[i]; continue; } if (this._items[i].visible()) { previousIsSeparator = false; lastSeparator = null ; } } if (lastSeparator && lastSeparator !== this._items.peekLast()) lastSeparator.setVisible(false); }}WebInspector.ToolbarItem = function(element) { this.element = element; this.element.classList.add("toolbar-item"); this._enabled = true; this._visible = true;}WebInspector.ToolbarItem.prototype = { setEnabled: function(value) { if (this._enabled === value) return; this._enabled = value; this._applyEnabledState(); }, _applyEnabledState: function() { this.element.disabled = !this._enabled; }, visible: function() { return this._visible; }, setVisible: function(x) { if (this._visible === x) return; this.element.classList.toggle("hidden", !x); this._visible = x; if (this._toolbar && !(this instanceof WebInspector.ToolbarSeparator)) this._toolbar._hideSeparatorDupes(); }, __proto__: WebInspector.Object.prototype}WebInspector.ToolbarCounter = function(counters) { WebInspector.ToolbarItem.call(this, createElementWithClass("div", "toolbar-counter hidden")); 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", "toolbar-counter-item"); var icon = element.createChild("label", "", "dt-icon-label"); icon.type = counters[i]; var span = icon.createChild("span"); this._counters.push({ counter: counters[i], element: element, value: 0, title: "", span: span }); } this._update();}WebInspector.ToolbarCounter.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("toolbar-counter-item-first", !total); counter.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.ToolbarItem.prototype}WebInspector.ToolbarText = function(text, className) { WebInspector.ToolbarItem.call(this, createElementWithClass("span", "toolbar-text")); if (className) this.element.classList.add(className); this.element.textContent = text;}WebInspector.ToolbarText.prototype = { setText: function(text) { this.element.textContent = text; }, __proto__: WebInspector.ToolbarItem.prototype}WebInspector.ToolbarInput = function(placeholder, growFactor) { WebInspector.ToolbarItem.call(this, createElementWithClass("input", "toolbar-item")); this.element.addEventListener("input", this._onChangeCallback.bind(this), false); if (growFactor) this.element.style.flexGrow = growFactor; if (placeholder) this.element.setAttribute("placeholder", placeholder); this._value = "";}WebInspector.ToolbarInput.Event = { TextChanged: "TextChanged"};WebInspector.ToolbarInput.prototype = { setValue: function(value) { this._value = value; this.element.value = value; }, value: function() { return this.element.value; }, _onChangeCallback: function() { this.dispatchEventToListeners(WebInspector.ToolbarInput.Event.TextChanged, this.element.value); }, __proto__: WebInspector.ToolbarItem.prototype}WebInspector.ToolbarButtonBase = function(title, className, states) { WebInspector.ToolbarItem.call(this, createElementWithClass("button", className + " toolbar-item")); this.element.addEventListener("click", this._clicked.bind(this), false); this._longClickController = new WebInspector.LongClickController(this.element); this._longClickController.addEventListener(WebInspector.LongClickController.Events.LongClick, this._onLongClick.bind(this)); this._longClickController.addEventListener(WebInspector.LongClickController.Events.LongPress, this._onLongPress.bind(this)); this._states = states; if (!states) this._states = 2; if (states == 2) this._state = "off"; else this._state = "0"; this.setTitle(title); this.className = className;}WebInspector.ToolbarButtonBase.prototype = { _onLongClick: function(event) { var nativeEvent = event.data; this.dispatchEventToListeners("longClickDown", nativeEvent); }, _onLongPress: function(event) { var nativeEvent = event.data; this.dispatchEventToListeners("longPressDown", nativeEvent); }, _clicked: function() { this.dispatchEventToListeners("click"); this._longClickController.reset(); }, _applyEnabledState: function() { this.element.disabled = !this._enabled; this._longClickController.reset(); }, enabled: function() { return this._enabled; }, title: function() { return this._title; }, setTitle: function(x) { if (this._title === x) return; this._title = x; this.element.title = x; }, state: function() { return this._state; }, setState: function(x) { if (this._state === x) return; this.element.classList.remove("toggled-" + this._state); this.element.classList.add("toggled-" + x); this._state = x; }, toggled: function() { if (this._states !== 2) throw ("Only used toggled when there are 2 states, otherwise, use state"); return this.state() === "on"; }, setToggled: function(x) { if (this._states !== 2) throw ("Only used toggled when there are 2 states, otherwise, use state"); this.setState(x ? "on" : "off"); }, makeLongClickEnabled: function() { this._longClickController.enable(); this._longClickGlyph = this.element.createChild("div", "fill long-click-glyph toolbar-button-theme"); }, unmakeLongClickEnabled: function() { this._longClickController.disable(); if (this._longClickGlyph) this.element.removeChild(this._longClickGlyph); }, setLongClickOptionsEnabled: function(buttonsProvider) { if (buttonsProvider) { if (!this._longClickOptionsData) { this.makeLongClickEnabled(); var longClickDownListener = this._showOptions.bind(this); this.addEventListener("longClickDown", longClickDownListener, this); this._longClickOptionsData = { longClickDownListener: longClickDownListener }; } this._longClickOptionsData.buttonsProvider = buttonsProvider; } else { if (!this._longClickOptionsData) return; this.removeEventListener("longClickDown", this._longClickOptionsData.longClickDownListener, this); delete this._longClickOptionsData; this.unmakeLongClickEnabled(); } }, _showOptions: function() { var buttons = this._longClickOptionsData.buttonsProvider(); var mainButtonClone = new WebInspector.ToolbarButton(this.title(),this.className,this._states); mainButtonClone.addEventListener("click", this._clicked, this); mainButtonClone.setState(this.state()); buttons.push(mainButtonClone); var document = this.element.ownerDocument; document.documentElement.addEventListener("mouseup", mouseUp, false); var optionsGlassPane = new WebInspector.GlassPane(document); var optionsBar = new WebInspector.Toolbar(optionsGlassPane.element); optionsBar.element.classList.add("fill"); optionsBar._contentElement.classList.add("floating"); const buttonHeight = 26; var hostButtonPosition = this.element.totalOffset(); var topNotBottom = hostButtonPosition.top + buttonHeight * buttons.length < document.documentElement.offsetHeight; if (topNotBottom) buttons = buttons.reverse(); optionsBar.element.style.height = (buttonHeight * buttons.length) + "px"; if (topNotBottom) optionsBar.element.style.top = (hostButtonPosition.top + 1) + "px"; else optionsBar.element.style.top = (hostButtonPosition.top - (buttonHeight * (buttons.length - 1))) + "px"; optionsBar.element.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); optionsBar.appendToolbarItem(buttons[i]); } 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("toolbar-item"); buttonElement.classList.add("emulate-active"); } function mouseOut(e) { if (e.which !== 1) return; var buttonElement = e.target.enclosingNodeOrSelfWithClass("toolbar-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(e); break; } } } }, __proto__: WebInspector.ToolbarItem.prototype}WebInspector.ToolbarButton = function(title, className, states) { WebInspector.ToolbarButtonBase.call(this, title, className, states); this._glyphElement = this.element.createChild("div", "glyph toolbar-button-theme");}WebInspector.ToolbarButton.prototype = { setBackgroundImage: function(iconURL) { this.element.style.backgroundImage = "url(" + iconURL + ")"; this._glyphElement.classList.add("hidden"); }, __proto__: WebInspector.ToolbarButtonBase.prototype}WebInspector.ToolbarSettingToggle = function(setting, className, title, toggledTitle) { WebInspector.ToolbarButton.call(this, "", className, 2); this._defaultTitle = title; this._toggledTitle = toggledTitle || title; this._setting = setting; this._settingChanged(); this._setting.addChangeListener(this._settingChanged, this);}WebInspector.ToolbarSettingToggle.prototype = { _settingChanged: function() { var toggled = this._setting.get(); this.setToggled(toggled); this.setTitle(toggled ? this._toggledTitle : this._defaultTitle); }, _clicked: function() { this._setting.set(!this.toggled()); WebInspector.ToolbarButton.prototype._clicked.call(this); }, __proto__: WebInspector.ToolbarButton.prototype}WebInspector.ToolbarSeparator = function() { WebInspector.ToolbarItem.call(this, createElementWithClass("div", "toolbar-divider"));}WebInspector.ToolbarSeparator.prototype = { __proto__: WebInspector.ToolbarItem.prototype}WebInspector.ToolbarTextButton = function(title, className, text, states) { WebInspector.ToolbarButtonBase.call(this, title, className, states); this._textElement = this.element.createChild("div", "toolbar-button-text"); this._textElement.textContent = text;}WebInspector.ToolbarTextButton.prototype = { __proto__: WebInspector.ToolbarButtonBase.prototype}WebInspector.ToolbarItem.Provider = function() {}WebInspector.ToolbarItem.Provider.prototype = { item: function() {}}WebInspector.ToolbarComboBox = function(changeHandler, className) { WebInspector.ToolbarItem.call(this, createElementWithClass("span", "toolbar-select-container")); this._selectElement = this.element.createChild("select", "toolbar-item"); this.element.createChild("div", "toolbar-select-arrow"); if (changeHandler) this._selectElement.addEventListener("change", changeHandler, false); if (className) this._selectElement.classList.add(className);}WebInspector.ToolbarComboBox.prototype = { selectElement: function() { return ( this._selectElement) ; }, size: function() { return this._selectElement.childElementCount; }, options: function() { return Array.prototype.slice.call(this._selectElement.children, 0); }, 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; }, setMaxWidth: function(width) { this._selectElement.style.maxWidth = width + "px"; }, __proto__: WebInspector.ToolbarItem.prototype}WebInspector.ToolbarCheckbox = function(text, title, setting) { WebInspector.ToolbarItem.call(this, createCheckboxLabel(text)); this.element.classList.add("checkbox"); this.inputElement = this.element.checkboxElement; if (title) this.element.title = title; if (setting) WebInspector.SettingsUI.bindCheckbox(this.inputElement, setting);}WebInspector.ToolbarCheckbox.prototype = { checked: function() { return this.inputElement.checked; }, __proto__: WebInspector.ToolbarItem.prototype}WebInspector.ToolbarStatesSettingButton = function(className, states, titles, initialState, currentStateSetting, lastStateSetting, stateChangedCallback) { WebInspector.ToolbarButton.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.ToolbarButton(titles[index],className,states.length); button.setState(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.ToolbarStatesSettingButton.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.setState(defaultState); this.setTitle(this._buttons[this._states.indexOf(defaultState)].title()); }, toggle: function() { this._toggleState(this.state()); }, _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.ToolbarButton.prototype}WebInspector.ExtensibleToolbar = function(location, parentElement) { WebInspector.Toolbar.call(this, parentElement); this._loadItems(location);}WebInspector.ExtensibleToolbar.prototype = { _loadItems: function(location) { var extensions = self.runtime.extensions(WebInspector.ToolbarItem.Provider); var promises = []; for (var i = 0; i < extensions.length; ++i) { if (extensions[i].descriptor()["location"] === location) promises.push(resolveItem(extensions[i])); } Promise.all(promises).then(appendItemsInOrder.bind(this)); function resolveItem(extension) { var descriptor = extension.descriptor(); if (descriptor["separator"]) return Promise.resolve((new WebInspector.ToolbarSeparator())); if (!descriptor["className"]) return Promise.resolve(new WebInspector.ToolbarButton(WebInspector.UIString(descriptor["title"]),descriptor["elementClass"])).then(attachHandler); return extension.instancePromise().then(fetchItemFromProvider).then(attachHandler); function fetchItemFromProvider(provider) { return (provider).item(); } function attachHandler(item) { if (extension.descriptor()["actionId"] && item) item.addEventListener("click", handler); return item; } function handler() { WebInspector.actionRegistry.execute(extension.descriptor()["actionId"]); } } function appendItemsInOrder(items) { for (var i = 0; i < items.length; ++i) { var item = items[i]; if (item) this.appendToolbarItem(item); } } }, __proto__: WebInspector.Toolbar.prototype};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._maybeHideBound = this._maybeHide.bind(this); this._element = 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 totalHeight = container.offsetHeight; var aboveHeight = anchorBox.y; var underHeight = totalHeight - anchorBox.y - anchorBox.height; this._overlay.setLeftOffset(anchorBox.x); var under = underHeight >= aboveHeight; if (under) this._overlay.setVerticalOffset(anchorBox.y + anchorBox.height, true); else this._overlay.setVerticalOffset(totalHeight - anchorBox.y, false); var rowHeight = 17; var spacer = 6; var maxHeight = this._maxItemsHeight ? this._maxItemsHeight * rowHeight : Math.max(underHeight, aboveHeight) - spacer; 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._bodyElement = document.body; this._bodyElement.addEventListener("mousedown", this._maybeHideBound, true); this._overlay = new WebInspector.SuggestBox.Overlay(); this._overlay.setContentElement(this._element); }, hide: function() { if (!this.visible()) return; this._bodyElement.removeEventListener("mousedown", this._maybeHideBound, true); delete this._bodyElement; 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 = 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 = createElementWithClass("div", "suggest-box-overlay"); var root = WebInspector.createShadowRootWithCoreStyles(this.element); root.appendChild(WebInspector.Widget.createStyleElement("ui/suggestBox.css")); this._leftSpacerElement = root.createChild("div", "suggest-box-left-spacer"); this._horizontalElement = root.createChild("div", "suggest-box-horizontal"); this._topSpacerElement = this._horizontalElement.createChild("div", "suggest-box-top-spacer"); this._bottomSpacerElement = this._horizontalElement.createChild("div", "suggest-box-bottom-spacer"); this._resize(); document.body.appendChild(this.element);}WebInspector.SuggestBox.Overlay.prototype = { setLeftOffset: function(offset) { this._leftSpacerElement.style.flexBasis = offset + "px"; }, setVerticalOffset: function(offset, isTopOffset) { this.element.classList.toggle("under-anchor", isTopOffset); if (isTopOffset) { this._bottomSpacerElement.style.flexBasis = "auto"; this._topSpacerElement.style.flexBasis = offset + "px"; } else { this._bottomSpacerElement.style.flexBasis = offset + "px"; this._topSpacerElement.style.flexBasis = "auto"; } }, setContentElement: function(element) { this._horizontalElement.insertBefore(element, this._bottomSpacerElement); }, _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.TabbedPane = function() { WebInspector.VBox.call(this, true); this.registerRequiredCSS("ui/tabbedPane.css"); this.element.classList.add("tabbed-pane"); this.contentElement.classList.add("tabbed-pane-shadow"); this.contentElement.tabIndex = -1; this._headerElement = this.contentElement.createChild("div", "tabbed-pane-header toolbar-colors"); this._headerElement.createChild("content").select = ".tabbed-pane-header-before"; this._headerContentsElement = this._headerElement.createChild("div", "tabbed-pane-header-contents"); this._tabSlider = this._headerContentsElement.createChild("div", "tabbed-pane-tab-slider"); this._headerElement.createChild("content").select = ".tabbed-pane-header-after"; this._tabsElement = this._headerContentsElement.createChild("div", "tabbed-pane-header-tabs"); this._contentElement = this.contentElement.createChild("div", "tabbed-pane-content"); this._contentElement.createChild("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 ; }, setShrinkableTabs: function(shrinkableTabs) { this._shrinkableTabs = shrinkableTabs; }, setVerticalTabLayout: function(verticalTabLayout) { this._verticalTabLayout = verticalTabLayout; this.contentElement.classList.add("vertical-tab-layout"); this.invalidateConstraints(); }, setCloseableTabs: function(closeableTabs) { this._closeableTabs = closeableTabs; }, setRetainTabOrder: function(retainTabOrder, tabOrderComparator) { this._retainTabOrder = retainTabOrder; this._tabOrderComparator = tabOrderComparator; }, defaultFocusedElement: function() { return this.visibleView ? this.visibleView.defaultFocusedElement() : this.contentElement; }, focus: function() { if (this.visibleView) this.visibleView.focus(); else this.contentElement.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._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() { return this._tabs.map(function(tab) { return tab.id; } ); }, otherTabs: function(id) { var result = []; for (var i = 0; i < this._tabs.length; ++i) { if (this._tabs[i].id !== id) result.push(this._tabs[i].id); } return result; }, _tabsToTheRight: function(id) { var index = -1; for (var i = 0; i < this._tabs.length; ++i) { if (this._tabs[i].id === id) { index = i; break; } } if (index === -1) return []; return this._tabs.slice(index + 1).map(function(tab) { return tab.id; } ); }, 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, iconType, iconTooltip) { var tab = this._tabsById[id]; if (tab._setIconType(iconType, iconTooltip)) this._updateTabElements(); }, toggleTabClass: function(id, className, force) { var tab = this._tabsById[id]; if (tab._toggleClass(className, force)) 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; }, onResize: function() { this._updateTabElements(); }, headerResized: function() { this._updateTabElements(); }, wasShown: function() { var effectiveTab = this._currentTab || this._tabsHistory[0]; if (effectiveTab) this.selectTab(effectiveTab.id); }, setTabSlider: function(enable) { this._sliderEnabled = enable; this._tabSlider.classList.toggle("enabled", enable); }, 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(120,0))); else constraints = constraints.addHeight(new Constraints(new Size(0,30))); 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(); this._updateTabSlider(); }, _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 = createElementWithClass("div", "tabbed-pane-header-tabs-drop-down-container"); dropDownContainer.createTextChild("\u00bb"); this._dropDownMenu = new WebInspector.DropDownMenu(dropDownContainer); this._dropDownMenu.addEventListener(WebInspector.DropDownMenu.Events.ItemSelected, this._dropDownMenuItemSelected, this); 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) { var width = measuringTabElements[i].getBoundingClientRect().width; measuringTabElements[i].__tab._measuredWidth = Math.ceil(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; var tabsToLookAt = tabsOrdered.slice(0); if (this._currentTab !== undefined) tabsToLookAt.unshift(tabsToLookAt.splice(tabsToLookAt.indexOf(this._currentTab), 1)[0]); for (var i = 0; i < tabCount; ++i) { var tab = this._retainTabOrder ? tabsToLookAt[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.element); this._updateTabSlider(); }, _updateTabSlider: function() { if (!this._currentTab) return; if (!this._sliderEnabled) return; var left = 0; for (var i = 0; i < this._tabs.length && this._currentTab !== this._tabs[i] && this._tabs[i]._shown; i++) left += this._tabs[i]._measuredWidth; var sliderWidth = this._currentTab._shown ? this._currentTab._measuredWidth : this._dropDownButton.offsetWidth; this._tabSlider.style.transform = "translateX(" + left + "px)"; this._tabSlider.style.width = sliderWidth + "px"; }, _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 || null , 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); }, insertBeforeTabStrip: function(element) { element.classList.add("tabbed-pane-header-before"); this.element.appendChild(element); }, appendAfterTabStrip: function(element) { element.classList.add("tabbed-pane-header-after"); this.element.appendChild(element); }, renderWithNoHeaderBackground: function() { this._headerElement.classList.add("tabbed-pane-no-header-background"); }, __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; }, isCloseable: function() { return this._closeable; }, _setIconType: function(iconType, iconTooltip) { if (iconType === this._iconType && iconTooltip === this._iconTooltip) return false; this._iconType = iconType; this._iconTooltip = iconTooltip; if (this._tabElement) this._createIconElement(this._tabElement, this._titleElement); delete this._measuredWidth; return true; }, _toggleClass: function(className, force) { var element = this.tabElement; var hasClass = element.classList.contains(className); if (hasClass === force) return false; element.classList.toggle(className, force); 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) { if (tabElement.__iconElement) tabElement.__iconElement.remove(); if (!this._iconType) return; var iconElement = createElementWithClass("label", "tabbed-pane-header-tab-icon", "dt-icon-label"); iconElement.type = this._iconType; if (this._iconTooltip) iconElement.title = this._iconTooltip; tabElement.insertBefore(iconElement, titleElement); tabElement.__iconElement = iconElement; }, _createTabElement: function(measuring) { var tabElement = 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 || ""; this._createIconElement(tabElement, titleElement); if (!measuring) this._titleElement = titleElement; if (this._closeable) tabElement.createChild("div", "tabbed-pane-close-button", "dt-close-button").gray = true; 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); tabElement.addEventListener("contextmenu", this._tabContextMenu.bind(this), false); if (this._closeable) 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("tabbed-pane-close-button")); if (!shouldClose) { this._tabbedPane.focus(); return; } this._closeTabs([this.id]); event.consume(true); }, _tabMouseDown: function(event) { if (event.target.classList.contains("tabbed-pane-close-button") || 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()); } function closeToTheRight() { this._closeTabs(this._tabbedPane._tabsToTheRight(this.id)); } var contextMenu = new WebInspector.ContextMenu(event); if (this._closeable) { contextMenu.appendItem(WebInspector.UIString.capitalize("Close"), close.bind(this)); contextMenu.appendItem(WebInspector.UIString.capitalize("Close ^others"), closeOthers.bind(this)); contextMenu.appendItem(WebInspector.UIString.capitalize("Close ^tabs to the ^right"), closeToTheRight.bind(this)); contextMenu.appendItem(WebInspector.UIString.capitalize("Close ^all"), closeAll.bind(this)); } if (this._delegate) this._delegate.onContextMenu(this.id, contextMenu); contextMenu.show(); }, _startTabDragging: function(event) { if (event.target.classList.contains("tabbed-pane-close-button")) 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) {}, onContextMenu: function(tabId, contextMenu) {}}WebInspector.ExtensibleTabbedPaneController = function(tabbedPane, extensionPoint, viewCallback) { this._tabbedPane = tabbedPane; this._extensionPoint = extensionPoint; this._viewCallback = viewCallback; this._tabOrders = {}; this._promiseForId = {}; this._tabbedPane.setRetainTabOrder(true, this._tabOrderComparator.bind(this)); this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); this._views = new Map(); this._initialize();}WebInspector.ExtensibleTabbedPaneController.prototype = { _initialize: function() { this._extensions = new Map(); var extensions = self.runtime.extensions(this._extensionPoint); for (var i = 0; i < extensions.length; ++i) { var descriptor = extensions[i].descriptor(); var id = descriptor["name"]; this._tabOrders[id] = i; var title = WebInspector.UIString(descriptor["title"]); this._extensions.set(id, extensions[i]); this._tabbedPane.appendTab(id, title, new WebInspector.Widget()); } }, appendView: function(id, title, order, view) { this._tabOrders[id] = order; this._views.set(id, view); this._tabbedPane.appendTab(id, title, new WebInspector.Widget()); }, _tabSelected: function(event) { var tabId = (event.data.tabId); this.viewForId(tabId).then(viewLoaded.bind(this)); function viewLoaded(view) { if (!view) return; this._tabbedPane.changeTabView(tabId, view); var shouldFocus = this._tabbedPane.visibleView.element.isSelfOrAncestor(WebInspector.currentFocusElement()); if (shouldFocus) view.focus(); } }, viewIds: function() { return this._extensions.keysArray(); }, viewForId: function(id) { if (this._views.has(id)) return Promise.resolve((this._views.get(id))); if (!this._extensions.has(id)) return Promise.resolve((null )); if (this._promiseForId[id]) return this._promiseForId[id]; var promise = this._extensions.get(id).instancePromise(); this._promiseForId[id] = (promise); return promise.then(cacheView.bind(this)); function cacheView(object) { var view = (object); delete this._promiseForId[id]; this._views.set(id, view); if (this._viewCallback && view) this._viewCallback(id, view); return view; } }, _tabOrderComparator: function(id1, id2) { return this._tabOrders[id2] = this._tabOrders[id1]; }};WebInspector.SidebarPane = function(title) { WebInspector.Widget.call(this); this.setMinimumSize(25, 0); this.element.className = "sidebar-pane"; this._title = title; this._expandCallback = null ; this._paneVisible = true;}WebInspector.SidebarPane.prototype = { toolbar: function() { if (!this._toolbar) { this._toolbar = new WebInspector.Toolbar(); this._toolbar.element.addEventListener("click", consumeEvent); this.element.insertBefore(this._toolbar.element, this.element.firstChild); } return this._toolbar; }, title: function() { return this._title; }, expand: function() { this.onContentReady(); }, onContentReady: function() { if (this._expandCallback) this._expandCallback(); else this._expandPending = true; }, _attached: function(setVisibleCallback, expandCallback) { this._setVisibleCallback = setVisibleCallback; this._setVisibleCallback(this._paneVisible); this._expandCallback = expandCallback; if (this._expandPending) { delete this._expandPending; this._expandCallback(); } }, setVisible: function(visible) { this._paneVisible = visible; if (this._setVisibleCallback) this._setVisibleCallback(visible) }, __proto__: WebInspector.Widget.prototype}WebInspector.SidebarPaneTitle = function(container, pane) { this._pane = pane; this.element = container.createChild("div", "sidebar-pane-title"); 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);}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.Widget.call(this); this.setMinimumSize(25, 0); this.element.className = "sidebar-pane-stack"; this._titleByPane = new Map();}WebInspector.SidebarPaneStack.prototype = { addPane: function(pane) { var paneTitle = new WebInspector.SidebarPaneTitle(this.element,pane); this._titleByPane.set(pane, paneTitle); if (pane._toolbar) paneTitle.element.appendChild(pane._toolbar.element); pane._attached(this._setPaneVisible.bind(this, pane), paneTitle._expand.bind(paneTitle)); }, _setPaneVisible: function(pane, visible) { var title = this._titleByPane.get(pane); if (!title) return; title.element.classList.toggle("hidden", !visible); pane.element.classList.toggle("sidebar-pane-hidden", !visible); }, __proto__: WebInspector.Widget.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); if (pane._toolbar) pane.element.insertBefore(pane._toolbar.element, pane.element.firstChild); pane._attached(this._setPaneVisible.bind(this, pane), this.selectTab.bind(this, title)); }, _setPaneVisible: function(pane, visible) { var title = pane._title; if (visible) { if (!this.hasTab(title)) this.appendTab(title, title, pane); } else { if (this.hasTab(title)) this.closeTab(title); } }, __proto__: WebInspector.TabbedPane.prototype};WebInspector.TextPrompt = function(completions, stopCharacters) { this._proxyElement; this._proxyElementDisplay = "inline-block"; this._loadCompletions = completions; this._completionStopCharacters = stopCharacters || " =:[({;,!+-*/&|^<>."; this._autocompletionTimeout = WebInspector.TextPrompt.DefaultAutocompletionTimeout;}WebInspector.TextPrompt.DefaultAutocompletionTimeout = 250;WebInspector.TextPrompt.Events = { ItemApplied: "text-prompt-item-applied", ItemAccepted: "text-prompt-item-accepted"};WebInspector.TextPrompt.prototype = { setAutocompletionTimeout: function(timeout) { this._autocompletionTimeout = timeout; }, setSuggestBoxEnabled: function(suggestBoxEnabled) { this._suggestBoxEnabled = suggestBoxEnabled; }, renderAsBlock: function() { this._proxyElementDisplay = "block"; }, attach: function(element) { return this._attachInternal(element); }, attachAndStartEditing: function(element, blurListener) { var proxyElement = this._attachInternal(element); this._startEditing(blurListener); return 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"); var shadowRoot = WebInspector.createShadowRootWithCoreStyles(this._proxyElement); shadowRoot.appendChild(WebInspector.Widget.createStyleElement("ui/textPrompt.css")); this._contentElement = shadowRoot.createChild("div"); this._contentElement.createChild("content"); 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); this._element.ownerDocument.defaultView.addEventListener("resize", 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); }, text: function() { return this._element.textContent; }, setText: function(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); this._element.ownerDocument.defaultView.removeEventListener("resize", this._boundRemoveSuggestionAids, false); if (this._isEditing) this._stopEditing(); if (this._suggestBox) this._suggestBox.removeFromElement(); }, _startEditing: function(blurListener) { this._isEditing = true; this._contentElement.classList.add("text-prompt-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._contentElement.classList.remove("text-prompt-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() && this._element.isComponentSelectionCollapsed()) { 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 : this._autocompletionTimeout); }, complete: function(force, reverse) { this.clearAutoComplete(true); var selection = this._element.getComponentSelection(); 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 = 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; }, _createRange: function() { return document.createRange(); }, _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 = this._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 = this._createRange(); var prefixTextNode = createTextNode(prefixText); fullWordRange.insertNode(prefixTextNode); this.autoCompleteElement = 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 = this._createRange(); var completionTextNode = 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 = this._element.getComponentSelection(); selection.removeAllRanges(); selection.addRange(finalSelectionRange); if (isIntermediateSuggestion) this.dispatchEventToListeners(WebInspector.TextPrompt.Events.ItemApplied, { itemText: completionText }); }, acceptSuggestion: function() { this._acceptSuggestionInternal(); }, _acceptSuggestionInternal: function(prefixAccepted) { if (!this.autoCompleteElement || !this.autoCompleteElement.parentNode) return false; var text = this.autoCompleteElement.textContent; var textNode = createTextNode(text); this.autoCompleteElement.parentNode.replaceChild(textNode, this.autoCompleteElement); delete this.autoCompleteElement; var finalSelectionRange = this._createRange(); finalSelectionRange.setStart(textNode, text.length); finalSelectionRange.setEnd(textNode, text.length); var selection = this._element.getComponentSelection(); 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 = this._element.getComponentSelection(); 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 = this._element.getComponentSelection(); 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 = this._element.getComponentSelection(); 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 = this._element.getComponentSelection(); var selectionRange = this._createRange(); var container = this._element; while (container.childNodes.length) container = container.lastChild; var offset = container.nodeType === Node.TEXT_NODE ? container.textContent.length : 0; selectionRange.setStart(container, offset); selectionRange.setEnd(container, offset); selection.removeAllRanges(); selection.addRange(selectionRange); }, tabKeyPressed: function(event) { this._completeCommonPrefix(); return true; }, proxyElementForTests: function() { return this._proxyElement || null ; }, __proto__: WebInspector.Object.prototype}WebInspector.TextPromptWithHistory = function(completions, stopCharacters) { WebInspector.TextPrompt.call(this, completions, stopCharacters); this._data = []; this._historyOffset = 1;}WebInspector.TextPromptWithHistory.prototype = { historyData: function() { return this._data; }, 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 (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.setText(newText); if (isPrevious) { var firstNewlineIndex = this.text().indexOf("\n"); if (firstNewlineIndex === -1) this.moveCaretToEndOfPrompt(); else { var selection = this._element.getComponentSelection(); var selectionRange = this._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.highlightedSearchResultClassName = "highlighted-search-result";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; WebInspector._dragEventsTargetDocument = targetDocument; WebInspector._dragEventsTargetDocumentTop = targetDocument.defaultView.top.document; targetDocument.addEventListener("mousemove", WebInspector._elementDragMove, true); targetDocument.addEventListener("mouseup", WebInspector._elementDragEnd, true); targetDocument.addEventListener("mouseout", WebInspector._mouseOutWhileDragging, true); if (targetDocument !== WebInspector._dragEventsTargetDocumentTop) WebInspector._dragEventsTargetDocumentTop.addEventListener("mouseup", WebInspector._elementDragEnd, true); var targetElement = (event.target); if (typeof cursor === "string") { WebInspector._restoreCursorAfterDrag = restoreCursor.bind(null , targetElement.style.cursor); targetElement.style.cursor = cursor; targetDocument.body.style.cursor = cursor; } function restoreCursor(oldCursor) { targetDocument.body.style.removeProperty("cursor"); targetElement.style.cursor = oldCursor; WebInspector._restoreCursorAfterDrag = null ; } event.preventDefault();}WebInspector._mouseOutWhileDragging = function() { var document = WebInspector._mouseOutWhileDraggingTargetDocument; WebInspector._unregisterMouseOutWhileDragging(); WebInspector._elementDraggingGlassPane = new WebInspector.GlassPane(document);}WebInspector._unregisterMouseOutWhileDragging = function() { if (!WebInspector._mouseOutWhileDraggingTargetDocument) return; WebInspector._mouseOutWhileDraggingTargetDocument.removeEventListener("mouseout", WebInspector._mouseOutWhileDragging, true); delete WebInspector._mouseOutWhileDraggingTargetDocument;}WebInspector._unregisterDragEvents = function() { if (!WebInspector._dragEventsTargetDocument) return; WebInspector._dragEventsTargetDocument.removeEventListener("mousemove", WebInspector._elementDragMove, true); WebInspector._dragEventsTargetDocument.removeEventListener("mouseup", WebInspector._elementDragEnd, true); if (WebInspector._dragEventsTargetDocument !== WebInspector._dragEventsTargetDocumentTop) WebInspector._dragEventsTargetDocumentTop.removeEventListener("mouseup", WebInspector._elementDragEnd, true); delete WebInspector._dragEventsTargetDocument; delete WebInspector._dragEventsTargetDocumentTop;}WebInspector._elementDragMove = function(event) { if (event.buttons !== 1) { WebInspector._elementDragEnd(event); return; } if (WebInspector._elementDraggingEventListener((event))) WebInspector._cancelDragEvents(event);}WebInspector._cancelDragEvents = function(event) { WebInspector._unregisterDragEvents(); WebInspector._unregisterMouseOutWhileDragging(); if (WebInspector._restoreCursorAfterDrag) WebInspector._restoreCursorAfterDrag(); 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(document) { this.element = createElement("div"); this.element.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;background-color:transparent;z-index:1000;overflow:hidden;"; 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.parentElementOrShadowHost(); } return false;}WebInspector.isEditing = function() { if (WebInspector.__editingCount) return true; var element = WebInspector.currentFocusElement(); if (!element) return false; return element.classList.contains("text-prompt") || element.nodeName === "INPUT" || element.nodeName === "TEXTAREA";}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.createReplacementString = function(wordString, event, customNumberHandler) { 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 null ; replacementString = customNumberHandler ? customNumberHandler(prefix, number, suffix) : prefix + number + suffix; } } return replacementString || null ;}WebInspector.handleElementValueModifications = function(event, element, finishHandler, suggestionHandler, customNumberHandler) { function createRange() { return document.createRange(); } 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 = element.getComponentSelection(); 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 = WebInspector.createReplacementString(wordString, event, customNumberHandler); if (replacementString) { var replacementTextNode = createTextNode(replacementString); wordRange.deleteContents(); wordRange.insertNode(replacementTextNode); var finalSelectionRange = 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);}WebInspector._subMillisFormat = new WebInspector.UIStringFormat("%.3f\u2009ms");WebInspector._millisFormat = new WebInspector.UIStringFormat("%.0f\u2009ms");WebInspector._secondsFormat = new WebInspector.UIStringFormat("%.2f\u2009s");WebInspector._minutesFormat = new WebInspector.UIStringFormat("%.1f\u2009min");WebInspector._hoursFormat = new WebInspector.UIStringFormat("%.1f\u2009hrs");WebInspector._daysFormat = new WebInspector.UIStringFormat("%.1f\u2009days");Number.millisToString = function(ms, higherResolution) { if (!isFinite(ms)) return "-"; if (ms === 0) return "0"; if (higherResolution && ms < 1000) return WebInspector._subMillisFormat.format(ms); else if (ms < 1000) return WebInspector._millisFormat.format(ms); var seconds = ms / 1000; if (seconds < 60) return WebInspector._secondsFormat.format(seconds); var minutes = seconds / 60; if (minutes < 60) return WebInspector._minutesFormat.format(minutes); var hours = minutes / 60; if (hours < 24) return WebInspector._hoursFormat.format(hours); var days = hours / 24; return WebInspector._daysFormat.format(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.formatLocalized = function(format, substitutions, initialValue) { var element = createElement("span"); var formatters = { s: function(substitution) { return substitution; } }; function append(a, b) { if (typeof b === "string") b = createTextNode(b); else if (b.shadowRoot) b = createTextNode(b.shadowRoot.lastChild.textContent); element.appendChild(b); } String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append); return element;}WebInspector.openLinkExternallyLabel = function() { return WebInspector.UIString.capitalize("Open ^link in ^new ^tab");}WebInspector.copyLinkAddressLabel = function() { return WebInspector.UIString.capitalize("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.installComponentRootStyles = function(element) { element.appendChild(WebInspector.Widget.createStyleElement("ui/inspectorCommon.css")); element.appendChild(WebInspector.Widget.createStyleElement("ui/inspectorSyntaxHighlight.css")); element.classList.add("platform-" + WebInspector.platform()); if (Runtime.experiments.isEnabled("materialDesign")) element.classList.add("material");}WebInspector.createShadowRootWithCoreStyles = function(element) { var shadowRoot = element.createShadowRoot(); shadowRoot.appendChild(WebInspector.Widget.createStyleElement("ui/inspectorCommon.css")); shadowRoot.appendChild(WebInspector.Widget.createStyleElement("ui/inspectorSyntaxHighlight.css")); shadowRoot.addEventListener("focus", WebInspector._focusChanged.bind(WebInspector), true); return shadowRoot;}WebInspector._windowFocused = function(document, event) { if (event.target.document.nodeType === Node.DOCUMENT_NODE) document.body.classList.remove("inactive");}WebInspector._windowBlurred = function(document, 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) { var node = event.deepActiveElement(); WebInspector.setCurrentFocusElement(node);}WebInspector._documentBlurred = function(document, 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 = x.getComponentSelection(); 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.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, WebInspector.highlightedSearchResultClassName, changes);}WebInspector.runCSSAnimationOnce = function(element, className) { function animationEndCallback() { element.classList.remove(className); element.removeEventListener("webkitAnimationEnd", animationEndCallback, false); } if (element.classList.contains(className)) element.classList.remove(className); element.addEventListener("webkitAnimationEnd", animationEndCallback, false); element.classList.add(className);}WebInspector.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes) { changes = changes || []; var highlightNodes = []; var lineText = element.deepTextContent(); var ownerDocument = element.ownerDocument; var textNodes = element.childTextNodes(); if (textNodes.length === 0) return highlightNodes; var nodeRanges = []; var rangeEndOffset = 0; for (var i = 0; i < textNodes.length; ++i) { var range = {}; range.offset = rangeEndOffset; range.length = textNodes[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 < textNodes.length && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset) startIndex++; var endIndex = startIndex; while (endIndex < textNodes.length && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset) endIndex++; if (endIndex === textNodes.length) break; var highlightNode = ownerDocument.createElement("span"); highlightNode.className = styleClass; highlightNode.textContent = lineText.substring(startOffset, endOffset); var lastTextNode = textNodes[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 = textNodes[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 = textNodes[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.measurePreferredSize = function(element, containerElement) { containerElement = containerElement || element.ownerDocument.body; containerElement.appendChild(element); element.positionAt(0, 0); var result = new Size(element.offsetWidth,element.offsetHeight); element.positionAt(undefined, undefined); element.remove(); return result;}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.set(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.keysArray(); for (var i = 0; i < keys.length; ++i) { var object = keys[i]; var methods = handlers.get(object).valuesArray(); 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(window, 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 = window.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;}WebInspector.LongClickController = function(element) { this._element = element;}WebInspector.LongClickController.Events = { LongClick: "LongClick", LongPress: "LongPress"};WebInspector.LongClickController.prototype = { reset: function() { if (this._longClickInterval) { clearInterval(this._longClickInterval); delete this._longClickInterval; } }, enable: function() { if (this._longClickData) return; var boundMouseDown = mouseDown.bind(this); var boundMouseUp = mouseUp.bind(this); var boundReset = this.reset.bind(this); this._element.addEventListener("mousedown", boundMouseDown, false); this._element.addEventListener("mouseout", boundReset, false); this._element.addEventListener("mouseup", boundMouseUp, false); this._element.addEventListener("click", boundReset, true); var longClicks = 0; this._longClickData = { mouseUp: boundMouseUp, mouseDown: boundMouseDown, reset: boundReset }; function mouseDown(e) { if (e.which !== 1) return; longClicks = 0; this._longClickInterval = setInterval(longClicked.bind(this, e), 200); } function mouseUp(e) { if (e.which !== 1) return; this.reset(); } function longClicked(e) { ++longClicks; this.dispatchEventToListeners(longClicks === 1 ? WebInspector.LongClickController.Events.LongClick : WebInspector.LongClickController.Events.LongPress, e); } }, disable: function() { if (!this._longClickData) return; this._element.removeEventListener("mousedown", this._longClickData.mouseDown, false); this._element.removeEventListener("mouseout", this._longClickData.reset, false); this._element.removeEventListener("mouseup", this._longClickData.mouseUp, false); this._element.addEventListener("click", this._longClickData.reset, true); delete this._longClickData; }, __proto__: WebInspector.Object.prototype}WebInspector.initializeUIUtils = function(window) { window.addEventListener("focus", WebInspector._windowFocused.bind(WebInspector, window.document), false); window.addEventListener("blur", WebInspector._windowBlurred.bind(WebInspector, window.document), false); window.document.addEventListener("focus", WebInspector._focusChanged.bind(WebInspector), true); window.document.addEventListener("blur", WebInspector._documentBlurred.bind(WebInspector, window.document), true);}WebInspector.beautifyFunctionName = function(name) { return name || WebInspector.UIString("(anonymous function)");}function registerCustomElement(localName, typeExtension, prototype) { return document.registerElement(typeExtension, { prototype: Object.create(prototype), extends: localName });}function createTextButton(text, clickHandler, className, title) { var element = createElementWithClass("button", className || "", "text-button"); element.textContent = text; if (clickHandler) element.addEventListener("click", clickHandler, false); if (title) element.title = title; return element;}function createRadioLabel(name, title, checked) { var element = createElement("label", "dt-radio"); element.radioElement.name = name; element.radioElement.checked = !!checked; element.createTextChild(title); return element;}function createCheckboxLabel(title, checked) { var element = createElement("label", "dt-checkbox"); element.checkboxElement.checked = !!checked; if (title !== undefined) { element.textElement = element.createChild("div", "dt-checkbox-text"); element.textElement.textContent = title; } return element;};(function() { registerCustomElement("button", "text-button", { createdCallback: function() { this.type = "button"; var root = WebInspector.createShadowRootWithCoreStyles(this); root.appendChild(WebInspector.Widget.createStyleElement("ui/textButton.css")); root.createChild("content"); }, __proto__: HTMLButtonElement.prototype }); registerCustomElement("label", "dt-radio", { createdCallback: function() { this.radioElement = this.createChild("input", "dt-radio-button"); this.radioElement.type = "radio"; var root = WebInspector.createShadowRootWithCoreStyles(this); root.appendChild(WebInspector.Widget.createStyleElement("ui/radioButton.css")); root.createChild("content").select = ".dt-radio-button"; root.createChild("content"); this.addEventListener("click", radioClickHandler, false); }, __proto__: HTMLLabelElement.prototype }); function radioClickHandler(event) { if (this.radioElement.checked || this.radioElement.disabled) return; this.radioElement.checked = true; this.radioElement.dispatchEvent(new Event("change")); } registerCustomElement("label", "dt-checkbox", { createdCallback: function() { this._root = WebInspector.createShadowRootWithCoreStyles(this); this._root.appendChild(WebInspector.Widget.createStyleElement("ui/checkboxTextLabel.css")); var checkboxElement = createElementWithClass("input", "dt-checkbox-button"); checkboxElement.type = "checkbox"; this._root.appendChild(checkboxElement); this.checkboxElement = checkboxElement; this.addEventListener("click", toggleCheckbox.bind(this)); function toggleCheckbox(event) { if (event.target !== checkboxElement && event.target !== this) checkboxElement.click(); } this._root.createChild("content"); }, set backgroundColor(color) { this.checkboxElement.classList.add("dt-checkbox-themed"); this.checkboxElement.style.backgroundColor = color; }, set checkColor(color) { this.checkboxElement.classList.add("dt-checkbox-themed"); var stylesheet = createElement("style"); stylesheet.textContent = "input.dt-checkbox-themed:checked:after { background-color: " + color + "}"; this._root.appendChild(stylesheet); }, set borderColor(color) { this.checkboxElement.classList.add("dt-checkbox-themed"); this.checkboxElement.style.borderColor = color; }, __proto__: HTMLLabelElement.prototype }); registerCustomElement("label", "dt-icon-label", { createdCallback: function() { var root = WebInspector.createShadowRootWithCoreStyles(this); root.appendChild(WebInspector.Widget.createStyleElement("ui/smallIcon.css")); this._iconElement = root.createChild("div"); root.createChild("content"); }, set type(type) { this._iconElement.className = type; }, __proto__: HTMLLabelElement.prototype }); registerCustomElement("div", "dt-close-button", { createdCallback: function() { var root = WebInspector.createShadowRootWithCoreStyles(this); root.appendChild(WebInspector.Widget.createStyleElement("ui/closeButton.css")); this._buttonElement = root.createChild("div", "close-button"); }, set gray(gray) { this._buttonElement.className = gray ? "close-button-gray" : "close-button"; }, __proto__: HTMLDivElement.prototype });})();WebInspector.StringFormatter = function() { this._processors = []; this._regexes = [];}WebInspector.StringFormatter.prototype = { addProcessor: function(regex, handler) { this._regexes.push(regex); this._processors.push(handler); }, formatText: function(text) { return this._runProcessor(0, text); }, _runProcessor: function(processorIndex, text) { if (processorIndex >= this._processors.length) return createTextNode(text); var container = createDocumentFragment(); var regex = this._regexes[processorIndex]; var processor = this._processors[processorIndex]; var items = text.replace(regex, "\0$1\0").split("\0"); for (var i = 0; i < items.length; ++i) { var processedNode = i % 2 ? processor(items[i]) : this._runProcessor(processorIndex + 1, items[i]); container.appendChild(processedNode); } return container; }};WebInspector.ViewportControl = function(provider) { this.element = 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 = this.element.getComponentSelection(); 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(this.element.getComponentSelection()); 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().deepTextContent()); 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.ZoomManager = function(window, 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; }, cssToDIP: function(value) { return value * this._zoomFactor; }, dipToCSS: function(valueDIP) { return valueDIP / 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.ThrottledWidget = function() { WebInspector.Widget.call(this); this._updateThrottler = new WebInspector.Throttler(100); this._updateWhenVisible = false;}WebInspector.ThrottledWidget.prototype = { doUpdate: function(finishedCallback) { finishedCallback(); }, update: function() { this._updateWhenVisible = !this.isShowing(); if (this._updateWhenVisible) return; this._updateThrottler.schedule(innerUpdate.bind(this)); function innerUpdate(finishedCallback) { if (this.isShowing()) { this.doUpdate(finishedCallback); } else { this._updateWhenVisible = true; finishedCallback(); } } }, wasShown: function() { WebInspector.Widget.prototype.wasShown.call(this); if (this._updateWhenVisible) this.update(); }, __proto__: WebInspector.Widget.prototype};function InspectorBackendClass() { this._connection = null ; this._agentPrototypes = {}; this._dispatcherPrototypes = {}; this._initialized = false; this._enums = {}; this._initProtocolAgentsConstructor();}InspectorBackendClass._DevToolsErrorCode = -32000;InspectorBackendClass.reportProtocolError = function(error, messageObject) { console.error(error + ": " + JSON.stringify(messageObject));}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; }, 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(", ") + "]);"); } } 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"] = {}; }, 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"; }, 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) { InspectorBackendClass.reportProtocolError("Protocol Error: the message with wrong id", 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 { if (messageObject.error) { InspectorBackendClass.reportProtocolError("Generic message format error", messageObject); return; } var method = messageObject.method.split("."); var domainName = method[0]; if (!(domainName in this._dispatchers)) { InspectorBackendClass.reportProtocolError("Protocol Error: the message " + messageObject.method + " is for non-existing domain '" + domainName + "'", messageObject); 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); setTimeout(function() { if (!this._pendingResponsesCount) this._executeAfterPendingDispatches(); else this.runAfterPendingDispatches(); } .bind(this), 0); }, _executeAfterPendingDispatches: function() { 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, can't dispatch pending " + methodName, 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); InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.DispatchMessageChunk, this._dispatchMessageChunk, this);}InspectorBackendClass.MainConnection.prototype = { sendMessage: function(messageObject) { var message = JSON.stringify(messageObject); InspectorFrontendHost.sendMessageToBackend(message); }, _dispatchMessage: function(event) { this.dispatch((event.data)); }, _dispatchMessageChunk: function(event) { var messageChunk = (event.data["messageChunk"]); var messageSize = (event.data["messageSize"]); if (messageSize) { this._messageBuffer = ""; this._messageSize = messageSize; } this._messageBuffer += messageChunk; if (this._messageBuffer.length === this._messageSize) { this.dispatch(this._messageBuffer); this._messageBuffer = ""; this._messageSize = 0; } }, __proto__: InspectorBackendClass.Connection.prototype}InspectorBackendClass.WebSocketConnection = function(url, onConnectionReady) { InspectorBackendClass.Connection.call(this); this._socket = new WebSocket(url); this._socket.onmessage = 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) { 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; this._promisified = domain in InspectorBackendClass.AgentPrototype.PromisifiedDomains;}InspectorBackendClass.AgentPrototype.PromisifiedDomains = { "CSS": true, "Profiler": true}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 = Array.prototype.slice.call(arguments); InspectorBackendClass.AgentPrototype.prototype._sendMessageToBackend.call(this, domainAndMethod, signature, params); } function sendMessagePromise(vararg) { var params = Array.prototype.slice.call(arguments); return InspectorBackendClass.AgentPrototype.prototype._sendMessageToBackendPromise.call(this, domainAndMethod, signature, replyArgs, params); } this[methodName] = this._promisified ? sendMessagePromise : 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; }, _prepareParameters: function(method, signature, args, allowExtraUndefinedArg, errorCallback) { 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) { errorCallback("Protocol Error: Invalid number of arguments for method '" + method + "' call. It must have the following arguments '" + JSON.stringify(signature) + "'."); return null ; } var value = args.shift(); if (optionalFlag && typeof value === "undefined") continue;if (typeof value !== typeName) { errorCallback("Protocol Error: Invalid type of argument '" + paramName + "' for method '" + method + "' call. It must be '" + typeName + "' but it is '" + typeof value + "'."); return null ; } params[paramName] = value; hasParams = true; } if (args.length === 1 && (!allowExtraUndefinedArg || (typeof args[0] !== "undefined"))) { errorCallback("Protocol Error: Optional callback argument for method '" + method + "' call must be a function but its type is '" + typeof args[0] + "'."); return null ; } if (args.length > 1) { errorCallback("Protocol Error: Extra " + args.length + " arguments in a call to method '" + method + "'."); return null ; } return hasParams ? params : null }, _sendMessageToBackend: function(method, signature, args) { var errorMessage; function onError(message) { console.error(message) errorMessage = message; } var callback = (args.length && typeof args.peekLast() === "function") ? args.pop() : null ; var params = this._prepareParameters(method, signature, args, !callback, onError); if (errorMessage) return; this._connection._wrapCallbackAndSendMessageObject(this._domain, method, params, callback); }, _sendMessageToBackendPromise: function(method, signature, replyArgs, args) { var errorMessage; function onError(message) { console.error(message) errorMessage = message; } var userCallback = (args.length && typeof args.peekLast() === "function") ? args.pop() : null ; var params = this._prepareParameters(method, signature, args, false, onError); if (errorMessage) return Promise.reject(new Error(errorMessage)); else return new Promise(promiseAction.bind(this)); function promiseAction(resolve, reject) { function callback(vararg) { var result = userCallback ? userCallback.apply(null , arguments) : undefined; resolve(result); } this._connection._wrapCallbackAndSendMessageObject(this._domain, method, params, 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) { var id = InspectorFrontendHost.isUnderTest() ? "##" : messageObject.id; console.error("Request with id = " + 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)) { InspectorBackendClass.reportProtocolError("Protocol Error: Attempted to dispatch an unimplemented method '" + messageObject.method + "'", messageObject); return; } if (!this._eventArgs[messageObject.method]) { InspectorBackendClass.reportProtocolError("Protocol Error: Attempted to dispatch an unspecified method '" + messageObject.method + "'", messageObject); 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.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("Memory.getDOMCounters", [], ["documents", "nodes", "jsEventListeners"], false);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.DialogType", { Alert: "alert", Confirm: "confirm", Prompt: "prompt", Beforeunload: "beforeunload"});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", "type"]);InspectorBackend.registerEvent("Page.javascriptDialogClosed", ["result"]);InspectorBackend.registerEvent("Page.screencastFrame", ["data", "metadata", "frameNumber"]);InspectorBackend.registerEvent("Page.screencastVisibilityChanged", ["visible"]);InspectorBackend.registerEvent("Page.colorPicked", ["color"]);InspectorBackend.registerEvent("Page.interstitialShown", []);InspectorBackend.registerEvent("Page.interstitialHidden", []);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}], [], 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}, { "name": "screenWidth", "type": "number", "optional": true}, { "name": "screenHeight", "type": "number", "optional": true}, { "name": "positionX", "type": "number", "optional": true}, { "name": "positionY", "type": "number", "optional": true}], [], false);InspectorBackend.registerCommand("Page.clearDeviceMetricsOverride", [], [], 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}, { "name": "configuration", "type": "string", "optional": true}], [], 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.screencastFrameAck", [{ "name": "frameNumber", "type": "number", "optional": false}], [], 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.setColorPickerEnabled", [{ "name": "enabled", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerCommand("Page.setOverlayMessage", [{ "name": "message", "type": "string", "optional": true}], [], false);InspectorBackend.registerCommand("Rendering.setShowPaintRects", [{ "name": "result", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerCommand("Rendering.setShowDebugBorders", [{ "name": "show", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerCommand("Rendering.setShowFPSCounter", [{ "name": "show", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerCommand("Rendering.setContinuousPaintingEnabled", [{ "name": "enabled", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerCommand("Rendering.setShowScrollBottleneckRects", [{ "name": "show", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerEvent("Emulation.viewportChanged", ["viewport"]);InspectorBackend.registerCommand("Emulation.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}, { "name": "screenWidth", "type": "number", "optional": true}, { "name": "screenHeight", "type": "number", "optional": true}, { "name": "positionX", "type": "number", "optional": true}, { "name": "positionY", "type": "number", "optional": true}], [], false);InspectorBackend.registerCommand("Emulation.clearDeviceMetricsOverride", [], [], false);InspectorBackend.registerCommand("Emulation.resetScrollAndPageScaleFactor", [], [], false);InspectorBackend.registerCommand("Emulation.setPageScaleFactor", [{ "name": "pageScaleFactor", "type": "number", "optional": false}], [], false);InspectorBackend.registerCommand("Emulation.setScriptExecutionDisabled", [{ "name": "value", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerCommand("Emulation.setGeolocationOverride", [{ "name": "latitude", "type": "number", "optional": true}, { "name": "longitude", "type": "number", "optional": true}, { "name": "accuracy", "type": "number", "optional": true}], [], false);InspectorBackend.registerCommand("Emulation.clearGeolocationOverride", [], [], false);InspectorBackend.registerCommand("Emulation.setTouchEmulationEnabled", [{ "name": "enabled", "type": "boolean", "optional": false}, { "name": "configuration", "type": "string", "optional": true}], [], false);InspectorBackend.registerCommand("Emulation.setEmulatedMedia", [{ "name": "media", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("Emulation.canEmulate", [], ["result"], false);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", Map: "map", Set: "set", Iterator: "iterator", Generator: "generator", Error: "error"});InspectorBackend.registerEnum("Runtime.ObjectPreviewType", { Object: "object", Function: "function", Undefined: "undefined", String: "string", Number: "number", Boolean: "boolean", Symbol: "symbol"});InspectorBackend.registerEnum("Runtime.ObjectPreviewSubtype", { Array: "array", Null: "null", Node: "node", Regexp: "regexp", Date: "date", Map: "map", Set: "set", Iterator: "iterator", Generator: "generator", Error: "error"});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", Map: "map", Set: "set", Iterator: "iterator", Generator: "generator", Error: "error"});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}, { "name": "generatePreview", "type": "boolean", "optional": true}], ["result", "internalProperties", "exceptionDetails"], 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.registerCommand("Runtime.setCustomObjectFormatterEnabled", [{ "name": "enabled", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerEnum("Console.ConsoleMessageSource", { XML: "xml", Javascript: "javascript", Network: "network", ConsoleAPI: "console-api", Storage: "storage", Appcache: "appcache", Rendering: "rendering", Security: "security", Other: "other", Deprecation: "deprecation"});InspectorBackend.registerEnum("Console.ConsoleMessageLevel", { Log: "log", Warning: "warning", Error: "error", Debug: "debug", Info: "info", RevokedError: "revokedError"});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.registerEnum("Network.InitiatorType", { Parser: "parser", Script: "script", Other: "other"});InspectorBackend.registerEvent("Network.requestWillBeSent", ["requestId", "frameId", "loaderId", "documentURL", "request", "timestamp", "wallTime", "initiator", "redirectResponse", "type"]);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", "wallTime", "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.registerEvent("Network.eventSourceMessageReceived", ["requestId", "timestamp", "eventName", "eventId", "data"]);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.setMonitoringXHREnabled", [{ "name": "enabled", "type": "boolean", "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.getCookies", [], ["cookies"], false);InspectorBackend.registerCommand("Network.deleteCookie", [{ "name": "cookieName", "type": "string", "optional": false}, { "name": "url", "type": "string", "optional": false}], [], 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.setDataSizeLimitsForTest", [{ "name": "maxTotalSize", "type": "number", "optional": false}, { "name": "maxResourceSize", "type": "number", "optional": false}], [], false);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.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.registerCommand("CacheStorage.requestCacheNames", [{ "name": "securityOrigin", "type": "string", "optional": false}], ["caches"], false);InspectorBackend.registerCommand("CacheStorage.requestEntries", [{ "name": "cacheId", "type": "string", "optional": false}, { "name": "skipCount", "type": "number", "optional": false}, { "name": "pageSize", "type": "number", "optional": false}], ["cacheDataEntries", "hasMore"], false);InspectorBackend.registerCommand("CacheStorage.deleteCache", [{ "name": "cacheId", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("CacheStorage.deleteEntry", [{ "name": "cacheId", "type": "string", "optional": false}, { "name": "request", "type": "string", "optional": false}], [], false);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.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.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.registerEnum("DOM.PseudoType", { FirstLine: "first-line", FirstLetter: "first-letter", Before: "before", After: "after", Backdrop: "backdrop", Selection: "selection", FirstLineInherited: "first-line-inherited", Scrollbar: "scrollbar", ScrollbarThumb: "scrollbar-thumb", ScrollbarButton: "scrollbar-button", ScrollbarTrack: "scrollbar-track", ScrollbarTrackPiece: "scrollbar-track-piece", ScrollbarCorner: "scrollbar-corner", Resizer: "resizer", InputListButton: "input-list-button"});InspectorBackend.registerEnum("DOM.ShadowRootType", { UserAgent: "user-agent", Author: "author"});InspectorBackend.registerEvent("DOM.documentUpdated", []);InspectorBackend.registerEvent("DOM.inspectNodeRequested", ["backendNodeId"]);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.registerEvent("DOM.distributedNodesUpdated", ["insertionPointId", "distributedNodes"]);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.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": "backendNodeId", "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.setInspectedNode", [{ "name": "nodeId", "type": "number", "optional": false}], [], 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.registerCommand("DOM.getHighlightObjectForTest", [{ "name": "nodeId", "type": "number", "optional": false}], ["highlight"], false);InspectorBackend.registerEnum("CSS.StyleSheetOrigin", { Injected: "injected", 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}], ["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.setRuleSelector", [{ "name": "styleSheetId", "type": "string", "optional": false}, { "name": "range", "type": "object", "optional": false}, { "name": "selector", "type": "string", "optional": false}], ["rule"], false);InspectorBackend.registerCommand("CSS.setStyleText", [{ "name": "styleSheetId", "type": "string", "optional": false}, { "name": "range", "type": "object", "optional": false}, { "name": "text", "type": "string", "optional": false}], ["style"], false);InspectorBackend.registerCommand("CSS.setMediaText", [{ "name": "styleSheetId", "type": "string", "optional": false}, { "name": "range", "type": "object", "optional": false}, { "name": "text", "type": "string", "optional": false}], ["media"], 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.registerCommand("CSS.setEffectivePropertyValueForNode", [{ "name": "nodeId", "type": "number", "optional": false}, { "name": "propertyName", "type": "string", "optional": false}, { "name": "value", "type": "string", "optional": false}], [], false);InspectorBackend.registerEvent("Timeline.eventRecorded", ["record"]);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.registerEnum("Debugger.GeneratorObjectDetailsStatus", { Running: "running", Suspended: "suspended", Closed: "closed"});InspectorBackend.registerEnum("Debugger.ScopeType", { Global: "global", Local: "local", With: "with", Closure: "closure", Catch: "catch", Block: "block", Script: "script"});InspectorBackend.registerEnum("Debugger.PromiseDetailsStatus", { Pending: "pending", Resolved: "resolved", Rejected: "rejected"});InspectorBackend.registerEvent("Debugger.globalObjectCleared", []);InspectorBackend.registerEvent("Debugger.scriptParsed", ["scriptId", "url", "startLine", "startColumn", "endLine", "endColumn", "isContentScript", "isInternalScript", "sourceMapURL", "hasSourceURL"]);InspectorBackend.registerEvent("Debugger.scriptFailedToParse", ["scriptId", "url", "startLine", "startColumn", "endLine", "endColumn", "isContentScript", "isInternalScript", "sourceMapURL", "hasSourceURL"]);InspectorBackend.registerEvent("Debugger.breakpointResolved", ["breakpointId", "location"]);InspectorBackend.registerEvent("Debugger.paused", ["callFrames", "reason", "data", "hitBreakpoints", "asyncStackTrace"]);InspectorBackend.registerEvent("Debugger.resumed", []);InspectorBackend.registerEvent("Debugger.promiseUpdated", ["eventType", "promise"]);InspectorBackend.registerEvent("Debugger.asyncOperationStarted", ["operation"]);InspectorBackend.registerEvent("Debugger.asyncOperationCompleted", ["id"]);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}], [], 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}], ["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.stepIntoAsync", [], [], 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.getGeneratorObjectDetails", [{ "name": "objectId", "type": "string", "optional": false}], ["details"], false);InspectorBackend.registerCommand("Debugger.getCollectionEntries", [{ "name": "objectId", "type": "string", "optional": false}], ["entries"], 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": "persistScript", "type": "boolean", "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.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}, { "name": "skipContentScripts", "type": "boolean", "optional": true}], [], false);InspectorBackend.registerCommand("Debugger.setAsyncCallStackDepth", [{ "name": "maxDepth", "type": "number", "optional": false}], [], false);InspectorBackend.registerCommand("Debugger.enablePromiseTracker", [{ "name": "captureStacks", "type": "boolean", "optional": true}], [], false);InspectorBackend.registerCommand("Debugger.disablePromiseTracker", [], [], false);InspectorBackend.registerCommand("Debugger.getPromiseById", [{ "name": "promiseId", "type": "number", "optional": false}, { "name": "objectGroup", "type": "string", "optional": true}], ["promise"], false);InspectorBackend.registerCommand("Debugger.flushAsyncOperationEvents", [], [], false);InspectorBackend.registerCommand("Debugger.setAsyncOperationBreakpoint", [{ "name": "operationId", "type": "number", "optional": false}], [], false);InspectorBackend.registerCommand("Debugger.removeAsyncOperationBreakpoint", [{ "name": "operationId", "type": "number", "optional": false}], [], false);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.registerCommand("DOMDebugger.getEventListeners", [{ "name": "objectId", "type": "string", "optional": false}], ["listeners"], false);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.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.addInspectedHeapObject", [{ "name": "heapObjectId", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("HeapProfiler.getHeapObjectId", [{ "name": "objectId", "type": "string", "optional": false}], ["heapSnapshotObjectId"], false);InspectorBackend.registerEvent("Worker.workerCreated", ["workerId", "url", "inspectorConnected"]);InspectorBackend.registerEvent("Worker.workerTerminated", ["workerId"]);InspectorBackend.registerEvent("Worker.dispatchMessageFromWorker", ["workerId", "message"]);InspectorBackend.registerCommand("Worker.enable", [], [], false);InspectorBackend.registerCommand("Worker.disable", [], [], false);InspectorBackend.registerCommand("Worker.sendMessageToWorker", [{ "name": "workerId", "type": "string", "optional": false}, { "name": "message", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("Worker.connectToWorker", [{ "name": "workerId", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("Worker.disconnectFromWorker", [{ "name": "workerId", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("Worker.setAutoconnectToWorkers", [{ "name": "value", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionRunningStatus", { Stopped: "stopped", Starting: "starting", Running: "running", Stopping: "stopping"});InspectorBackend.registerEnum("ServiceWorker.ServiceWorkerVersionStatus", { New: "new", Installing: "installing", Installed: "installed", Activating: "activating", Activated: "activated", Redundant: "redundant"});InspectorBackend.registerEvent("ServiceWorker.workerCreated", ["workerId", "url"]);InspectorBackend.registerEvent("ServiceWorker.workerTerminated", ["workerId"]);InspectorBackend.registerEvent("ServiceWorker.dispatchMessage", ["workerId", "message"]);InspectorBackend.registerEvent("ServiceWorker.workerRegistrationUpdated", ["registrations"]);InspectorBackend.registerEvent("ServiceWorker.workerVersionUpdated", ["versions"]);InspectorBackend.registerEvent("ServiceWorker.workerErrorReported", ["errorMessage"]);InspectorBackend.registerEvent("ServiceWorker.debugOnStartUpdated", ["debugOnStart"]);InspectorBackend.registerCommand("ServiceWorker.enable", [], [], false);InspectorBackend.registerCommand("ServiceWorker.disable", [], [], false);InspectorBackend.registerCommand("ServiceWorker.sendMessage", [{ "name": "workerId", "type": "string", "optional": false}, { "name": "message", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.stop", [{ "name": "workerId", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.unregister", [{ "name": "scopeURL", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.updateRegistration", [{ "name": "scopeURL", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.startWorker", [{ "name": "scopeURL", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.stopWorker", [{ "name": "versionId", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.inspectWorker", [{ "name": "versionId", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.skipWaiting", [{ "name": "versionId", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.setDebugOnStart", [{ "name": "debugOnStart", "type": "boolean", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.deliverPushMessage", [{ "name": "origin", "type": "string", "optional": false}, { "name": "registrationId", "type": "string", "optional": false}, { "name": "data", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ServiceWorker.getTargetInfo", [{ "name": "targetId", "type": "string", "optional": false}], ["targetInfo"], false);InspectorBackend.registerCommand("ServiceWorker.activateTarget", [{ "name": "targetId", "type": "string", "optional": false}], [], false);InspectorBackend.registerEnum("Input.TouchPointState", { TouchPressed: "touchPressed", TouchReleased: "touchReleased", TouchMoved: "touchMoved", TouchStationary: "touchStationary", TouchCancelled: "touchCancelled"});InspectorBackend.registerEnum("Input.GestureSourceType", { Default: "default", Touch: "touch", Mouse: "mouse"});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": "code", "type": "string", "optional": true}, { "name": "key", "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": "timestamp", "type": "number", "optional": false}, { "name": "button", "type": "string", "optional": false}, { "name": "deltaX", "type": "number", "optional": true}, { "name": "deltaY", "type": "number", "optional": true}, { "name": "modifiers", "type": "number", "optional": true}, { "name": "clickCount", "type": "number", "optional": true}], [], false);InspectorBackend.registerCommand("Input.synthesizePinchGesture", [{ "name": "x", "type": "number", "optional": false}, { "name": "y", "type": "number", "optional": false}, { "name": "scaleFactor", "type": "number", "optional": false}, { "name": "relativeSpeed", "type": "number", "optional": true}, { "name": "gestureSourceType", "type": "string", "optional": true}], [], false);InspectorBackend.registerCommand("Input.synthesizeScrollGesture", [{ "name": "x", "type": "number", "optional": false}, { "name": "y", "type": "number", "optional": false}, { "name": "xDistance", "type": "number", "optional": true}, { "name": "yDistance", "type": "number", "optional": true}, { "name": "xOverscroll", "type": "number", "optional": true}, { "name": "yOverscroll", "type": "number", "optional": true}, { "name": "preventFling", "type": "boolean", "optional": true}, { "name": "speed", "type": "number", "optional": true}, { "name": "gestureSourceType", "type": "string", "optional": true}], [], false);InspectorBackend.registerCommand("Input.synthesizeTapGesture", [{ "name": "x", "type": "number", "optional": false}, { "name": "y", "type": "number", "optional": false}, { "name": "duration", "type": "number", "optional": true}, { "name": "tapCount", "type": "number", "optional": true}, { "name": "gestureSourceType", "type": "string", "optional": true}], [], false);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": "tiles", "type": "object", "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}, { "name": "clipRect", "type": "object", "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.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.registerEnum("ScreenOrientation.OrientationType", { PortraitPrimary: "portraitPrimary", PortraitSecondary: "portraitSecondary", LandscapePrimary: "landscapePrimary", LandscapeSecondary: "landscapeSecondary"});InspectorBackend.registerCommand("ScreenOrientation.setScreenOrientationOverride", [{ "name": "angle", "type": "number", "optional": false}, { "name": "type", "type": "string", "optional": false}], [], false);InspectorBackend.registerCommand("ScreenOrientation.clearScreenOrientationOverride", [], [], false);InspectorBackend.registerEvent("Tracing.dataCollected", ["value"]);InspectorBackend.registerEvent("Tracing.tracingComplete", []);InspectorBackend.registerEvent("Tracing.bufferUsage", ["percentFull", "eventCount", "value"]);InspectorBackend.registerCommand("Tracing.start", [{ "name": "categories", "type": "string", "optional": true}, { "name": "options", "type": "string", "optional": true}, { "name": "bufferUsageReportingInterval", "type": "number", "optional": true}], [], false);InspectorBackend.registerCommand("Tracing.end", [], [], false);InspectorBackend.registerCommand("Tracing.getCategories", [], ["categories"], false);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);InspectorBackend.registerEnum("Animation.AnimationType", { CSSTransition: "CSSTransition", CSSAnimation: "CSSAnimation", WebAnimation: "WebAnimation"});InspectorBackend.registerEvent("Animation.animationCreated", ["player", "resetTimeline"]);InspectorBackend.registerEvent("Animation.animationCanceled", ["id"]);InspectorBackend.registerCommand("Animation.enable", [], [], false);InspectorBackend.registerCommand("Animation.disable", [], [], false);InspectorBackend.registerCommand("Animation.getPlaybackRate", [], ["playbackRate"], false);InspectorBackend.registerCommand("Animation.setPlaybackRate", [{ "name": "playbackRate", "type": "number", "optional": false}], [], false);InspectorBackend.registerCommand("Animation.setCurrentTime", [{ "name": "currentTime", "type": "number", "optional": false}], [], false);InspectorBackend.registerCommand("Animation.setTiming", [{ "name": "playerId", "type": "string", "optional": false}, { "name": "duration", "type": "number", "optional": false}, { "name": "delay", "type": "number", "optional": false}], [], false);InspectorBackend.registerEnum("Accessibility.AXValueType", { Boolean: "boolean", Tristate: "tristate", BooleanOrUndefined: "booleanOrUndefined", Idref: "idref", IdrefList: "idrefList", Integer: "integer", Number: "number", String: "string", Token: "token", TokenList: "tokenList", DomRelation: "domRelation", Role: "role", InternalRole: "internalRole"});InspectorBackend.registerEnum("Accessibility.AXPropertySourceType", { Attribute: "attribute", Implicit: "implicit", Style: "style"});InspectorBackend.registerEnum("Accessibility.AXGlobalStates", { Disabled: "disabled", Hidden: "hidden", HiddenRoot: "hiddenRoot", Invalid: "invalid"});InspectorBackend.registerEnum("Accessibility.AXLiveRegionAttributes", { Live: "live", Atomic: "atomic", Relevant: "relevant", Busy: "busy", Root: "root"});InspectorBackend.registerEnum("Accessibility.AXWidgetAttributes", { Autocomplete: "autocomplete", Haspopup: "haspopup", Level: "level", Multiselectable: "multiselectable", Orientation: "orientation", Multiline: "multiline", Readonly: "readonly", Required: "required", Valuemin: "valuemin", Valuemax: "valuemax", Valuetext: "valuetext"});InspectorBackend.registerEnum("Accessibility.AXWidgetStates", { Checked: "checked", Expanded: "expanded", Pressed: "pressed", Selected: "selected"});InspectorBackend.registerEnum("Accessibility.AXRelationshipAttributes", { Activedescendant: "activedescendant", Flowto: "flowto", Controls: "controls", Describedby: "describedby", Labelledby: "labelledby", Owns: "owns"});InspectorBackend.registerCommand("Accessibility.getAXNode", [{ "name": "nodeId", "type": "number", "optional": false}], ["accessibilityNode"], false);InspectorBackend.registerEnum("Security.SecurityState", { Unknown: "unknown", Http: "http", Insecure: "insecure", Warning: "warning", Secure: "secure"});InspectorBackend.registerEvent("Security.securityStateChanged", ["securityState", "explanations"]);InspectorBackend.registerCommand("Security.enable", [], [], false);InspectorBackend.registerCommand("Security.disable", [], [], false);;WebInspector.Target = function(name, type, connection, parentTarget, callback) { Protocol.Agents.call(this, connection.agentsMap()); this._name = name; this._type = type; this._connection = connection; this._parentTarget = parentTarget; 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, this._loadedWithCapabilities.bind(this, callback)));}WebInspector.Target.Capabilities = { CanScreencast: "CanScreencast"}WebInspector.Target.Type = { Page: 1, DedicatedWorker: 2, ServiceWorker: 4}WebInspector.Target._nextId = 1;WebInspector.Target.prototype = { id: function() { return this._id; }, name: function() { return this._name; }, decorateLabel: function(label) { return this.isWorker() ? "\u2699 " + label : label; }, _initializeCapability: function(name, callback, error, result) { this._capabilities[name] = result; if (callback) callback(); }, hasCapability: function(capability) { return !!this._capabilities[capability]; }, _loadedWithCapabilities: function(callback) { if (this._connection.isClosed()) { callback(null ); return; } this.consoleModel = new WebInspector.ConsoleModel(this); this.networkManager = new WebInspector.NetworkManager(this); this.resourceTreeModel = new WebInspector.ResourceTreeModel(this); this.networkLog = new WebInspector.NetworkLog(this); if (this.hasJSContext()) new WebInspector.DebuggerModel(this); this.runtimeModel = new WebInspector.RuntimeModel(this); if (this._type === WebInspector.Target.Type.Page) { new WebInspector.DOMModel(this); new WebInspector.CSSStyleModel(this); } this.workerManager = !this.isDedicatedWorker() ? new WebInspector.WorkerManager(this) : null ; this.cpuProfilerModel = new WebInspector.CPUProfilerModel(this); this.heapProfilerModel = new WebInspector.HeapProfilerModel(this); this.layerTreeModel = new WebInspector.LayerTreeModel(this); this.tracingManager = new WebInspector.TracingManager(this); if (this.isPage() && (Runtime.experiments.isEnabled("serviceWorkersInPageFrontend") || Runtime.experiments.isEnabled("serviceWorkersInResources"))) this.serviceWorkerManager = new WebInspector.ServiceWorkerManager(this); if (callback) callback(this); }, registerDispatcher: function(domain, dispatcher) { this._connection.registerDispatcher(domain, dispatcher); }, isPage: function() { return this._type === WebInspector.Target.Type.Page; }, isWorker: function() { return this.isDedicatedWorker() || this.isServiceWorker(); }, isDedicatedWorker: function() { return this._type === WebInspector.Target.Type.DedicatedWorker; }, isServiceWorker: function() { return this._type === WebInspector.Target.Type.ServiceWorker; }, hasJSContext: function() { return !this.isServiceWorker(); }, parentTarget: function() { return this._parentTarget; }, _onDisconnect: function() { WebInspector.targetManager.removeTarget(this); this._dispose(); }, _dispose: function() { WebInspector.targetManager.dispatchEventToListeners(WebInspector.TargetManager.Events.TargetDisposed, this); this.networkManager.dispose(); this.cpuProfilerModel.dispose(); WebInspector.ServiceWorkerCacheModel.fromTarget(this).dispose(); if (this.workerManager) this.workerManager.dispose(); }, isDetached: function() { return this._connection.isClosed(); }, model: function(modelClass) { return this._modelByConstructor.get(modelClass) || null ; }, __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.set(modelClass, this);}WebInspector.SDKModel.prototype = { __proto__: WebInspector.SDKObject.prototype}WebInspector.TargetManager = function() { WebInspector.Object.call(this); this._targets = []; this._observers = []; this._observerTypeSymbol = Symbol("observerType"); this._modelListeners = {}; this._suspendCount = 0;}WebInspector.TargetManager.Events = { InspectedURLChanged: "InspectedURLChanged", MainFrameNavigated: "MainFrameNavigated", Load: "Load", WillReloadPage: "WillReloadPage", SuspendStateChanged: "SuspendStateChanged", TargetDisposed: "TargetDisposed"}WebInspector.TargetManager.prototype = { suspendAllTargets: function() { if (this._suspendCount++) return; this.dispatchEventToListeners(WebInspector.TargetManager.Events.SuspendStateChanged); }, resumeAllTargets: function() { console.assert(this._suspendCount > 0); if (--this._suspendCount) return; this.dispatchEventToListeners(WebInspector.TargetManager.Events.SuspendStateChanged); }, allTargetsSuspended: function() { return !!this._suspendCount; }, inspectedPageURL: function() { if (!this._targets.length) return ""; return this._targets[0].resourceTreeModel.inspectedPageURL(); }, inspectedPageDomain: function() { if (!this._targets.length) return ""; return this._targets[0].resourceTreeModel.inspectedPageDomain(); }, _redispatchEvent: function(event) { this.dispatchEventToListeners(event.type, event.data); }, reloadPage: function(ignoreCache) { if (this._targets.length) this._targets[0].resourceTreeModel.reloadPage(ignoreCache); }, addModelListener: function(modelClass, eventType, listener, thisObject) { for (var i = 0; i < this._targets.length; ++i) { var model = this._targets[i]._modelByConstructor.get(modelClass); if (model) model.addEventListener(eventType, listener, thisObject); } if (!this._modelListeners[eventType]) this._modelListeners[eventType] = []; this._modelListeners[eventType].push({ modelClass: modelClass, thisObject: thisObject, listener: listener }); }, removeModelListener: function(modelClass, eventType, listener, thisObject) { if (!this._modelListeners[eventType]) return; for (var i = 0; i < this._targets.length; ++i) { var model = this._targets[i]._modelByConstructor.get(modelClass); if (model) model.removeEventListener(eventType, listener, thisObject); } var listeners = this._modelListeners[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._modelListeners[eventType]; }, observeTargets: function(targetObserver, type) { if (this._observerTypeSymbol in targetObserver) throw new Error("Observer can only be registered once"); targetObserver[this._observerTypeSymbol] = type || 0x7fff; this.targets(type).forEach(targetObserver.targetAdded.bind(targetObserver)); this._observers.push(targetObserver); }, unobserveTargets: function(targetObserver) { delete targetObserver[this._observerTypeSymbol]; this._observers.remove(targetObserver); }, createTarget: function(name, type, connection, parentTarget, callback) { new WebInspector.Target(name,type,connection,parentTarget,callbackWrapper.bind(this)); function callbackWrapper(newTarget) { if (newTarget) this.addTarget(newTarget); if (callback) callback(newTarget); } }, _observersByType: function(type) { var result = []; for (var observer of this._observers) { if (observer[this._observerTypeSymbol] & type) result.push(observer); } return result; }, addTarget: function(target) { this._targets.push(target); if (this._targets.length === 1) { target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._redispatchEvent, this); target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._redispatchEvent, this); target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.Load, this._redispatchEvent, this); target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.WillReloadPage, this._redispatchEvent, this); } var copy = this._observersByType(target._type); for (var i = 0; i < copy.length; ++i) copy[i].targetAdded(target); for (var eventType in this._modelListeners) { var listeners = this._modelListeners[eventType]; for (var i = 0; i < listeners.length; ++i) { var model = target._modelByConstructor.get(listeners[i].modelClass); if (model) model.addEventListener(eventType, listeners[i].listener, listeners[i].thisObject); } } }, removeTarget: function(target) { this._targets.remove(target); if (this._targets.length === 0) { target.resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._redispatchEvent, this); target.resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._redispatchEvent, this); target.resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.Load, this._redispatchEvent, this); target.resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.WillReloadPage, this._redispatchEvent, this); } var copy = this._observersByType(target._type); for (var i = 0; i < copy.length; ++i) copy[i].targetRemoved(target); for (var eventType in this._modelListeners) { var listeners = this._modelListeners[eventType]; for (var i = 0; i < listeners.length; ++i) { var model = target._modelByConstructor.get(listeners[i].modelClass); if (model) model.removeEventListener(eventType, listeners[i].listener, listeners[i].thisObject); } } }, hasTargets: function(type) { return !!this.targets(type).length; }, targets: function(type) { if (!type) return this._targets.slice(); var result = []; for (var target of this._targets) { if (target._type & type) result.push(target); } return result; }, targetsWithJSContext: function() { var result = []; for (var target of this._targets) { if (target.hasJSContext()) result.push(target); } return result; }, targetById: function(id) { for (var i = 0; i < this._targets.length; ++i) { if (this._targets[i].id() === id) return this._targets[i]; } return null ; }, mainTarget: function() { return this._targets[0] || null ; }, __proto__: WebInspector.Object.prototype}WebInspector.TargetManager.Observer = function() {}WebInspector.TargetManager.Observer.prototype = { targetAdded: function(target) {}, targetRemoved: function(target) {},}WebInspector.targetManager = new WebInspector.TargetManager();;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; 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.ConsoleModel = function(target) { WebInspector.SDKModel.call(this, WebInspector.ConsoleModel, target); this._messages = []; this._messageById = new Map(); this._warnings = 0; this._errors = 0; this._revokedErrors = 0; this._consoleAgent = target.consoleAgent(); target.registerConsoleDispatcher(new WebInspector.ConsoleDispatcher(this)); this._enableAgent();}WebInspector.ConsoleModel.Events = { ConsoleCleared: "ConsoleCleared", MessageAdded: "MessageAdded", MessageUpdated: "MessageUpdated", CommandEvaluated: "CommandEvaluated",}WebInspector.ConsoleModel.prototype = { _enableAgent: function() { this._enablingConsole = true; function callback() { delete this._enablingConsole; } this._consoleAgent.enable(callback.bind(this)); }, addMessage: function(msg) { if (msg.level === WebInspector.ConsoleMessage.MessageLevel.RevokedError && msg._relatedMessageId) { var relatedMessage = this._messageById.get(msg._relatedMessageId); if (!relatedMessage) return; this._errors--; this._revokedErrors++; relatedMessage.level = WebInspector.ConsoleMessage.MessageLevel.RevokedError; this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.MessageUpdated, relatedMessage); return; } this._messages.push(msg); if (msg._messageId) this._messageById.set(msg._messageId, 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; case WebInspector.ConsoleMessage.MessageLevel.RevokedError: this._revokedErrors++; break; } }, messages: function() { return this._messages; }, requestClearMessages: function() { this._consoleAgent.clearMessages(); this._messagesCleared(); }, _messagesCleared: function() { this._messages = []; this._messageById.clear(); this._errors = 0; this._revokedErrors = 0; this._warnings = 0; this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.ConsoleCleared); }, errors: function() { return this._errors; }, revokedErrors: function() { return this._revokedErrors; }, warnings: function() { return this._warnings; }, __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.showPromise().then(reportUponEvaluation); function reportUponEvaluation() { target.consoleModel.dispatchEventToListeners(WebInspector.ConsoleModel.Events.CommandEvaluated, { result: result, wasThrown: wasThrown, text: text, commandMessage: commandMessage, exceptionDetails: exceptionDetails }); } } executionContext.evaluate(text, "console", useCommandLineAPI, false, false, true, printResult); WebInspector.userMetrics.ConsoleEvaluated.record();}WebInspector.ConsoleMessage = function(target, source, level, messageText, type, url, line, column, requestId, parameters, stackTrace, timestamp, executionContextId, asyncStackTrace, scriptId, messageId, relatedMessageId) { this._target = target; this.source = source; this.level = level; this.messageText = messageText; this.type = type || WebInspector.ConsoleMessage.MessageType.Log; this.url = url || undefined; this.line = line || 0; this.column = column || 0; this.parameters = parameters; this.stackTrace = stackTrace; this.timestamp = timestamp || Date.now(); this.executionContextId = executionContextId || 0; this.asyncStackTrace = asyncStackTrace; this.scriptId = scriptId || null ; this._messageId = messageId || 0; this._relatedMessageId = relatedMessageId || 0; this.request = requestId ? target.networkLog.requestForId(requestId) : null ; if (this.request) { var initiator = this.request.initiator(); if (initiator) { this.stackTrace = initiator.stackTrace || undefined; this.asyncStackTrace = initiator.asyncStackTrace; if (initiator.url) { this.url = initiator.url; this.line = initiator.lineNumber || 0; } } }}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) ; }, isEqual: function(msg) { if (!msg) return false; if (this._messageId || msg._messageId) return false; if (this._relatedMessageId || msg._relatedMessageId) 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) && (this.scriptId === msg.scriptId); }, _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", RevokedError: "revokedError"};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,payload.executionContextId,payload.asyncStackTrace,payload.scriptId,payload.messageId,payload.relatedMessageId); this._console.addMessage(consoleMessage); }, messageRepeatCountUpdated: function(count) {}, messagesCleared: function() { if (!WebInspector.moduleSetting("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.MessageUpdated, this._consoleMessageUpdated, 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); }, _consoleMessageUpdated: function(event) { this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.MessageUpdated, event.data); }, _commandEvaluated: function(event) { this.dispatchEventToListeners(WebInspector.ConsoleModel.Events.CommandEvaluated, event.data); }, __proto__: WebInspector.Object.prototype}WebInspector.multitargetConsoleModel;;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) { WebInspector.ResourceLoader.loadUsingTargetUA(this._sourceURL, {}, contentLoaded.bind(this)); function contentLoaded(statusCode, headers, content) { if (statusCode >= 400) { console.error("Could not load content for " + this._sourceURL + " : " + "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.CookieParser = function(target) { this._target = target;}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(this._target,keyValue.key,keyValue.value,type) : new WebInspector.Cookie(this._target,"",keyValue.key,type); this._lastCookiePosition = keyValue.position; this._cookies.push(this._lastCookie); }};WebInspector.CookieParser.parseCookie = function(target, header) { return (new WebInspector.CookieParser(target)).parseCookie(header);}WebInspector.CookieParser.parseSetCookie = function(target, header) { return (new WebInspector.CookieParser(target)).parseSetCookie(header);}WebInspector.Cookie = function(target, name, value, type) { this._target = target; 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; }, firstPartyOnly: function() { return "first-party-only" 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) { this._target.networkAgent().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) { var allCookies = []; function mycallback(target, error, cookies) { if (error) { console.error(error); return; } for (var i = 0; i < cookies.length; ++i) allCookies.push(WebInspector.Cookies._parseProtocolCookie(target, cookies[i])); } var barrier = new CallbackBarrier(); for (var target of WebInspector.targetManager.targets(WebInspector.Target.Type.Page)) target.networkAgent().getCookies(barrier.createCallback(mycallback.bind(null , target))); barrier.callWhenDone(callback.bind(null , allCookies));}WebInspector.Cookies._parseProtocolCookie = function(target, protocolCookie) { var cookie = new WebInspector.Cookie(target,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"); if (protocolCookie["firstPartyOnly"]) cookie.addAttribute("first-party-only"); 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.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._fixLineAndColumnNumbers(); } this._calculateTimes(profile);}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); }, _fixLineAndColumnNumbers: function() { var nodeListsToTraverse = [this.profileHead.children]; while (nodeListsToTraverse.length) { var nodeList = nodeListsToTraverse.pop(); for (var i = 0; i < nodeList.length; ++i) { var node = nodeList[i]; --node.lineNumber; --node.columnNumber; if (node.children) nodeListsToTraverse.push(node.children); } } }, _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 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.moduleSetting("highResolutionCpuProfiling").addChangeListener(this._configureCpuProfilerSamplingInterval, this);}WebInspector.CPUProfilerModel.EventTypes = { ProfileStarted: "ProfileStarted", ProfileStopped: "ProfileStopped", ConsoleProfileStarted: "ConsoleProfileStarted", ConsoleProfileFinished: "ConsoleProfileFinished"};WebInspector.CPUProfilerModel.prototype = { _configureCpuProfilerSamplingInterval: function() { var intervalUs = WebInspector.moduleSetting("highResolutionCpuProfiling").get() ? 100 : 1000; this.target().profilerAgent().setSamplingInterval(intervalUs); }, consoleProfileFinished: function(id, scriptLocation, cpuProfile, title) { self.runtime.loadModulePromise("profiler").then(dispatchEvent.bind(this)); function dispatchEvent() { var debuggerModel = (WebInspector.DebuggerModel.fromTarget(this.target())); var debuggerLocation = WebInspector.DebuggerModel.Location.fromPayload(debuggerModel, scriptLocation); this.dispatchEventToListeners(WebInspector.CPUProfilerModel.EventTypes.ConsoleProfileFinished, { protocolId: id, scriptLocation: debuggerLocation, cpuProfile: cpuProfile, title: title }); } }, consoleProfileStarted: function(id, scriptLocation, title) { self.runtime.loadModulePromise("profiler").then(dispatchEvent.bind(this)); function dispatchEvent() { var debuggerModel = (WebInspector.DebuggerModel.fromTarget(this.target())); var debuggerLocation = WebInspector.DebuggerModel.Location.fromPayload(debuggerModel, 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() { function extractProfile(error, profile) { return !error && profile ? profile : null ; } this._isRecording = false; this.dispatchEventToListeners(WebInspector.CPUProfilerModel.EventTypes.ProfileStopped); return this.target().profilerAgent().stop(extractProfile); }, dispose: function() { WebInspector.moduleSetting("highResolutionCpuProfiling").removeChangeListener(this._configureCpuProfilerSamplingInterval, this); }, __proto__: WebInspector.SDKModel.prototype};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; if (!CSS.supports(propertyName, "initial")) continue;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.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.isBezierAwareProperty = function(propertyName) { return !!WebInspector.CSSMetadata._bezierAwareProperties[propertyName.toLowerCase()];}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", "-webkit-user-select", "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._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._bezierAwareProperties = ["animation", "animation-timing-function", "transition", "transition-timing-function", "-webkit-animation", "-webkit-animation-timing-function", "-webkit-transition", "-webkit-transition-timing-function"].keySet();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"] }, "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"] }, "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", "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"] }, "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"] }, "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", "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"] }, "perspective": { values: ["none"] }, "perspective-origin": { values: ["left", "center", "right", "top", "bottom"] }, "transform-origin": { values: ["left", "center", "right", "top", "bottom"] }, "transform-style": { values: ["flat", "preserve-3d"] }, "transition-timing-function": { values: ["ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "steps", "cubic-bezier"] }, "animation-timing-function": { values: ["ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end", "steps", "cubic-bezier"] }, "animation-direction": { values: ["normal", "reverse", "alternate", "alternate-reverse"] }, "animation-play-state": { values: ["running", "paused"] }, "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-filter": { values: ["url", "blur", "brightness", "contrast", "drop-shadow", "grayscale", "hue-rotate", "invert", "opacity", "saturate", "sepia"] }, "-webkit-line-break": { values: ["auto", "loose", "normal", "strict"] }, "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"] }}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("currentColor"); for (var color in WebInspector.Color.Nicknames) acceptedKeywords.push(color); } 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 = { "align-content": 57, "align-items": 129, "align-self": 55, "animation": 175, "animation-delay": 114, "animation-direction": 113, "animation-duration": 137, "animation-fill-mode": 132, "animation-iteration-count": 124, "animation-name": 139, "animation-play-state": 104, "animation-timing-function": 141, "backface-visibility": 123, "background": 249, "background-attachment": 119, "background-clip": 165, "background-color": 259, "background-image": 246, "background-origin": 107, "background-position": 237, "background-position-x": 108, "background-position-y": 93, "background-repeat": 234, "background-size": 203, "border": 263, "border-bottom": 233, "border-bottom-color": 190, "border-bottom-left-radius": 186, "border-bottom-right-radius": 185, "border-bottom-style": 150, "border-bottom-width": 179, "border-collapse": 209, "border-color": 226, "border-image": 89, "border-image-outset": 50, "border-image-repeat": 49, "border-image-slice": 58, "border-image-source": 32, "border-image-width": 52, "border-left": 221, "border-left-color": 174, "border-left-style": 142, "border-left-width": 172, "border-radius": 224, "border-right": 223, "border-right-color": 182, "border-right-style": 130, "border-right-width": 178, "border-spacing": 198, "border-style": 206, "border-top": 231, "border-top-color": 192, "border-top-left-radius": 187, "border-top-right-radius": 189, "border-top-style": 152, "border-top-width": 180, "border-width": 214, "bottom": 227, "box-shadow": 213, "box-sizing": 216, "caption-side": 96, "clear": 229, "clip": 173, "clip-rule": 5, "color": 256, "content": 219, "counter-increment": 111, "counter-reset": 110, "cursor": 250, "direction": 176, "display": 262, "empty-cells": 99, "fill": 140, "fill-opacity": 82, "fill-rule": 22, "filter": 160, "flex": 133, "flex-basis": 66, "flex-direction": 85, "flex-flow": 94, "flex-grow": 112, "flex-shrink": 61, "flex-wrap": 68, "float": 252, "font": 211, "font-family": 254, "font-kerning": 18, "font-size": 264, "font-stretch": 77, "font-style": 220, "font-variant": 161, "font-weight": 257, "height": 266, "image-rendering": 90, "justify-content": 127, "left": 248, "letter-spacing": 188, "line-height": 244, "list-style": 215, "list-style-image": 145, "list-style-position": 149, "list-style-type": 199, "margin": 267, "margin-bottom": 241, "margin-left": 243, "margin-right": 238, "margin-top": 253, "mask": 20, "max-height": 205, "max-width": 225, "min-height": 217, "min-width": 218, "object-fit": 33, "opacity": 251, "order": 117, "orphans": 146, "outline": 222, "outline-color": 153, "outline-offset": 147, "outline-style": 151, "outline-width": 148, "overflow": 255, "overflow-wrap": 105, "overflow-x": 184, "overflow-y": 196, "padding": 265, "padding-bottom": 230, "padding-left": 235, "padding-right": 232, "padding-top": 240, "page": 8, "page-break-after": 120, "page-break-before": 69, "page-break-inside": 121, "perspective": 92, "perspective-origin": 103, "pointer-events": 183, "position": 261, "quotes": 158, "resize": 168, "right": 245, "shape-rendering": 38, "size": 64, "speak": 118, "src": 170, "stop-color": 42, "stop-opacity": 31, "stroke": 98, "stroke-dasharray": 36, "stroke-dashoffset": 3, "stroke-linecap": 30, "stroke-linejoin": 21, "stroke-miterlimit": 12, "stroke-opacity": 34, "stroke-width": 87, "table-layout": 171, "tab-size": 46, "text-align": 260, "text-anchor": 35, "text-decoration": 247, "text-indent": 207, "text-overflow": 204, "text-rendering": 155, "text-shadow": 208, "text-transform": 202, "top": 258, "touch-action": 80, "transform": 181, "transform-origin": 162, "transform-style": 86, "transition": 193, "transition-delay": 134, "transition-duration": 135, "transition-property": 131, "transition-timing-function": 122, "unicode-bidi": 156, "unicode-range": 136, "vertical-align": 236, "visibility": 242, "-webkit-appearance": 191, "-webkit-backface-visibility": 154, "-webkit-background-clip": 164, "-webkit-background-origin": 40, "-webkit-background-size": 163, "-webkit-border-end": 9, "-webkit-border-horizontal-spacing": 81, "-webkit-border-image": 75, "-webkit-border-radius": 212, "-webkit-border-start": 10, "-webkit-border-start-color": 16, "-webkit-border-start-width": 13, "-webkit-border-vertical-spacing": 43, "-webkit-box-align": 101, "-webkit-box-direction": 51, "-webkit-box-flex": 128, "-webkit-box-lines": 2, "-webkit-box-ordinal-group": 91, "-webkit-box-orient": 144, "-webkit-box-pack": 106, "-webkit-box-reflect": 39, "-webkit-box-shadow": 210, "-webkit-column-break-inside": 60, "-webkit-column-count": 84, "-webkit-column-gap": 76, "-webkit-column-rule": 25, "-webkit-column-rule-color": 23, "-webkit-columns": 44, "-webkit-column-span": 29, "-webkit-column-width": 47, "-webkit-filter": 159, "-webkit-font-feature-settings": 59, "-webkit-font-smoothing": 177, "-webkit-highlight": 1, "-webkit-line-break": 45, "-webkit-line-clamp": 126, "-webkit-margin-after": 67, "-webkit-margin-before": 70, "-webkit-margin-collapse": 14, "-webkit-margin-end": 65, "-webkit-margin-start": 100, "-webkit-margin-top-collapse": 78, "-webkit-mask": 19, "-webkit-mask-box-image": 72, "-webkit-mask-image": 88, "-webkit-mask-position": 54, "-webkit-mask-repeat": 63, "-webkit-mask-size": 79, "-webkit-padding-after": 15, "-webkit-padding-before": 28, "-webkit-padding-end": 48, "-webkit-padding-start": 73, "-webkit-print-color-adjust": 83, "-webkit-rtl-ordering": 7, "-webkit-tap-highlight-color": 169, "-webkit-text-emphasis-color": 11, "-webkit-text-fill-color": 71, "-webkit-text-security": 17, "-webkit-text-stroke": 56, "-webkit-text-stroke-color": 37, "-webkit-text-stroke-width": 53, "-webkit-user-drag": 95, "-webkit-user-modify": 62, "-webkit-user-select": 194, "-webkit-writing-mode": 4, "white-space": 228, "widows": 115, "width": 268, "will-change": 74, "word-break": 166, "word-spacing": 157, "word-wrap": 197, "writing-mode": 41, "z-index": 239, "zoom": 200};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.CSSParser = function() { this._worker = new WorkerRuntime.Worker("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.CSSStyleModel = function(target) { WebInspector.SDKModel.call(this, WebInspector.CSSStyleModel, target); this._domModel = WebInspector.DOMModel.fromTarget(target); this._agent = target.cssAgent(); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.SuspendStateChanged, this._suspendStateChanged, this); this._styleLoader = new WebInspector.CSSStyleModel.ComputedStyleLoader(this); target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this); target.registerCSSDispatcher(new WebInspector.CSSDispatcher(this)); this._agent.enable().then(this._wasEnabled.bind(this)); this._styleSheetIdToHeader = new Map(); this._styleSheetIdsForURL = new Map();}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 = { MediaQueryResultChanged: "MediaQueryResultChanged", ModelWasEnabled: "ModelWasEnabled", PseudoStateForced: "PseudoStateForced", StyleSheetAdded: "StyleSheetAdded", StyleSheetChanged: "StyleSheetChanged", StyleSheetRemoved: "StyleSheetRemoved"}WebInspector.CSSStyleModel.MediaTypes = ["all", "braille", "embossed", "handheld", "print", "projection", "screen", "speech", "tty", "tv"];WebInspector.CSSStyleModel.prototype = { mediaQueriesPromise: function() { function parsePayload(error, payload) { return !error && payload ? WebInspector.CSSMedia.parseMediaArrayPayload(this, payload) : []; } return this._agent.getMediaQueries(parsePayload.bind(this)); }, isEnabled: function() { return this._isEnabled; }, _wasEnabled: function(error) { if (error) { console.error("Failed to enabled CSS agent: " + error); return; } this._isEnabled = true; this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.ModelWasEnabled); }, matchedStylesPromise: function(nodeId, excludePseudo, excludeInherited) { function callback(error, matchedPayload, pseudoPayload, inheritedPayload) { if (error) return null ; var matchedRules = WebInspector.CSSStyleModel.parseRuleMatchArrayPayload(this, matchedPayload); var pseudoElements = []; if (pseudoPayload) { for (var i = 0; i < pseudoPayload.length; ++i) { var entryPayload = pseudoPayload[i]; pseudoElements.push(new WebInspector.CSSStyleModel.PseudoElementMatches(entryPayload.pseudoId,WebInspector.CSSStyleModel.parseRuleMatchArrayPayload(this, entryPayload.matches))); } } var inherited = []; if (inheritedPayload) { for (var i = 0; i < inheritedPayload.length; ++i) { var entryPayload = inheritedPayload[i]; var inlineStyle = entryPayload.inlineStyle ? WebInspector.CSSStyleDeclaration.parsePayload(this, entryPayload.inlineStyle) : null ; var matchedCSSRules = entryPayload.matchedCSSRules ? WebInspector.CSSStyleModel.parseRuleMatchArrayPayload(this, entryPayload.matchedCSSRules) : null ; inherited.push(new WebInspector.CSSStyleModel.InheritedMatches(inlineStyle,matchedCSSRules)); } } return new WebInspector.CSSStyleModel.MatchedStyleResult(matchedRules,inherited,pseudoElements); } return this._agent.getMatchedStylesForNode(nodeId, excludePseudo, excludeInherited, callback.bind(this)); }, computedStylePromise: function(nodeId) { return this._styleLoader.computedStylePromise(nodeId); }, platformFontsPromise: function(nodeId) { function platformFontsCallback(error, fonts) { return !error && fonts ? fonts : null ; } return this._agent.getPlatformFontsForNode(nodeId, platformFontsCallback); }, allStyleSheets: function() { var values = this._styleSheetIdToHeader.valuesArray(); 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; }, inlineStylesPromise: function(nodeId) { function callback(error, inlinePayload, attributesStylePayload) { if (error || !inlinePayload) return null ; var inlineStyle = inlinePayload ? WebInspector.CSSStyleDeclaration.parsePayload(this, inlinePayload) : null ; var attributesStyle = attributesStylePayload ? WebInspector.CSSStyleDeclaration.parsePayload(this, attributesStylePayload) : null ; return new WebInspector.CSSStyleModel.InlineStyleResult(inlineStyle,attributesStyle); } return this._agent.getInlineStylesForNode(nodeId, callback.bind(this)); }, 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); this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.PseudoStateForced, { node: node, pseudoClass: pseudoClass, enable: enable }); return true; }, setRuleSelector: function(rule, nodeId, newSelector, userCallback) { function callback(error, rulePayload) { if (error || !rulePayload) return null ; this._domModel.markUndoableState(); return rulePayload; } if (!rule.styleSheetId) throw "No rule stylesheet id"; WebInspector.userMetrics.StyleRuleEdited.record(); this._agent.setRuleSelector(rule.styleSheetId, rule.selectorRange, newSelector, callback.bind(this)).then(this._computeMatchingSelectors.bind(this, nodeId)).catchException(null ).then(userCallback); }, setMediaText: function(media, newMediaText, userCallback) { function parsePayload(error, mediaPayload) { if (!mediaPayload) return null ; this._domModel.markUndoableState(); return WebInspector.CSSMedia.parsePayload(this, mediaPayload); } console.assert(!!media.parentStyleSheetId); WebInspector.userMetrics.StyleRuleEdited.record(); this._agent.setMediaText(media.parentStyleSheetId, media.range, newMediaText, parsePayload.bind(this)).catchException(null ).then(userCallback); }, _computeMatchingSelectors: function(nodeId, rulePayload) { var ownerDocumentId = this._ownerDocumentId(nodeId); if (!ownerDocumentId || !rulePayload) return Promise.resolve((null )); 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); } return new Promise(promiseConstructor); function promiseConstructor(resolve) { allSelectorsBarrier.callWhenDone(function() { rule.matchingSelectors = matchingSelectors; resolve(rule); } ); } function selectorQueried(index, nodeId, matchingSelectors, matchingNodeIds) { if (!matchingNodeIds) return; if (matchingNodeIds.indexOf(nodeId) !== -1) matchingSelectors.push(index); } }, addRule: function(styleSheetId, node, ruleText, ruleLocation, userCallback) { this._agent.addRule(styleSheetId, ruleText, ruleLocation, parsePayload.bind(this)).then(this._computeMatchingSelectors.bind(this, node.id)).catchException(null ).then(userCallback); function parsePayload(error, rulePayload) { if (error || !rulePayload) return null ; this._domModel.markUndoableState(); return rulePayload; } }, requestViaInspectorStylesheet: function(node, userCallback) { var frameId = node.frameId() || this.target().resourceTreeModel.mainFrame.id; var headers = this._styleSheetIdToHeader.valuesArray(); for (var i = 0; i < headers.length; ++i) { var styleSheetHeader = headers[i]; if (styleSheetHeader.frameId === frameId && styleSheetHeader.isViaInspector()) { userCallback(styleSheetHeader); return; } } function innerCallback(error, styleSheetId) { return !error && styleSheetId ? this._styleSheetIdToHeader.get(styleSheetId) || null : null ; } this._agent.createStyleSheet(frameId, innerCallback.bind(this)).catchException(null ).then(userCallback) }, mediaQueryResultChanged: function() { this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.MediaQueryResultChanged); }, styleSheetHeaderForId: function(id) { return this._styleSheetIdToHeader.get(id) || null ; }, styleSheetHeaders: function() { return this._styleSheetIdToHeader.valuesArray(); }, _ownerDocumentId: function(nodeId) { var node = this._domModel.nodeForId(nodeId); if (!node) return null ; return node.ownerDocument ? node.ownerDocument.id : null ; }, _fireStyleSheetChanged: function(styleSheetId) { if (!styleSheetId || !this.hasEventListeners(WebInspector.CSSStyleModel.Events.StyleSheetChanged)) return; this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.StyleSheetChanged, { styleSheetId: styleSheetId }); }, _styleSheetAdded: function(header) { console.assert(!this._styleSheetIdToHeader.get(header.styleSheetId)); var styleSheetHeader = new WebInspector.CSSStyleSheetHeader(this,header); this._styleSheetIdToHeader.set(header.styleSheetId, styleSheetHeader); var url = styleSheetHeader.resourceURL(); if (!this._styleSheetIdsForURL.get(url)) this._styleSheetIdsForURL.set(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; }, setStyleSheetText: function(styleSheetId, newText, majorChange) { var header = this._styleSheetIdToHeader.get(styleSheetId); console.assert(header); return header._setContentPromise(newText).then(callback.bind(this)); function callback(error) { if (!error && majorChange) this._domModel.markUndoableState(); return error; } }, _mainFrameNavigated: function() { this._resetStyleSheets(); }, _resetStyleSheets: function() { var headers = this._styleSheetIdToHeader.valuesArray(); this._styleSheetIdsForURL.clear(); this._styleSheetIdToHeader.clear(); for (var i = 0; i < headers.length; ++i) this.dispatchEventToListeners(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, headers[i]); }, _suspendStateChanged: function() { if (WebInspector.targetManager.allTargetsSuspended()) { this._agent.disable(); this._isEnabled = false; } else { this._resetStyleSheets(); this._agent.enable().then(this._wasEnabled.bind(this)); } }, __proto__: WebInspector.SDKModel.prototype}WebInspector.CSSLocation = function(cssModel, styleSheetId, url, lineNumber, columnNumber) { WebInspector.SDKObject.call(this, cssModel.target()); this._cssModel = cssModel; this.styleSheetId = styleSheetId; this.url = url; this.lineNumber = lineNumber; this.columnNumber = columnNumber || 0;}WebInspector.CSSLocation.prototype = { cssModel: function() { return this._cssModel; }, __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 ; var shorthandEntries = payload.shorthandEntries; this._shorthandValues = new Map(); this._shorthandIsImportant = new Set(); for (var i = 0; i < shorthandEntries.length; ++i) { this._shorthandValues.set(shorthandEntries[i].name, shorthandEntries[i].value); if (shorthandEntries[i].important) this._shorthandIsImportant.add(shorthandEntries[i].name); } 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.createDummyStyle = function(cssModel) { var dummyPayload = { shorthandEntries: [], cssProperties: [] }; return new WebInspector.CSSStyleDeclaration(cssModel,dummyPayload);}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(); }, cssModel: function() { return this._cssModel; }, 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.get(shorthandProperty) || ""; }, shorthandIsImportant: function(shorthandProperty) { return this._shorthandIsImportant.has(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; }, setText: function(text, majorChange, userCallback) { if (!this.styleSheetId) { userCallback(null ); return; } function parsePayload(error, stylePayload) { if (error || !stylePayload) return null ; if (majorChange) this._cssModel._domModel.markUndoableState(); return WebInspector.CSSStyleDeclaration.parsePayload(this._cssModel, stylePayload); } this._cssModel._agent.setStyleText(this.styleSheetId, this.range.serializeToObject(), text, parsePayload.bind(this)).catchException(null ).then(userCallback) }, insertPropertyAt: function(index, name, value, userCallback) { this.newBlankProperty(index).setText(name + ": " + value + ";", false, true, userCallback); }, 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) { this._sourceStyleSheetEditedWithMedia(styleSheetId, oldRange, newRange, null , null ); }, _sourceStyleSheetEditedWithMedia: function(styleSheetId, oldRange, newRange, oldMedia, newMedia) { 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) { if (oldMedia && newMedia && oldMedia.equal(this.media[i])) { this.media[i] = newMedia; } else { this.media[i].sourceStyleSheetEdited(styleSheetId, oldRange, newRange); } } } this.style.sourceStyleSheetEdited(styleSheetId, oldRange, newRange); }, mediaEdited: function(oldMedia, newMedia) { this._sourceStyleSheetEditedWithMedia((oldMedia.parentStyleSheetId), oldMedia.range, newMedia.range, oldMedia, newMedia); }, _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); }, get isUserAgent() { return this.origin === "user-agent"; }, get isInjected() { return this.origin === "injected"; }, 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) { if (!this.ownerStyle) throw "No ownerStyle for property"; if (!this.ownerStyle.styleSheetId) throw "No owner style id"; if (!this.range || !this.ownerStyle.range) throw "Style not editable"; if (majorChange) WebInspector.userMetrics.StyleRuleEdited.record(); if (overwrite && propertyText === this.propertyText) { if (majorChange) this.ownerStyle._cssModel._domModel.markUndoableState(); if (userCallback) userCallback(this.ownerStyle); return; } var range = this.range.relativeTo(this.ownerStyle.range.startLine, this.ownerStyle.range.startColumn); var indentation = this.ownerStyle.cssText ? this._detectIndentation(this.ownerStyle.cssText) : WebInspector.moduleSetting("textEditorIndent").get(); var endIntentation = this.ownerStyle.cssText ? indentation.substring(0, this.ownerStyle.range.endColumn) : ""; var newStyleText = range.replaceInText(this.ownerStyle.cssText || "", ";" + propertyText); this._formatStyle(newStyleText, indentation, endIntentation, setStyleText.bind(this)); function setStyleText(styleText) { this.ownerStyle.setText(styleText, majorChange, callback); } function callback(style) { if (userCallback) userCallback(style); } function enabledCallback(style) { if (userCallback) userCallback(style); } }, _formatStyle: function(styleText, indentation, endIndentation, callback) { self.runtime.instancePromise(WebInspector.TokenizerFactory).then(processTokens); var result = ""; function processTokens(tokenizerFactory) { var tokenize = tokenizerFactory.createTokenizer("text/css"); tokenize("*{" + styleText + "}", processToken); result = result.slice(0, result.length - 1); callback(result + (indentation ? "\n" + endIndentation : "")); } var lastWasSemicolon = true; var lastWasMeta = false; var insideProperty = false; function processToken(token, tokenType, column, newColumn) { if (newColumn <= 2) return; var isSemicolon = token === ";"; if (isSemicolon && lastWasSemicolon) return; lastWasSemicolon = isSemicolon || (lastWasSemicolon && tokenType && tokenType.includes("css-comment")) || (lastWasSemicolon && !token.trim()); if (!indentation) { result += token; return; } if (!insideProperty && !token.trim()) return; if (tokenType && tokenType.includes("css-comment") && token.includes(":") && token.includes(";")) { result += "\n" + indentation + token; insideProperty = false; return; } if (isSemicolon) insideProperty = false; if (tokenType && (tokenType.includes("css-meta") || (tokenType.includes("css-property") && !lastWasMeta))) { result += "\n" + indentation; insideProperty = true; } result += token; lastWasMeta = tokenType && tokenType.includes("css-meta"); } }, _detectIndentation: function(text) { var lines = text.split("\n"); if (lines.length < 2) return ""; return WebInspector.TextUtils.lineIndent(lines[1]); }, 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.CSSMediaQuery = function(payload) { this._active = payload.active; this._expressions = []; for (var j = 0; j < payload.expressions.length; ++j) this._expressions.push(WebInspector.CSSMediaQueryExpression.parsePayload(payload.expressions[j]));}WebInspector.CSSMediaQuery.parsePayload = function(payload) { return new WebInspector.CSSMediaQuery(payload);}WebInspector.CSSMediaQuery.prototype = { active: function() { return this._active; }, expressions: function() { return this._expressions; }}WebInspector.CSSMediaQueryExpression = function(payload) { this._value = payload.value; this._unit = payload.unit; this._feature = payload.feature; this._valueRange = payload.valueRange ? WebInspector.TextRange.fromObject(payload.valueRange) : null ; 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; }, valueRange: function() { return this._valueRange; }, 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) this.mediaList.push(WebInspector.CSSMediaQuery.parsePayload(payload.mediaList[i])); }}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); }, equal: function(other) { if (!this.parentStyleSheetId || !this.range || !other.range) return false; return this.parentStyleSheetId === other.parentStyleSheetId && this.range.equal(other.range); }, active: function() { if (!this.mediaList) return true; for (var i = 0; i < this.mediaList.length; ++i) { if (this.mediaList[i].active()) return true; } return false; }, 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,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; if (payload.ownerNode) this.ownerNode = new WebInspector.DeferredDOMNode(cssModel.target(),payload.ownerNode);}WebInspector.CSSStyleSheetHeader.prototype = { target: function() { return this._cssModel.target(); }, cssModel: function() { return this._cssModel; }, 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(userCallback) { this._cssModel._agent.getStyleSheetText(this.id, textCallback.bind(this)).catchException("").then(userCallback) function textCallback(error, text) { if (error || text === null ) { WebInspector.console.error("Failed to get text for stylesheet " + this.id + ": " + error) text = ""; } return this._trimSourceURL(text); } }, searchInContent: function(query, caseSensitive, isRegex, callback) { function performSearch(content) { callback(WebInspector.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex)); } this.requestContent(performSearch); }, _setContentPromise: function(newText) { newText = this._trimSourceURL(newText); if (this.hasSourceURL) newText += "\n/*# sourceURL=" + this.sourceURL + " */"; return this._cssModel._agent.setStyleSheetText(this.id, newText, extractProtocolError); function extractProtocolError(error) { return error || null ; } }, setContent: function(newText, callback) { this._setContentPromise(newText).catchException(null ).then(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._nodeIdToPromise = new Map();}WebInspector.CSSStyleModel.ComputedStyleLoader.prototype = { computedStylePromise: function(nodeId) { if (!this._nodeIdToPromise[nodeId]) this._nodeIdToPromise[nodeId] = this._cssModel._agent.getComputedStyleForNode(nodeId, parsePayload.bind(this)).then(cleanUp.bind(this)); return this._nodeIdToPromise[nodeId]; function parsePayload(error, computedPayload) { return !error && computedPayload ? WebInspector.CSSStyleDeclaration.parseComputedStylePayload(this._cssModel, computedPayload) : null ; } function cleanUp(computedStyle) { delete this._nodeIdToPromise[nodeId]; return computedStyle; } }}WebInspector.CSSStyleModel.fromTarget = function(target) { if (!target.isPage()) return null ; return ( target.model(WebInspector.CSSStyleModel)) ;}WebInspector.CSSStyleModel.fromNode = function(node) { return ( WebInspector.CSSStyleModel.fromTarget(node.target())) ;}WebInspector.CSSStyleModel.MatchedStyleResult = function(matchedRules, inherited, pseudoElements) { this.matchedCSSRules = matchedRules; this.inherited = inherited; this.pseudoElements = pseudoElements;}WebInspector.CSSStyleModel.PseudoElementMatches = function(pseudoId, rules) { this.pseudoId = pseudoId; this.rules = rules;}WebInspector.CSSStyleModel.InheritedMatches = function(inlineStyle, matchedRules) { this.inlineStyle = inlineStyle; this.matchedCSSRules = matchedRules;}WebInspector.CSSStyleModel.InlineStyleResult = function(inlineStyle, attributesStyle) { this.inlineStyle = inlineStyle; this.attributesStyle = attributesStyle;};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.distributedNodes) this._setDistributedNodePayloads(payload.distributedNodes); 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 || null ; }, importedDocument: function() { return this._importedDocument || null ; }, nodeType: function() { return this._nodeType; }, nodeName: function() { return this._nodeName; }, pseudoType: function() { return this._pseudoType; }, hasPseudoElements: function() { return this._pseudoElements.size > 0; }, pseudoElements: function() { return this._pseudoElements; }, beforePseudoElement: function() { if (!this._pseudoElements) return null ; return this._pseudoElements.get(WebInspector.DOMNode.PseudoElementNames.Before); }, afterPseudoElement: function() { if (!this._pseudoElements) return null ; return this._pseudoElements.get(WebInspector.DOMNode.PseudoElementNames.After); }, isInsertionPoint: function() { return !this.isXMLNode() && (this._nodeName === "SHADOW" || this._nodeName === "CONTENT"); }, distributedNodes: function() { return this._distributedNodes || []; }, isInShadowTree: function() { return this._isInShadowTree; }, ancestorShadowHost: function() { var ancestorShadowRoot = this.ancestorShadowRoot(); return ancestorShadowRoot ? ancestorShadowRoot.parentNode : null ; }, ancestorShadowRoot: function() { if (!this._isInShadowTree) return null ; var current = this; while (current && !current.isShadowRoot()) current = current.parentNode; return current; }, ancestorUserAgentShadowRoot: function() { var ancestorShadowRoot = this.ancestorShadowRoot(); if (!ancestorShadowRoot) return null ; return ancestorShadowRoot.shadowRootType() === WebInspector.DOMNode.ShadowRootTypes.UserAgent ? ancestorShadowRoot : 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); }, 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()) { this._pseudoElements.delete(node.pseudoType()); } else { var shadowRootIndex = this._shadowRoots.indexOf(node); if (shadowRootIndex !== -1) { this._shadowRoots.splice(shadowRootIndex, 1); } else { console.assert(this._children.indexOf(node) !== -1); 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 = new Map(); 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.set(node.pseudoType(), node); } }, _setDistributedNodePayloads: function(payloads) { this._distributedNodes = []; for (var payload of payloads) this._distributedNodes.push(new WebInspector.DOMNodeShortcut(this._domModel.target(),payload.backendNodeId,payload.nodeType,payload.nodeName)); }, _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, undefined, 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)); } }, resolveToObjectPromise: function(objectGroup) { return new Promise(resolveToObject.bind(this)); function resolveToObject(fulfill, reject) { this.resolveToObject(objectGroup, mycallback); function mycallback(object) { if (object) fulfill(object) else reject(null ); } } }, boxModel: function(callback) { this._agent.getBoxModel(this.id, this._domModel._wrapClientCallback(callback)); }, setAsInspectedNode: function() { var node = this; while (true) { var ancestor = node.ancestorUserAgentShadowRoot(); if (!ancestor) break; ancestor = node.ancestorShadowHost(); if (!ancestor) break node = ancestor; } this._agent.setInspectedNode(node.id); }, __proto__: WebInspector.SDKObject.prototype}WebInspector.DeferredDOMNode = function(target, backendNodeId) { this._domModel = WebInspector.DOMModel.fromTarget(target); this._backendNodeId = backendNodeId;}WebInspector.DeferredDOMNode.prototype = { resolve: function(callback) { if (!this._domModel) { callback(null ); return; } this._domModel.pushNodesByBackendIdsToFrontend(new Set([this._backendNodeId]), onGotNode.bind(this)); function onGotNode(nodeIds) { callback(nodeIds && (nodeIds.get(this._backendNodeId) || null )); } }, backendNodeId: function() { return this._backendNodeId; }, highlight: function() { if (this._domModel) this._domModel.highlightDOMNode(undefined, undefined, this._backendNodeId); }}WebInspector.DOMNodeShortcut = function(target, backendNodeId, nodeType, nodeName) { this.nodeType = nodeType; this.nodeName = nodeName; this.deferredNode = new WebInspector.DeferredDOMNode(target,backendNodeId);}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(); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.SuspendStateChanged, this._suspendStateChanged, this); this._idToDOMNode = {}; this._document = null ; this._attributeLoadNodeIds = {}; target.registerDOMDispatcher(new WebInspector.DOMDispatcher(this)); this._showRulers = false; this._showExtensionLines = false; this._defaultHighlighter = new WebInspector.DefaultDOMNodeHighlighter(this._agent); this._highlighter = this._defaultHighlighter; this._agent.enable();}WebInspector.DOMModel.Events = { AttrModified: "AttrModified", AttrRemoved: "AttrRemoved", CharacterDataModified: "CharacterDataModified", DOMMutated: "DOMMutated", NodeInserted: "NodeInserted", NodeInspected: "NodeInspected", NodeRemoved: "NodeRemoved", DocumentUpdated: "DocumentUpdated", ChildNodeCountUpdated: "ChildNodeCountUpdated", UndoRedoRequested: "UndoRedoRequested", UndoRedoCompleted: "UndoRedoCompleted", DistributedNodesChanged: "DistributedNodesChanged", ModelSuspended: "ModelSuspended", InspectModeWillBeToggled: "InspectModeWillBeToggled"}WebInspector.DOMModel.highlightObjectAsDOMNode = function(object) { var domModel = WebInspector.DOMModel.fromTarget(object.target()); if (domModel) domModel.highlightDOMNode(undefined, undefined, undefined, object.objectId);}WebInspector.DOMModel.instances = function() { var result = []; for (var target of WebInspector.targetManager.targets()) { var domModel = WebInspector.DOMModel.fromTarget(target); if (domModel) result.push(domModel); } return result;}WebInspector.DOMModel.hideDOMNodeHighlight = function() { for (var domModel of WebInspector.DOMModel.instances()) domModel.highlightDOMNode(0);}WebInspector.DOMModel.cancelSearch = function() { for (var domModel of WebInspector.DOMModel.instances()) domModel._cancelSearch();}WebInspector.DOMModel.prototype = { _scheduleMutationEvent: function() { if (!this.hasEventListeners(WebInspector.DOMModel.Events.DOMMutated)) return; this._lastMutationId = (this._lastMutationId || 0) + 1; Promise.resolve().then(callObserve.bind(this, this._lastMutationId)); function callObserve(mutationId) { if (!this.hasEventListeners(WebInspector.DOMModel.Events.DOMMutated) || this._lastMutationId !== mutationId) return; this.dispatchEventToListeners(WebInspector.DOMModel.Events.DOMMutated); } }, 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) { var backendNodeIdsArray = Array.from(backendNodeIds.values()); function mycallback(nodeIds) { if (!nodeIds) { callback(null ); return; } var map = new Map(); for (var i = 0; i < nodeIds.length; ++i) { if (nodeIds[i]) map.set(backendNodeIdsArray[i], this.nodeForId(nodeIds[i])); } callback(map); } this._dispatchWhenDocumentAvailable(this._agent.pushNodesByBackendIdsToFrontend.bind(this._agent, backendNodeIdsArray), mycallback.bind(this)); }, _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 }); this._scheduleMutationEvent(); }, _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 }); this._scheduleMutationEvent(); }, _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" }); this._scheduleMutationEvent(); } } } 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); this._scheduleMutationEvent(); }, 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); this._scheduleMutationEvent(); }, _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); this._scheduleMutationEvent(); }, _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 }); this._scheduleMutationEvent(); }, _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.unshift(node); this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInserted, node); this._scheduleMutationEvent(); }, _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 }); this._scheduleMutationEvent(); }, _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.get(node.pseudoType())); parent._pseudoElements.set(node.pseudoType(), node); this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInserted, node); this._scheduleMutationEvent(); }, _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 }); this._scheduleMutationEvent(); }, _distributedNodesUpdated: function(insertionPointId, distributedNodes) { var insertionPoint = this._idToDOMNode[insertionPointId]; if (!insertionPoint) return; insertionPoint._setDistributedNodePayloads(distributedNodes); this.dispatchEventToListeners(WebInspector.DOMModel.Events.DistributedNodesChanged, insertionPoint); this._scheduleMutationEvent(); }, _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 value of pseudoElements.values()) this._unbind(value); if (node._templateContent) this._unbind(node._templateContent); }, _inspectNodeRequested: function(backendNodeId) { var deferredNode = new WebInspector.DeferredDOMNode(this.target(),backendNodeId); this.dispatchEventToListeners(WebInspector.DOMModel.Events.NodeInspected, deferredNode); }, performSearch: function(query, includeUserAgentShadowDOM, searchCallback) { WebInspector.DOMModel.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, backendNodeId, objectId) { this.highlightDOMNodeWithConfig(nodeId, { mode: mode }, backendNodeId, objectId); }, highlightDOMNodeWithConfig: function(nodeId, config, backendNodeId, 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, backendNodeId, objectId); }, highlightDOMNodeForTwoSeconds: function(nodeId) { this.highlightDOMNode(nodeId); if (!Runtime.experiments.isEnabled("layoutEditor")) this._hideDOMNodeHighlightTimeout = setTimeout(WebInspector.DOMModel.hideDOMNodeHighlight.bind(WebInspector.DOMModel), 2000); }, highlightFrame: function(frameId) { this._highlighter.highlightFrame(frameId); }, setInspectModeEnabled: function(enabled, inspectUAShadowDOM, callback) { function onDocumentAvailable() { this.dispatchEventToListeners(WebInspector.DOMModel.Events.InspectModeWillBeToggled, enabled); this._highlighter.setInspectModeEnabled(enabled, inspectUAShadowDOM, this._buildHighlightConfig(), callback); } this.requestDocument(onDocumentAvailable.bind(this)); }, setHighlightSettings: function(showRulers, showExtensionLines) { this._showRulers = showRulers; this._showExtensionLines = showExtensionLines; }, _buildHighlightConfig: function(mode) { mode = mode || "all"; var highlightConfig = { showInfo: mode === "all", showRulers: this._showRulers, showExtensionLines: this._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(); highlightConfig.showLayoutEditor = Runtime.experiments.isEnabled("layoutEditor"); } return highlightConfig; }, _markRevision: function(node, callback) { function wrapperFunction(error) { if (!error) this.markUndoableState(); if (callback) callback.apply(this, arguments); } return wrapperFunction.bind(this); }, 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)); } }, pushObjectAsNodeToFrontend: function(object, callback) { if (object.isNode()) this.pushNodeToFrontend(object.objectId, callback); else callback(null ); }, _suspendStateChanged: function() { if (WebInspector.targetManager.allTargetsSuspended()) { this._agent.disable(); } else { this._agent.enable(); this._setDocument(null ); } }, __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); }, distributedNodesUpdated: function(insertionPointId, distributedNodes) { this._domModel._distributedNodesUpdated(insertionPointId, distributedNodes); }}WebInspector.DOMNodeHighlighter = function() {}WebInspector.DOMNodeHighlighter.prototype = { highlightDOMNode: function(node, config, backendNodeId, objectId) {}, setInspectModeEnabled: function(enabled, inspectUAShadowDOM, config, callback) {}, highlightFrame: function(frameId) {}}WebInspector.DefaultDOMNodeHighlighter = function(agent) { this._agent = agent;}WebInspector.DefaultDOMNodeHighlighter.prototype = { highlightDOMNode: function(node, config, backendNodeId, objectId) { if (objectId || node || backendNodeId) this._agent.highlightNode(config, (objectId || backendNodeId) ? undefined : node.id, backendNodeId, objectId); else this._agent.hideHighlight(); }, setInspectModeEnabled: function(enabled, inspectUAShadowDOM, config, callback) { this._agent.setInspectModeEnabled(enabled, inspectUAShadowDOM, config, callback); }, highlightFrame: function(frameId) { this._agent.highlightFrame(frameId, WebInspector.Color.PageHighlight.Content.toProtocolRGBA(), WebInspector.Color.PageHighlight.ContentOutline.toProtocolRGBA()); }}WebInspector.DOMModel.fromTarget = function(target) { return ( target.model(WebInspector.DOMModel)) ;};WebInspector.DebuggerModel = function(target) { WebInspector.SDKModel.call(this, WebInspector.DebuggerModel, target); target.registerDebuggerDispatcher(new WebInspector.DebuggerDispatcher(this)); this._agent = target.debuggerAgent(); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.SuspendStateChanged, this._suspendStateChanged, this); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.TargetDisposed, this._targetDisposed, this); this._debuggerPausedDetails = null ; this._scripts = {}; this._scriptsBySourceURL = new Map(); this._breakpointResolvedEventTarget = new WebInspector.Object(); this._isPausing = false; WebInspector.moduleSetting("pauseOnExceptionEnabled").addChangeListener(this._pauseOnExceptionStateChanged, this); WebInspector.moduleSetting("pauseOnCaughtException").addChangeListener(this._pauseOnExceptionStateChanged, this); WebInspector.moduleSetting("enableAsyncStackTraces").addChangeListener(this.asyncStackTracesStateChanged, this); WebInspector.moduleSetting("skipStackFramesPattern").addChangeListener(this._applySkipStackFrameSettings, this); WebInspector.moduleSetting("skipContentScripts").addChangeListener(this._applySkipStackFrameSettings, this); this.enableDebugger(); this._applySkipStackFrameSettings();}WebInspector.DebuggerModel.FunctionDetails;WebInspector.DebuggerModel.GeneratorObjectDetails;WebInspector.DebuggerModel.PauseOnExceptionsState = { DontPauseOnExceptions: "none", PauseOnAllExceptions: "all", PauseOnUncaughtExceptions: "uncaught"};WebInspector.DebuggerModel.Events = { AsyncOperationStarted: "AsyncOperationStarted", AsyncOperationCompleted: "AsyncOperationCompleted", DebuggerWasEnabled: "DebuggerWasEnabled", DebuggerWasDisabled: "DebuggerWasDisabled", BeforeDebuggerPaused: "BeforeDebuggerPaused", DebuggerPaused: "DebuggerPaused", DebuggerResumed: "DebuggerResumed", ParsedScriptSource: "ParsedScriptSource", FailedToParseScriptSource: "FailedToParseScriptSource", GlobalObjectCleared: "GlobalObjectCleared", CallFrameSelected: "CallFrameSelected", ConsoleCommandEvaluatedInSelectedCallFrame: "ConsoleCommandEvaluatedInSelectedCallFrame", PromiseUpdated: "PromiseUpdated",}WebInspector.DebuggerModel.BreakReason = { AsyncOperation: "AsyncOperation", DOM: "DOM", EventListener: "EventListener", XHR: "XHR", Exception: "exception", PromiseRejection: "promiseRejection", Assert: "assert", CSPViolation: "CSPViolation", DebugCommand: "debugCommand", Other: "other"}WebInspector.DebuggerModel.prototype = { debuggerEnabled: function() { return !!this._debuggerEnabled; }, enableDebugger: function() { if (this._debuggerEnabled) return; this._agent.enable(); this._debuggerEnabled = true; if (this._hasStaleState) { this._globalObjectCleared(); this._hasStaleState = false; } this._pauseOnExceptionStateChanged(); this.asyncStackTracesStateChanged(); this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasEnabled); }, disableDebugger: function() { if (!this._debuggerEnabled) return; this._hasStaleState = true; this._agent.disable(); this._debuggerEnabled = false; this._isPausing = false; this.asyncStackTracesStateChanged(); this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerWasDisabled); }, _skipAllPauses: function(skip) { if (this._skipAllPausesTimeout) { clearTimeout(this._skipAllPausesTimeout); delete this._skipAllPausesTimeout; } this._agent.setSkipAllPauses(skip); }, skipAllPausesUntilReloadOrTimeout: function(timeout) { if (this._skipAllPausesTimeout) clearTimeout(this._skipAllPausesTimeout); this._agent.setSkipAllPauses(true); this._skipAllPausesTimeout = setTimeout(this._skipAllPauses.bind(this, false), timeout); }, _pauseOnExceptionStateChanged: function() { var state; if (!WebInspector.moduleSetting("pauseOnExceptionEnabled").get()) { state = WebInspector.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions; } else if (WebInspector.moduleSetting("pauseOnCaughtException").get()) { state = WebInspector.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions; } else { state = WebInspector.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions; } this._agent.setPauseOnExceptions(state); }, asyncStackTracesStateChanged: function() { const maxAsyncStackChainDepth = 4; var enabled = WebInspector.moduleSetting("enableAsyncStackTraces").get() && !WebInspector.targetManager.allTargetsSuspended(); this._agent.setAsyncCallStackDepth(enabled ? maxAsyncStackChainDepth : 0); }, stepInto: function() { this._agent.stepInto(); }, stepIntoAsync: function() { this._agent.stepIntoAsync(); }, stepOver: function() { this._agent.stepOver(); }, stepOut: function() { this._agent.stepOut(); }, resume: function() { this._agent.resume(); this._isPausing = false; }, pause: function() { this._isPausing = true; this._skipAllPauses(false); this._agent.pause(); }, setBreakpointsActive: function(active) { this._agent.setBreakpointsActive(active); }, 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, this)) : []; callback(error ? null : breakpointId, rawLocations); } } this._agent.setBreakpointByUrl(lineNumber, url, undefined, columnNumber, condition, didSetBreakpoint.bind(this)); }, setBreakpointBySourceId: function(rawLocation, condition, callback) { var target = this.target(); function didSetBreakpoint(error, breakpointId, actualLocation) { if (callback) { var location = WebInspector.DebuggerModel.Location.fromPayload(this, actualLocation); callback(error ? null : breakpointId, [location]); } } this._agent.setBreakpoint(rawLocation.payload(), condition, didSetBreakpoint.bind(this)); }, removeBreakpoint: function(breakpointId, callback) { this._agent.removeBreakpoint(breakpointId, innerCallback); function innerCallback(error) { if (error) console.error("Failed to remove breakpoint: " + error); if (callback) callback(); } }, getCollectionEntries: function(objectId, callback) { this._agent.getCollectionEntries(objectId, innerCallback); function innerCallback(error, response) { if (error) { console.error(error); callback(null ); return; } callback(response); } }, enablePromiseTracker: function(captureStacks) { this._agent.enablePromiseTracker(captureStacks); }, disablePromiseTracker: function() { this._agent.disablePromiseTracker(); }, getPromiseById: function(promiseId, objectGroup, callback) { this._agent.getPromiseById(promiseId, objectGroup, innerCallback); function innerCallback(error, promise) { if (error) { console.error(error); callback(null ); return; } callback(promise); } }, flushAsyncOperationEvents: function() { this._agent.flushAsyncOperationEvents(); }, setAsyncOperationBreakpoint: function(operationId) { this._agent.setAsyncOperationBreakpoint(operationId); }, removeAsyncOperationBreakpoint: function(operationId) { this._agent.removeAsyncOperationBreakpoint(operationId); }, _breakpointResolved: function(breakpointId, location) { this._breakpointResolvedEventTarget.dispatchEventToListeners(breakpointId, WebInspector.DebuggerModel.Location.fromPayload(this, location)); }, _globalObjectCleared: function() { this._setDebuggerPausedDetails(null ); this._reset(); this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.GlobalObjectCleared); }, _promiseUpdated: function(eventType, promise) { this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.PromiseUpdated, { eventType: eventType, promise: promise }); }, _asyncOperationStarted: function(operation) { this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.AsyncOperationStarted, operation); }, _asyncOperationCompleted: function(operationId) { this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.AsyncOperationCompleted, operationId); }, _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) { if (Runtime.experiments.isEnabled("emptySourceMapAutoStepping")) { if (this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.BeforeDebuggerPaused, this._debuggerPausedDetails)) { return false; } } this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPausedDetails); } if (debuggerPausedDetails) this.setSelectedCallFrame(debuggerPausedDetails.callFrames[0]); else this.setSelectedCallFrame(null ); return true; }, _pausedScript: function(callFrames, reason, auxData, breakpointIds, asyncStackTrace) { var pausedDetails = new WebInspector.DebuggerPausedDetails(this,callFrames,reason,auxData,breakpointIds,asyncStackTrace); if (this._setDebuggerPausedDetails(pausedDetails)) { if (this._pendingLiveEditCallback) { var callback = this._pendingLiveEditCallback; delete this._pendingLiveEditCallback; callback(); } } else { this._agent.stepInto(); } }, _resumedScript: function() { this._setDebuggerPausedDetails(null ); this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.DebuggerResumed); }, _parsedScriptSource: function(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, isInternalScript, sourceMapURL, hasSourceURL, hasSyntaxError) { var script = new WebInspector.Script(this,scriptId,sourceURL,startLine,startColumn,endLine,endColumn,isContentScript,isInternalScript,sourceMapURL,hasSourceURL); this._registerScript(script); if (!hasSyntaxError) this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.ParsedScriptSource, script); else this.dispatchEventToListeners(WebInspector.DebuggerModel.Events.FailedToParseScriptSource, script); return 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.set(script.sourceURL, scripts); } scripts.push(script); }, createRawLocation: function(script, lineNumber, columnNumber) { if (script.sourceURL) return this.createRawLocationByURL(script.sourceURL, lineNumber, columnNumber); return new WebInspector.DebuggerModel.Location(this,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,closestScript.scriptId,lineNumber,columnNumber) : null ; }, createRawLocationByScriptId: function(scriptId, lineNumber, columnNumber) { var script = this.scriptForId(scriptId); return script ? this.createRawLocation(script, lineNumber, columnNumber) : null ; }, 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)); }, 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.moduleSetting("skipStackFramesPattern").get(), WebInspector.moduleSetting("skipContentScripts").get()); }, functionDetails: function(remoteObject, callback) { this._agent.getFunctionDetails(remoteObject.objectId, didGetDetails.bind(this)); function didGetDetails(error, response) { if (error) { callback(null ); return; } var location = response.location; var script = this.scriptForId(location.scriptId); var rawLocation = script ? this.createRawLocation(script, location.lineNumber, location.columnNumber || 0) : null ; var sourceURL = script ? script.contentURL() : null ; callback({ location: rawLocation, sourceURL: sourceURL, functionName: response.functionName, scopeChain: response.scopeChain || null }); } }, compileScript: function(expression, sourceURL, persistScript, executionContextId, callback) { this._agent.compileScript(expression, sourceURL, persistScript, executionContextId, innerCallback); function innerCallback(error, scriptId, exceptionDetails) { if (error) { console.error(error); return; } if (callback) callback(scriptId, exceptionDetails); } }, runScript: function(scriptId, executionContextId, objectGroup, doNotPauseOnExceptionsAndMuteConsole, callback) { this._agent.runScript(scriptId, executionContextId, objectGroup, doNotPauseOnExceptionsAndMuteConsole, innerCallback); function innerCallback(error, result, exceptionDetails) { if (error) { console.error(error); return; } if (callback) callback(result, exceptionDetails); } }, setVariableValue: function(scopeNumber, variableName, newValue, callFrameId, functionObjectId, callback) { this._agent.setVariableValue(scopeNumber, variableName, newValue, callFrameId, functionObjectId, innerCallback); function innerCallback(error) { if (error) { console.error(error); if (callback) callback(error); return; } if (callback) callback(); } }, generatorObjectDetails: function(remoteObject, callback) { this._agent.getGeneratorObjectDetails(remoteObject.objectId, didGetDetails.bind(this)); function didGetDetails(error, response) { if (error) { console.error(error); callback(null ); return; } var location = response.location; var script = location && this.scriptForId(location.scriptId); var rawLocation = script ? this.createRawLocation(script, location.lineNumber, location.columnNumber || 0) : null ; var sourceURL = script ? script.contentURL() : null ; callback({ location: rawLocation, sourceURL: sourceURL, functionName: response.functionName, status: response.status }); } }, addBreakpointListener: function(breakpointId, listener, thisObject) { this._breakpointResolvedEventTarget.addEventListener(breakpointId, listener, thisObject) }, removeBreakpointListener: function(breakpointId, listener, thisObject) { this._breakpointResolvedEventTarget.removeEventListener(breakpointId, listener, thisObject); }, _targetDisposed: function(event) { var target = (event.data); if (target != this.target()) return; WebInspector.moduleSetting("pauseOnExceptionEnabled").removeChangeListener(this._pauseOnExceptionStateChanged, this); WebInspector.moduleSetting("pauseOnCaughtException").removeChangeListener(this._pauseOnExceptionStateChanged, this); WebInspector.moduleSetting("skipStackFramesPattern").removeChangeListener(this._applySkipStackFrameSettings, this); WebInspector.moduleSetting("skipContentScripts").removeChangeListener(this._applySkipStackFrameSettings, this); WebInspector.moduleSetting("enableAsyncStackTraces").removeChangeListener(this.asyncStackTracesStateChanged, this); }, _suspendStateChanged: function() { if (WebInspector.targetManager.allTargetsSuspended()) this.disableDebugger(); else this.enableDebugger(); }, __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, isInternalScript, sourceMapURL, hasSourceURL) { this._debuggerModel._parsedScriptSource(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, !!isContentScript, !!isInternalScript, sourceMapURL, hasSourceURL, false); }, scriptFailedToParse: function(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, isInternalScript, sourceMapURL, hasSourceURL) { this._debuggerModel._parsedScriptSource(scriptId, sourceURL, startLine, startColumn, endLine, endColumn, !!isContentScript, !!isInternalScript, sourceMapURL, hasSourceURL, true); }, breakpointResolved: function(breakpointId, location) { this._debuggerModel._breakpointResolved(breakpointId, location); }, promiseUpdated: function(eventType, promise) { this._debuggerModel._promiseUpdated(eventType, promise); }, asyncOperationStarted: function(operation) { this._debuggerModel._asyncOperationStarted(operation); }, asyncOperationCompleted: function(operationId) { this._debuggerModel._asyncOperationCompleted(operationId); }}WebInspector.DebuggerModel.Location = function(debuggerModel, scriptId, lineNumber, columnNumber) { WebInspector.SDKObject.call(this, debuggerModel.target()); this._debuggerModel = debuggerModel; this.scriptId = scriptId; this.lineNumber = lineNumber; this.columnNumber = columnNumber || 0;}WebInspector.DebuggerModel.Location.fromPayload = function(debuggerModel, payload) { return new WebInspector.DebuggerModel.Location(debuggerModel,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(debuggerModel, script, payload, isAsync) { var target = debuggerModel.target(); WebInspector.SDKObject.call(this, target); this.debuggerModel = debuggerModel; this._debuggerAgent = debuggerModel._agent; this._script = script; this._payload = payload; this._isAsync = isAsync; this._location = WebInspector.DebuggerModel.Location.fromPayload(debuggerModel, payload.location); this._scopeChain = []; this._localScope = null ; for (var i = 0; i < payload.scopeChain.length; ++i) { var scope = new WebInspector.DebuggerModel.Scope(this,i); this._scopeChain.push(scope); if (scope.type() === DebuggerAgent.ScopeType.Local) this._localScope = scope; } if (payload.functionLocation) this._functionLocation = WebInspector.DebuggerModel.Location.fromPayload(debuggerModel, payload.functionLocation);}WebInspector.DebuggerModel.CallFrame.fromPayloadArray = function(debuggerModel, callFrames, isAsync) { var result = []; for (var i = 0; i < callFrames.length; ++i) { var callFrame = callFrames[i]; var script = debuggerModel.scriptForId(callFrame.location.scriptId); if (script) result.push(new WebInspector.DebuggerModel.CallFrame(debuggerModel,script,callFrame,isAsync)); } return result;}WebInspector.DebuggerModel.CallFrame.prototype = { get script() { return this._script; }, get id() { return this._payload.callFrameId; }, scopeChain: function() { return this._scopeChain; }, localScope: function() { return this._localScope; }, 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; }, functionLocation: function() { return this._functionLocation || null ; }, 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.debuggerModel.callStackModified(callFrames, details, asyncStackTrace); if (callback) callback(error); } this._debuggerAgent.restartFrame(this._payload.callFrameId, protocolCallback.bind(this)); }, variableNames: function(callback) { var result = { this: true }; function propertiesCollected(properties) { for (var i = 0; properties && i < properties.length; ++i) result[properties[i].name] = true; if (--pendingRequests == 0) callback(result); } var scopeChain = this.scopeChain(); var pendingRequests = scopeChain.length; for (var i = 0; i < scopeChain.length; ++i) { var scope = scopeChain[i]; var object = scope.object(); object.getAllProperties(false, propertiesCollected); } }, __proto__: WebInspector.SDKObject.prototype}WebInspector.DebuggerModel.Scope = function(callFrame, ordinal) { this._callFrame = callFrame; this._payload = callFrame._payload.scopeChain[ordinal]; this._type = this._payload.type; this._ordinal = ordinal;}WebInspector.DebuggerModel.Scope.prototype = { type: function() { return this._type; }, object: function() { if (this._object) return this._object; var runtimeModel = this._callFrame.target().runtimeModel; var declarativeScope = this._type !== DebuggerAgent.ScopeType.With && this._type !== DebuggerAgent.ScopeType.Global; if (declarativeScope) this._object = runtimeModel.createScopeRemoteObject(this._payload.object, new WebInspector.ScopeRef(this._ordinal,this._callFrame.id,undefined)); else this._object = runtimeModel.createRemoteObject(this._payload.object); return this._callFrame.target().runtimeModel.createRemoteObject(this._payload.object); }, description: function() { var declarativeScope = this._type !== DebuggerAgent.ScopeType.With && this._type !== DebuggerAgent.ScopeType.Global; return declarativeScope ? "" : (this._payload.object.description || ""); }}WebInspector.DebuggerModel.StackTrace = function(callFrames, asyncStackTrace, description) { this.callFrames = callFrames; this.asyncStackTrace = asyncStackTrace; this.description = description;}WebInspector.DebuggerModel.StackTrace.fromPayload = function(debuggerModel, payload, isAsync) { if (!payload) return null ; var callFrames = WebInspector.DebuggerModel.CallFrame.fromPayloadArray(debuggerModel, payload.callFrames, isAsync); if (!callFrames.length) return null ; var asyncStackTrace = WebInspector.DebuggerModel.StackTrace.fromPayload(debuggerModel, payload.asyncStackTrace, true); return new WebInspector.DebuggerModel.StackTrace(callFrames,asyncStackTrace,payload.description);}WebInspector.DebuggerPausedDetails = function(debuggerModel, callFrames, reason, auxData, breakpointIds, asyncStackTrace) { WebInspector.SDKObject.call(this, debuggerModel.target()); this.debuggerModel = debuggerModel; this.callFrames = WebInspector.DebuggerModel.CallFrame.fromPayloadArray(debuggerModel, callFrames); this.reason = reason; this.auxData = auxData; this.breakpointIds = breakpointIds; this.asyncStackTrace = WebInspector.DebuggerModel.StackTrace.fromPayload(debuggerModel, asyncStackTrace, true);}WebInspector.DebuggerPausedDetails.prototype = { exception: function() { if (this.reason !== WebInspector.DebuggerModel.BreakReason.Exception && this.reason !== WebInspector.DebuggerModel.BreakReason.PromiseRejection) return null ; return this.target().runtimeModel.createRemoteObject((this.auxData)); }, __proto__: WebInspector.SDKObject.prototype}WebInspector.DebuggerModel.instances = function() { var result = []; for (var target of WebInspector.targetManager.targets()) { var debuggerModel = WebInspector.DebuggerModel.fromTarget(target); if (debuggerModel) result.push(debuggerModel); } return result;}WebInspector.DebuggerModel.fromTarget = function(target) { if (!target || !target.hasJSContext()) return null ; return ( target.model(WebInspector.DebuggerModel)) ;};WebInspector.HAREntry = function(request) { this._request = request;}WebInspector.HAREntry.prototype = { build: function() { var entry = { startedDateTime: WebInspector.HARLog.pseudoWallTime(this._request, this._request.startTime), time: this._request.timing ? WebInspector.HAREntry._toMilliseconds(this._request.duration) : 0, request: this._buildRequest(), response: this._buildResponse(), cache: {}, timings: this._buildTimings() }; if (this._request.connectionId !== "0") entry.connection = this._request.connectionId; var page = this._request.target().networkLog.pageLoadForRequest(this._request); if (page) entry.pageref = "page_" + page.id; return entry; }, _buildRequest: function() { var headersText = this._request.requestHeadersText(); var res = { method: this._request.requestMethod, url: this._buildRequestURL(this._request.url), httpVersion: this._request.requestHttpVersion(), headers: this._request.requestHeaders(), queryString: this._buildParameters(this._request.queryParameters || []), cookies: this._buildCookies(this._request.requestCookies || []), headersSize: headersText ? headersText.length : -1, bodySize: this.requestBodySize }; if (this._request.requestFormData) res.postData = this._buildPostData(); return res; }, _buildResponse: function() { var headersText = this._request.responseHeadersText; return { status: this._request.statusCode, statusText: this._request.statusText, httpVersion: this._request.responseHttpVersion(), headers: this._request.responseHeaders, cookies: this._buildCookies(this._request.responseCookies || []), content: this._buildContent(), redirectURL: this._request.responseHeaderValue("Location") || "", headersSize: headersText ? headersText.length : -1, bodySize: this.responseBodySize, _transferSize: this._request.transferSize, _error: this._request.localizedFailDescription }; }, _buildContent: function() { var content = { size: this._request.resourceSize, mimeType: this._request.mimeType || "x-unknown", }; var compression = this.responseCompression; if (typeof compression === "number") content.compression = compression; return content; }, _buildTimings: function() { var timing = this._request.timing; if (!timing) return { blocked: -1, dns: -1, connect: -1, send: 0, wait: 0, receive: 0, ssl: -1 }; function firstNonNegative(values) { for (var i = 0; i < values.length; ++i) { if (values[i] >= 0) return values[i]; } console.assert(false, "Incomplete request timing information."); } var blocked = firstNonNegative([timing.dnsStart, timing.connectStart, timing.sendStart]); var dns = -1; if (timing.dnsStart >= 0) dns = firstNonNegative([timing.connectStart, timing.sendStart]) - timing.dnsStart; var connect = -1; if (timing.connectStart >= 0) connect = timing.sendStart - timing.connectStart; var send = timing.sendEnd - timing.sendStart; var wait = timing.receiveHeadersEnd - timing.sendEnd; var receive = WebInspector.HAREntry._toMilliseconds(this._request.duration) - timing.receiveHeadersEnd; var ssl = -1; if (timing.sslStart >= 0 && timing.sslEnd >= 0) ssl = timing.sslEnd - timing.sslStart; return { blocked: blocked, dns: dns, connect: connect, send: send, wait: wait, receive: receive, ssl: ssl }; }, _buildPostData: function() { var res = { mimeType: this._request.requestContentType(), text: this._request.requestFormData }; if (this._request.formParameters) res.params = this._buildParameters(this._request.formParameters); return res; }, _buildParameters: function(parameters) { return parameters.slice(); }, _buildRequestURL: function(url) { return url.split("#", 2)[0]; }, _buildCookies: function(cookies) { return cookies.map(this._buildCookie.bind(this)); }, _buildCookie: function(cookie) { return { name: cookie.name(), value: cookie.value(), path: cookie.path(), domain: cookie.domain(), expires: cookie.expiresDate(WebInspector.HARLog.pseudoWallTime(this._request, this._request.startTime)), httpOnly: cookie.httpOnly(), secure: cookie.secure() }; }, get requestBodySize() { return !this._request.requestFormData ? 0 : this._request.requestFormData.length; }, get responseBodySize() { if (this._request.cached() || this._request.statusCode === 304) return 0; if (!this._request.responseHeadersText) return -1; return this._request.transferSize - this._request.responseHeadersText.length; }, get responseCompression() { if (this._request.cached() || this._request.statusCode === 304 || this._request.statusCode === 206) return; if (!this._request.responseHeadersText) return; return this._request.resourceSize - this.responseBodySize; }}WebInspector.HAREntry._toMilliseconds = function(time) { return time === -1 ? -1 : time * 1000;}WebInspector.HARLog = function(requests) { this._requests = requests;}WebInspector.HARLog.pseudoWallTime = function(request, monotonicTime) { return new Date(request.pseudoWallTime(monotonicTime) * 1000);}WebInspector.HARLog.prototype = { build: function() { return { version: "1.2", creator: this._creator(), pages: this._buildPages(), entries: this._requests.map(this._convertResource.bind(this)) } }, _creator: function() { var webKitVersion = /AppleWebKit\/([^ ]+)/.exec(window.navigator.userAgent); return { name: "WebInspector", version: webKitVersion ? webKitVersion[1] : "n/a" }; }, _buildPages: function() { var seenIdentifiers = {}; var pages = []; for (var i = 0; i < this._requests.length; ++i) { var request = this._requests[i]; var page = request.target().networkLog.pageLoadForRequest(request); if (!page || seenIdentifiers[page.id]) continue;seenIdentifiers[page.id] = true; pages.push(this._convertPage(page, request)); } return pages; }, _convertPage: function(page, request) { return { startedDateTime: WebInspector.HARLog.pseudoWallTime(request, page.startTime), id: "page_" + page.id, title: page.url, pageTimings: { onContentLoad: this._pageEventTime(page, page.contentLoadTime), onLoad: this._pageEventTime(page, page.loadTime) } } }, _convertResource: function(request) { return (new WebInspector.HAREntry(request)).build(); }, _pageEventTime: function(page, time) { var startTime = page.startTime; if (time === -1 || startTime === -1) return -1; return WebInspector.HAREntry._toMilliseconds(time - startTime); }};WebInspector.TracingLayerPayload;WebInspector.TracingLayerTile;WebInspector.LayerTreeModel = function(target) { WebInspector.SDKModel.call(this, WebInspector.LayerTreeModel, target); target.registerLayerTreeDispatcher(new WebInspector.LayerTreeDispatcher(this)); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.MainFrameNavigated, this._onMainFrameNavigated, 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._forceEnable(); }, _forceEnable: function() { 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); }, _onMainFrameNavigated: function() { if (this._enabled) this._forceEnable(); }, __proto__: WebInspector.SDKModel.prototype}WebInspector.LayerTreeBase = function(target) { this._target = target; this._domModel = target ? WebInspector.DOMModel.fromTarget(target) : null ; this._layersById = {}; this._backendNodeIdToNode = new Map(); this._reset();}WebInspector.LayerTreeBase.prototype = { _reset: function() { this._root = null ; this._contentRoot = null ; }, target: function() { return this._target; }, 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.size || !this._domModel) { callback(); return; } if (this._domModel) this._domModel.pushNodesByBackendIdsToFrontend(requestedNodeIds, populateBackendNodeMap.bind(this)); function populateBackendNodeMap(nodesMap) { if (nodesMap) { for (var entry of nodesMap) this._backendNodeIdToNode.set(entry[0], entry[1]); } callback(); } }, setViewportSize: function(viewportSize) { this._viewportSize = viewportSize; }, viewportSize: function() { return this._viewportSize; }, _nodeForId: function(id) { return this._domModel ? this._domModel.nodeForId(id) : null ; }}WebInspector.TracingLayerTree = function(target) { WebInspector.LayerTreeBase.call(this, target); this._tileById = new Map();}WebInspector.TracingLayerTree.prototype = { setLayers: function(root, callback) { var idsToResolve = new Set(); 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(); } }, setTiles: function(tiles) { this._tileById = new Map(); for (var tile of tiles) this._tileById.set(tile.id, tile); }, tileById: function(id) { return this._tileById.get(id) || null ; }, _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 (payload.owner_node) layer._setNode(this._backendNodeIdToNode.get(payload.owner_node) || null ); if (!this._contentRoot && layer.drawsContent()) this._contentRoot = layer; 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 && !this._backendNodeIdToNode[backendNodeId]) nodeIdsToResolve.add(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 = new Set(); for (var i = 0; i < payload.length; ++i) { var backendNodeId = payload[i].backendNodeId; if (!backendNodeId || this._backendNodeIdToNode.has(backendNodeId)) continue;idsToResolve.add(backendNodeId); } this._resolveBackendNodeIds(idsToResolve, 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; var backendNodeId = layers[i].backendNodeId; if (backendNodeId) layer._setNode(this._backendNodeIdToNode.get(backendNodeId)); if (!this._contentRoot && layer.drawsContent()) 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() {}, gpuMemoryUsage: function() {}, requestCompositingReasons: function(callback) {}, drawsContent: function() {}}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); }, drawsContent: function() { return this._layerPayload.drawsContent; }, gpuMemoryUsage: function() { var bytesPerPixel = 4; return this.drawsContent() ? this.width() * this.height() * bytesPerPixel : 0; }, 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); this._compositingReasons = payload.compositing_reasons || []; this._drawsContent = !!payload.draws_content; this._gpuMemoryUsage = payload.gpu_memory_usage; }, 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; }, gpuMemoryUsage: function() { return this._gpuMemoryUsage; }, _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) { callback(this._compositingReasons); }, drawsContent: function() { return this._drawsContent; }}WebInspector.DeferredLayerTree = function(target) { this._target = target;}WebInspector.DeferredLayerTree.prototype = { resolve: function(callback) {}, target: function() { return this._target; }};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.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.requestForURL = function(url) { for (var target of WebInspector.targetManager.targets()) { var result = target.networkLog.requestForURL(url); if (result) return result; } return null ;}WebInspector.NetworkLog.requests = function() { var result = []; for (var target of WebInspector.targetManager.targets()) { result = result.concat(target.networkLog.requests()); } return result;}WebInspector.NetworkLog.prototype = { requests: function() { 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.PageLoad = function(mainRequest) { this.id = ++WebInspector.PageLoad._lastIdentifier; this.url = mainRequest.url; this.startTime = mainRequest.startTime;}WebInspector.PageLoad._lastIdentifier = 0;;WebInspector.ServiceWorkerManager = function(target) { WebInspector.SDKObject.call(this, target); target.registerServiceWorkerDispatcher(new WebInspector.ServiceWorkerDispatcher(this)); this._lastAnonymousTargetId = 0; this._agent = target.serviceWorkerAgent(); this._workers = new Map(); this._registrations = new Map(); this.enable();}WebInspector.ServiceWorkerManager.Events = { WorkersUpdated: "WorkersUpdated", RegistrationUpdated: "RegistrationUpdated", RegistrationDeleted: "RegistrationDeleted", DebugOnStartUpdated: "DebugOnStartUpdated"}WebInspector.ServiceWorkerManager.prototype = { enable: function() { if (this._enabled) return; this._enabled = true; this._agent.enable(); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.MainFrameNavigated, this._mainFrameNavigated, this); }, disable: function() { if (!this._enabled) return; this._enabled = false; for (var worker of this._workers.values()) worker._connection.close(); this._workers.clear(); this._registrations.clear(); this._agent.disable(); WebInspector.targetManager.removeEventListener(WebInspector.TargetManager.Events.MainFrameNavigated, this._mainFrameNavigated, this); }, workers: function() { return this._workers.values(); }, hasWorkers: function() { return !!this._workers.size; }, debugOnStart: function() { return !!this._debugOnStart; }, setDebugOnStart: function(flag) { this._agent.setDebugOnStart(flag); }, registrations: function() { return this._registrations; }, deleteRegistration: function(registrationId) { var registration = this._registrations.get(registrationId); if (!registration) return; if (registration._isRedundant()) { this._registrations.delete(registrationId); this.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.RegistrationDeleted, registration); return; } registration._deleting = true; for (var version of registration.versions.values()) this.stopWorker(version.id); this._unregister(registration.scopeURL); }, updateRegistration: function(registrationId) { var registration = this._registrations.get(registrationId); if (!registration) return; this._agent.updateRegistration(registration.scopeURL); }, deliverPushMessage: function(registrationId, data) { var registration = this._registrations.get(registrationId); if (!registration) return; var origin = WebInspector.ParsedURL.splitURLIntoPathComponents(registration.scopeURL)[0]; this._agent.deliverPushMessage(origin, registrationId, data); }, activateTarget: function(targetId) { this._agent.activateTarget(targetId); }, _unregister: function(scope) { this._agent.unregister(scope); }, startWorker: function(scope) { this._agent.startWorker(scope); }, stopWorker: function(versionId) { this._agent.stopWorker(versionId); }, inspectWorker: function(versionId) { this._agent.inspectWorker(versionId); }, skipWaiting: function(versionId) { this._agent.skipWaiting(versionId); }, getTargetInfo: function(targetId, callback) { function innerCallback(error, targetInfo) { if (error) { console.error(error); callback(null ); return; } if (targetInfo) callback(new WebInspector.TargetInfo(targetInfo)); else callback(null ) } this._agent.getTargetInfo(targetId, innerCallback); }, _workerCreated: function(workerId, url) { new WebInspector.ServiceWorker(this,workerId,url); }, _workerTerminated: function(workerId) { var worker = this._workers.get(workerId); if (!worker) return; worker._closeConnection(); this._workers.delete(workerId); this.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.WorkersUpdated); }, _dispatchMessage: function(workerId, message) { var worker = this._workers.get(workerId); if (worker) worker._connection.dispatch(message); }, _workerRegistrationUpdated: function(registrations) { for (var payload of registrations) { var registration = this._registrations.get(payload.registrationId); if (!registration) { registration = new WebInspector.ServiceWorkerRegistration(payload); this._registrations.set(payload.registrationId, registration); this.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.RegistrationUpdated, registration); continue; } registration._update(payload); if (registration._shouldBeRemoved()) { this._registrations.delete(registration.id); this.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.RegistrationDeleted, registration); } else { this.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.RegistrationUpdated, registration); } } }, _workerVersionUpdated: function(versions) { var registrations = new Set(); for (var payload of versions) { var registration = this._registrations.get(payload.registrationId); if (!registration) continue;registration._updateVersion(payload); registrations.add(registration); } for (var registration of registrations) { if (registration._shouldBeRemoved()) { this._registrations.delete(registration.id); this.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.RegistrationDeleted, registration); } else { this.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.RegistrationUpdated, registration); } } }, _workerErrorReported: function(payload) { var registration = this._registrations.get(payload.registrationId); if (!registration) return; registration._addError(payload); this.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.RegistrationUpdated, registration); }, _debugOnStartUpdated: function(flag) { this._debugOnStart = flag; this.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.DebugOnStartUpdated, flag); }, _mainFrameNavigated: function(event) {}, __proto__: WebInspector.SDKObject.prototype}WebInspector.ServiceWorker = function(manager, workerId, url) { this._manager = manager; this._agent = manager.target().serviceWorkerAgent(); this._workerId = workerId; this._connection = new WebInspector.ServiceWorkerConnection(this._agent,workerId); this._url = url; var parsedURL = url.asParsedURL(); this._name = parsedURL ? parsedURL.lastPathComponentWithFragment() : "#" + (++WebInspector.ServiceWorker._lastAnonymousTargetId); this._scope = parsedURL.host + parsedURL.folderPathComponents; var title = WebInspector.UIString("\u2699 %s", this._name); this._manager._workers.set(workerId, this); WebInspector.targetManager.createTarget(title, WebInspector.Target.Type.ServiceWorker, this._connection, manager.target(), targetCreated.bind(this)); function targetCreated(target) { if (!target) { this._manager._workers.delete(workerId); return; } this._manager.dispatchEventToListeners(WebInspector.ServiceWorkerManager.Events.WorkersUpdated); target.runtimeAgent().run(); }}WebInspector.ServiceWorker._lastAnonymousTargetId = 0;WebInspector.ServiceWorker.prototype = { name: function() { return this._name; }, url: function() { return this._url; }, scope: function() { return this._scope; }, stop: function() { this._agent.stop(this._workerId); }, _closeConnection: function() { this._connection._close(); }}WebInspector.ServiceWorkerDispatcher = function(manager) { this._manager = manager;}WebInspector.ServiceWorkerDispatcher.prototype = { workerCreated: function(workerId, url) { this._manager._workerCreated(workerId, url); }, workerTerminated: function(workerId) { this._manager._workerTerminated(workerId); }, dispatchMessage: function(workerId, message) { this._manager._dispatchMessage(workerId, message); }, workerRegistrationUpdated: function(registrations) { this._manager._workerRegistrationUpdated(registrations); }, workerVersionUpdated: function(versions) { this._manager._workerVersionUpdated(versions); }, workerErrorReported: function(errorMessage) { this._manager._workerErrorReported(errorMessage); }, debugOnStartUpdated: function(flag) { this._manager._debugOnStartUpdated(flag); }}WebInspector.ServiceWorkerConnection = function(agent, workerId) { InspectorBackendClass.Connection.call(this); this.suppressErrorsForDomains(["Worker", "Page", "CSS", "DOM", "DOMStorage", "Database", "Network", "IndexedDB"]); this._agent = agent; this._workerId = workerId;}WebInspector.ServiceWorkerConnection.prototype = { sendMessage: function(messageObject) { this._agent.sendMessage(this._workerId, JSON.stringify(messageObject)); }, _close: function() { this.connectionClosed("worker_terminated"); }, __proto__: InspectorBackendClass.Connection.prototype}WebInspector.TargetInfo = function(payload) { this.id = payload.id; this.type = payload.type; this.title = payload.title; this.url = payload.url;}WebInspector.TargetInfo.prototype = { isWebContents: function() { return this.type == "web_contents"; }, isFrame: function() { return this.type == "frame"; },}WebInspector.ServiceWorkerErrorMessage = function(payload) { this.errorMessage = payload.errorMessage; this.sourceURL = payload.sourceURL; this.lineNumber = payload.lineNumber; this.columnNumber = payload.columnNumber;}WebInspector.ServiceWorkerVersion = function(registration, payload) { this._registration = registration; this._update(payload); this.errorMessages = [];}WebInspector.ServiceWorkerVersion.prototype = { _update: function(payload) { this.id = payload.versionId; this.scriptURL = payload.scriptURL; this.runningStatus = payload.runningStatus; this.status = payload.status; this.scriptLastModified = payload.scriptLastModified; this.scriptResponseTime = payload.scriptResponseTime; this.controlledClients = [] for (var i = 0; i < payload.controlledClients.length; ++i) { this.controlledClients.push(payload.controlledClients[i]); } }, isStartable: function() { return !this._registration.isDeleted && this.isActivated() && this.isStopped(); }, isStoppedAndRedundant: function() { return this.runningStatus == ServiceWorkerAgent.ServiceWorkerVersionRunningStatus.Stopped && this.status == ServiceWorkerAgent.ServiceWorkerVersionStatus.Redundant; }, isStopped: function() { return this.runningStatus == ServiceWorkerAgent.ServiceWorkerVersionRunningStatus.Stopped; }, isStarting: function() { return this.runningStatus == ServiceWorkerAgent.ServiceWorkerVersionRunningStatus.Starting; }, isRunning: function() { return this.runningStatus == ServiceWorkerAgent.ServiceWorkerVersionRunningStatus.Running; }, isStopping: function() { return this.runningStatus == ServiceWorkerAgent.ServiceWorkerVersionRunningStatus.Stopping; }, isNew: function() { return this.status == ServiceWorkerAgent.ServiceWorkerVersionStatus.New; }, isInstalling: function() { return this.status == ServiceWorkerAgent.ServiceWorkerVersionStatus.Installing; }, isInstalled: function() { return this.status == ServiceWorkerAgent.ServiceWorkerVersionStatus.Installed; }, isActivating: function() { return this.status == ServiceWorkerAgent.ServiceWorkerVersionStatus.Activating; }, isActivated: function() { return this.status == ServiceWorkerAgent.ServiceWorkerVersionStatus.Activated; }, isRedundant: function() { return this.status == ServiceWorkerAgent.ServiceWorkerVersionStatus.Redundant; }, _addError: function(payload) { this.errorMessages.push(new WebInspector.ServiceWorkerErrorMessage(payload)); }}WebInspector.ServiceWorkerRegistration = function(payload) { this._update(payload); this.versions = new Map(); this._deleting = false;}WebInspector.ServiceWorkerRegistration.prototype = { _update: function(payload) { this.id = payload.registrationId; this.scopeURL = payload.scopeURL; this.isDeleted = payload.isDeleted; }, _updateVersion: function(payload) { var version = this.versions.get(payload.versionId); if (!version) { version = new WebInspector.ServiceWorkerVersion(this,payload); this.versions.set(payload.versionId, version); return version; } version._update(payload); return version; }, _addError: function(payload) { var version = this.versions.get(payload.versionId); if (version) version._addError(payload); }, _isRedundant: function() { for (var version of this.versions.values()) { if (!version.isStoppedAndRedundant()) return false; } return true; }, _hasErrorLog: function() { for (var version of this.versions.values()) { if (version.errorMessages.length) return true; } return false; }, _shouldBeRemoved: function() { return this._isRedundant() && (!this._hasErrorLog() || this._deleting); }};WebInspector.TracingManagerClient = function() {}WebInspector.TracingManagerClient.prototype = { tracingStarted: function() {}, traceEventsCollected: function(events) {}, tracingComplete: function() {}, tracingBufferUsage: function(usage) {}, eventsRetrievalProgress: function(progress) {}}WebInspector.TracingManager = function(target) { this._target = target; target.registerTracingDispatcher(new WebInspector.TracingDispatcher(this)); this._activeClient = null ; this._eventBufferSize = 0; this._eventsRetrieved = 0;}WebInspector.TracingManager.EventPayload;WebInspector.TracingManager.prototype = { target: function() { return this._target; }, _bufferUsage: function(usage, eventCount, percentFull) { this._eventBufferSize = eventCount; this._activeClient.tracingBufferUsage(usage || percentFull || 0); }, _eventsCollected: function(events) { this._activeClient.traceEventsCollected(events); this._eventsRetrieved += events.length; if (!this._eventBufferSize) return; if (this._eventsRetrieved > this._eventBufferSize) this._eventsRetrieved = this._eventBufferSize; this._activeClient.eventsRetrievalProgress(this._eventsRetrieved / this._eventBufferSize); }, _tracingComplete: function() { this._eventBufferSize = 0; this._eventsRetrieved = 0; this._activeClient.tracingComplete(); this._activeClient = null ; }, start: function(client, categoryFilter, options, callback) { if (this._activeClient) throw new Error("Tracing is already started"); var bufferUsageReportingIntervalMs = 500; this._activeClient = client; this._target.tracingAgent().start(categoryFilter, options, bufferUsageReportingIntervalMs, callback); this._activeClient.tracingStarted(); }, stop: function() { this._target.tracingAgent().end(); }}WebInspector.TracingDispatcher = function(tracingManager) { this._tracingManager = tracingManager;}WebInspector.TracingDispatcher.prototype = { bufferUsage: function(usage, eventCount, percentFull) { this._tracingManager._bufferUsage(usage, eventCount, percentFull); }, dataCollected: function(data) { this._tracingManager._eventsCollected(data); }, tracingComplete: function() { this._tracingManager._tracingComplete(); }};WebInspector.TracingModel = function(backingStorage) { this._backingStorage = backingStorage; this.reset();}WebInspector.TracingModel.Phase = { Begin: "B", End: "E", Complete: "X", Instant: "I", AsyncBegin: "S", AsyncStepInto: "T", AsyncStepPast: "p", AsyncEnd: "F", NestableAsyncBegin: "b", NestableAsyncEnd: "e", NestableAsyncInstant: "n", 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.TopLevelEventCategory = "toplevel";WebInspector.TracingModel.DevToolsMetadataEventCategory = "disabled-by-default-devtools.timeline";WebInspector.TracingModel.DevToolsTimelineEventCategory = "disabled-by-default-devtools.timeline";WebInspector.TracingModel.ConsoleEventCategory = "blink.console";WebInspector.TracingModel.FrameLifecycleEventCategory = "cc,devtools";WebInspector.TracingModel.DevToolsMetadataEvent = { TracingStartedInPage: "TracingStartedInPage", TracingSessionIdForWorker: "TracingSessionIdForWorker",};WebInspector.TracingModel._nestableAsyncEventsString = WebInspector.TracingModel.Phase.NestableAsyncBegin + WebInspector.TracingModel.Phase.NestableAsyncEnd + WebInspector.TracingModel.Phase.NestableAsyncInstant;WebInspector.TracingModel._legacyAsyncEventsString = WebInspector.TracingModel.Phase.AsyncBegin + WebInspector.TracingModel.Phase.AsyncEnd + WebInspector.TracingModel.Phase.AsyncStepInto + WebInspector.TracingModel.Phase.AsyncStepPast;WebInspector.TracingModel._flowEventsString = WebInspector.TracingModel.Phase.FlowBegin + WebInspector.TracingModel.Phase.FlowStep + WebInspector.TracingModel.Phase.FlowEnd;WebInspector.TracingModel._rendererMainThreadName = "CrRendererMain";WebInspector.TracingModel._asyncEventsString = WebInspector.TracingModel._nestableAsyncEventsString + WebInspector.TracingModel._legacyAsyncEventsString;WebInspector.TracingModel.isNestableAsyncPhase = function(phase) { return WebInspector.TracingModel._nestableAsyncEventsString.indexOf(phase) >= 0;}WebInspector.TracingModel.isAsyncBeginPhase = function(phase) { return phase === WebInspector.TracingModel.Phase.AsyncBegin || phase === WebInspector.TracingModel.Phase.NestableAsyncBegin;}WebInspector.TracingModel.isAsyncPhase = function(phase) { return WebInspector.TracingModel._asyncEventsString.indexOf(phase) >= 0;}WebInspector.TracingModel.isFlowPhase = function(phase) { return WebInspector.TracingModel._flowEventsString.indexOf(phase) >= 0;}WebInspector.TracingModel.isTopLevelEvent = function(event) { return event.hasCategory(WebInspector.TracingModel.TopLevelEventCategory) || event.hasCategory(WebInspector.TracingModel.DevToolsMetadataEventCategory) && event.name === "Program";}WebInspector.BackingStorage = function() {}WebInspector.BackingStorage.prototype = { appendString: function(string) {}, appendAccessibleString: function(string) {}, finishWriting: function() {}, reset: function() {},}WebInspector.TracingModel.prototype = { devtoolsPageMetadataEvents: function() { return this._devtoolsPageMetadataEvents; }, devtoolsWorkerMetadataEvents: function() { return this._devtoolsWorkerMetadataEvents; }, sessionId: function() { return this._sessionId; }, setEventsForTest: function(events) { this.reset(); this.addEvents(events); this.tracingComplete(); }, addEvents: function(events) { for (var i = 0; i < events.length; ++i) this._addEvent(events[i]); }, tracingComplete: function() { this._processMetadataEvents(); this._processPendingAsyncEvents(); this._backingStorage.finishWriting(); for (var process of Object.values(this._processById)) { for (var thread of Object.values(process._threads)) thread.tracingComplete(); } }, reset: function() { this._processById = {}; this._processByName = new Map(); this._minimumRecordTime = 0; this._maximumRecordTime = 0; this._sessionId = null ; this._devtoolsPageMetadataEvents = []; this._devtoolsWorkerMetadataEvents = []; this._backingStorage.reset(); this._appendDelimiter = false; this._loadedFromFile = false; this._asyncEvents = []; this._openAsyncEvents = new Map(); this._openNestableAsyncEvents = new Map(); this._parsedCategories = new Map(); }, _addEvent: function(payload) { var process = this._processById[payload.pid]; if (!process) { process = new WebInspector.TracingModel.Process(this,payload.pid); this._processById[payload.pid] = process; } var eventsDelimiter = ",\n"; if (this._appendDelimiter) this._backingStorage.appendString(eventsDelimiter); this._appendDelimiter = true; var stringPayload = JSON.stringify(payload); var isAccessible = payload.ph === WebInspector.TracingModel.Phase.SnapshotObject; var backingStorage = null ; var keepStringsLessThan = 10000; if (isAccessible && stringPayload.length > keepStringsLessThan) backingStorage = this._backingStorage.appendAccessibleString(stringPayload); else this._backingStorage.appendString(stringPayload); if (payload.ph !== WebInspector.TracingModel.Phase.Metadata) { var timestamp = payload.ts / 1000; if (timestamp && (!this._minimumRecordTime || timestamp < this._minimumRecordTime)) this._minimumRecordTime = timestamp; var endTimeStamp = (payload.ts + (payload.dur || 0)) / 1000; this._maximumRecordTime = Math.max(this._maximumRecordTime, endTimeStamp); var event = process._addEvent(payload); if (!event) return; if (WebInspector.TracingModel.isAsyncPhase(payload.ph)) this._asyncEvents.push(event); event._setBackingStorage(backingStorage); if (event.name === WebInspector.TracingModel.DevToolsMetadataEvent.TracingStartedInPage && event.hasCategory(WebInspector.TracingModel.DevToolsMetadataEventCategory)) { this._devtoolsPageMetadataEvents.push(event); } if (event.name === WebInspector.TracingModel.DevToolsMetadataEvent.TracingSessionIdForWorker && event.hasCategory(WebInspector.TracingModel.DevToolsMetadataEventCategory)) { 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: var processName = payload.args["name"]; process._setName(processName); this._processByName.set(processName, process); break; case WebInspector.TracingModel.MetadataEvent.ThreadSortIndex: process.threadById(payload.tid)._setSortIndex(payload.args["sort_index"]); break; case WebInspector.TracingModel.MetadataEvent.ThreadName: process.threadById(payload.tid)._setName(payload.args["name"]); break; } }, _processMetadataEvents: function() { this._devtoolsPageMetadataEvents.sort(WebInspector.TracingModel.Event.compareStartTime); if (!this._devtoolsPageMetadataEvents.length) { var pageMetaEvent = this._loadedFromFile ? this._makeMockPageMetadataEvent() : null ; if (!pageMetaEvent) { console.error(WebInspector.TracingModel.DevToolsMetadataEvent.TracingStartedInPage + " event not found."); return; } this._devtoolsPageMetadataEvents.push(pageMetaEvent); } var sessionId = this._devtoolsPageMetadataEvents[0].args["sessionId"] || this._devtoolsPageMetadataEvents[0].args["data"]["sessionId"]; this._sessionId = sessionId; var mismatchingIds = {}; function checkSessionId(event) { var args = event.args; if (args["data"]) args = args["data"]; var id = args["sessionId"]; if (id === sessionId) return true; mismatchingIds[id] = true; return false; } this._devtoolsPageMetadataEvents = this._devtoolsPageMetadataEvents.filter(checkSessionId); this._devtoolsWorkerMetadataEvents = this._devtoolsWorkerMetadataEvents.filter(checkSessionId); var idList = Object.keys(mismatchingIds); if (idList.length) WebInspector.console.error("Timeline recording was started in more than one page simultaneously. Session id mismatch: " + this._sessionId + " and " + idList + "."); }, _makeMockPageMetadataEvent: function() { var rendererMainThreadName = WebInspector.TracingModel._rendererMainThreadName; var process = Object.values(this._processById).filter(function(p) { return p.threadByName(rendererMainThreadName); } )[0]; var thread = process && process.threadByName(rendererMainThreadName); if (!thread) return null ; var pageMetaEvent = new WebInspector.TracingModel.Event(WebInspector.TracingModel.DevToolsMetadataEventCategory,WebInspector.TracingModel.DevToolsMetadataEvent.TracingStartedInPage,WebInspector.TracingModel.Phase.Metadata,this._minimumRecordTime,thread); pageMetaEvent.addArgs({ "data": { "sessionId": "mockSessionId" } }); return pageMetaEvent; }, minimumRecordTime: function() { return this._minimumRecordTime; }, maximumRecordTime: function() { return this._maximumRecordTime; }, sortedProcesses: function() { return WebInspector.TracingModel.NamedObject._sort(Object.values(this._processById)); }, processByName: function(name) { return this._processByName.get(name); }, _processPendingAsyncEvents: function() { this._asyncEvents.sort(WebInspector.TracingModel.Event.compareStartTime); for (var i = 0; i < this._asyncEvents.length; ++i) { var event = this._asyncEvents[i]; if (WebInspector.TracingModel.isNestableAsyncPhase(event.phase)) this._addNestableAsyncEvent(event); else this._addAsyncEvent(event); } this._asyncEvents = []; this._closeOpenAsyncEvents(); }, _closeOpenAsyncEvents: function() { for (var event of this._openAsyncEvents.values()) { event.setEndTime(this._maximumRecordTime); event.steps[0].setEndTime(this._maximumRecordTime); } this._openAsyncEvents.clear(); for (var eventStack of this._openNestableAsyncEvents.values()) { while (eventStack.length) eventStack.pop().setEndTime(this._maximumRecordTime); } this._openNestableAsyncEvents.clear(); }, _addNestableAsyncEvent: function(event) { var phase = WebInspector.TracingModel.Phase; var key = event.categoriesString + "." + event.id; var openEventsStack = this._openNestableAsyncEvents.get(key); switch (event.phase) { case phase.NestableAsyncBegin: if (!openEventsStack) { openEventsStack = []; this._openNestableAsyncEvents.set(key, openEventsStack); } var asyncEvent = new WebInspector.TracingModel.AsyncEvent(event); openEventsStack.push(asyncEvent); event.thread._addAsyncEvent(asyncEvent); break; case phase.NestableAsyncInstant: if (openEventsStack && openEventsStack.length) openEventsStack.peekLast()._addStep(event); break; case phase.NestableAsyncEnd: if (!openEventsStack || !openEventsStack.length) break; var top = openEventsStack.pop(); if (top.name !== event.name) { console.error("Begin/end event mismatch for nestable async event, " + top.name + " vs. " + event.name); break; } top._addStep(event); } }, _addAsyncEvent: function(event) { var phase = WebInspector.TracingModel.Phase; var key = event.categoriesString + "." + event.name + "." + event.id; var asyncEvent = this._openAsyncEvents.get(key); if (event.phase === phase.AsyncBegin) { if (asyncEvent) { console.error("Event " + event.name + " has already been started"); return; } asyncEvent = new WebInspector.TracingModel.AsyncEvent(event); this._openAsyncEvents.set(key, asyncEvent); event.thread._addAsyncEvent(asyncEvent); return; } if (!asyncEvent) { return; } if (event.phase === phase.AsyncEnd) { asyncEvent._addStep(event); this._openAsyncEvents.delete(key); return; } if (event.phase === phase.AsyncStepInto || event.phase === phase.AsyncStepPast) { var lastStep = asyncEvent.steps.peekLast(); if (lastStep.phase !== phase.AsyncBegin && lastStep.phase !== event.phase) { console.assert(false, "Async event step phase mismatch: " + lastStep.phase + " at " + lastStep.startTime + " vs. " + event.phase + " at " + event.startTime); return; } asyncEvent._addStep(event); return; } console.assert(false, "Invalid async event phase"); }, _parsedCategoriesForString: function(str) { var parsedCategories = this._parsedCategories.get(str); if (!parsedCategories) { parsedCategories = new Set(str.split(",")); this._parsedCategories.set(str, parsedCategories); } return parsedCategories; }}WebInspector.TracingModel.Loader = function(tracingModel) { this._tracingModel = tracingModel; this._firstChunkReceived = false;}WebInspector.TracingModel.Loader.prototype = { loadNextChunk: function(events) { if (!this._firstChunkReceived) { this._tracingModel.reset(); this._firstChunkReceived = true; } this._tracingModel.addEvents(events); }, finish: function() { this._tracingModel._loadedFromFile = true; this._tracingModel.tracingComplete(); }}WebInspector.TracingModel.Event = function(categories, name, phase, startTime, thread) { this.categoriesString = categories; this._parsedCategories = thread._model._parsedCategoriesForString(categories); this.name = name; this.phase = phase; this.startTime = startTime; this.thread = thread; this.args = {}; this.warning = null ; this.initiator = null ; this.stackTrace = null ; this.previewElement = null ; this.url = null ; this.backendNodeId = 0; this.selfTime = 0;}WebInspector.TracingModel.Event.fromPayload = function(payload, thread) { var event = new WebInspector.TracingModel.Event(payload.cat,payload.name,(payload.ph),payload.ts / 1000,thread); if (payload.args) event.addArgs(payload.args); else console.error("Missing mandatory event argument 'args' at " + payload.ts / 1000); if (typeof payload.dur === "number") event.setEndTime((payload.ts + payload.dur) / 1000); if (payload.id) event.id = payload.id; return event;}WebInspector.TracingModel.Event.prototype = { hasCategory: function(categoryName) { return this._parsedCategories.has(categoryName); }, 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; }, addArgs: function(args) { for (var name in 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] = args[name]; } }, _complete: function(endEvent) { if (endEvent.args) this.addArgs(endEvent.args); else console.error("Missing mandatory event argument 'args' at " + endEvent.startTime); this.setEndTime(endEvent.startTime); }, _setBackingStorage: function(backingStorage) {}}WebInspector.TracingModel.Event.compareStartTime = function(a, b) { return a.startTime - b.startTime;}WebInspector.TracingModel.Event.orderedCompareStartTime = function(a, b) { return a.startTime - b.startTime || a.ordinal - b.ordinal || -1;}WebInspector.TracingModel.ObjectSnapshot = function(category, name, startTime, thread) { WebInspector.TracingModel.Event.call(this, category, name, WebInspector.TracingModel.Phase.SnapshotObject, startTime, thread);}WebInspector.TracingModel.ObjectSnapshot.fromPayload = function(payload, thread) { var snapshot = new WebInspector.TracingModel.ObjectSnapshot(payload.cat,payload.name,payload.ts / 1000,thread); if (payload.id) snapshot.id = payload.id; if (!payload.args || !payload.args["snapshot"]) { console.error("Missing mandatory 'snapshot' argument at " + payload.ts / 1000); return snapshot; } if (payload.args) snapshot.addArgs(payload.args); return snapshot;}WebInspector.TracingModel.ObjectSnapshot.prototype = { requestObject: function(callback) { var snapshot = this.args["snapshot"]; if (snapshot) { callback(snapshot); return; } this._backingStorage().then(onRead, callback.bind(null , null )); function onRead(result) { if (!result) { callback(null ); return; } try { var payload = JSON.parse(result); callback(payload["args"]["snapshot"]); } catch (e) { WebInspector.console.error("Malformed event data in backing storage"); callback(null ); } } }, objectPromise: function() { if (!this._objectPromise) this._objectPromise = new Promise(this.requestObject.bind(this)); return this._objectPromise; }, _setBackingStorage: function(backingStorage) { if (!backingStorage) return; this._backingStorage = backingStorage; this.args = {}; }, __proto__: WebInspector.TracingModel.Event.prototype}WebInspector.TracingModel.AsyncEvent = function(startEvent) { WebInspector.TracingModel.Event.call(this, startEvent.categoriesString, startEvent.name, startEvent.phase, startEvent.startTime, startEvent.thread) this.addArgs(startEvent.args); this.steps = [startEvent];}WebInspector.TracingModel.AsyncEvent.prototype = { _addStep: function(event) { this.steps.push(event) if (event.phase === WebInspector.TracingModel.Phase.AsyncEnd || event.phase === WebInspector.TracingModel.Phase.NestableAsyncEnd) { this.setEndTime(event.startTime); this.steps[0].setEndTime(event.startTime); } }, __proto__: WebInspector.TracingModel.Event.prototype}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(model, id) { WebInspector.TracingModel.NamedObject.call(this); this._setName("Process " + id); this._id = id; this._threads = {}; this._threadByName = new Map(); this._model = model;}WebInspector.TracingModel.Process.prototype = { id: function() { return this._id; }, threadById: function(id) { var thread = this._threads[id]; if (!thread) { thread = new WebInspector.TracingModel.Thread(this,id); this._threads[id] = thread; } return thread; }, threadByName: function(name) { return this._threadByName.get(name) || null ; }, _setThreadByName: function(name, thread) { this._threadByName.set(name, thread); }, _addEvent: function(payload) { return this.threadById(payload.tid)._addEvent(payload); }, 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._asyncEvents = []; this._id = id; this._model = process._model;}WebInspector.TracingModel.Thread.prototype = { target: function() { if (this.name() === WebInspector.TracingModel._rendererMainThreadName) return WebInspector.targetManager.targets()[0] || null ; else return null ; }, tracingComplete: function() { this._asyncEvents.stableSort(WebInspector.TracingModel.Event.compareStartTime); this._events.stableSort(WebInspector.TracingModel.Event.compareStartTime); var phases = WebInspector.TracingModel.Phase; var stack = []; for (var i = 0; i < this._events.length; ++i) { var e = this._events[i]; e.ordinal = i; switch (e.phase) { case phases.End: this._events[i] = null ; if (!stack.length) continue;var top = stack.pop(); if (top.name !== e.name || top.categoriesString !== e.categoriesString) console.error("B/E events mismatch at " + top.startTime + " (" + top.name + ") vs. " + e.startTime + " (" + e.name + ")"); else top._complete(e); break; case phases.Begin: stack.push(e); break; } } this._events.remove(null , false); }, _addEvent: function(payload) { var event = payload.ph === WebInspector.TracingModel.Phase.SnapshotObject ? WebInspector.TracingModel.ObjectSnapshot.fromPayload(payload, this) : WebInspector.TracingModel.Event.fromPayload(payload, this); if (WebInspector.TracingModel.isTopLevelEvent(event)) { if (this._lastTopLevelEvent && this._lastTopLevelEvent.endTime > event.startTime) return null ; this._lastTopLevelEvent = event; } this._events.push(event); return event; }, _addAsyncEvent: function(asyncEvent) { this._asyncEvents.push(asyncEvent); }, _setName: function(name) { WebInspector.TracingModel.NamedObject.prototype._setName.call(this, name); this._process._setThreadByName(name, this); }, id: function() { return this._id; }, process: function() { return this._process; }, events: function() { return this._events; }, asyncEvents: function() { return this._asyncEvents; }, __proto__: WebInspector.TracingModel.NamedObject.prototype};WebInspector.WorkerManager = function(target) { WebInspector.SDKObject.call(this, target); target.registerWorkerDispatcher(new WebInspector.WorkerDispatcher(this)); this._lastAnonymousTargetId = 0; this._connections = new Map(); this._targetsByWorkerId = new Map(); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChanged, this); this._onSuspendStateChanged(); this.enable();}WebInspector.WorkerManager.prototype = { enable: function() { if (this._enabled) return; this._enabled = true; this.target().workerAgent().enable(); this.target().resourceTreeModel.addEventListener(WebInspector.TargetManager.Events.MainFrameNavigated, this._mainFrameNavigated, this); }, disable: function() { if (!this._enabled) return; this._enabled = false; this._reset(); this.target().workerAgent().disable(); this.target().resourceTreeModel.removeEventListener(WebInspector.TargetManager.Events.MainFrameNavigated, this._mainFrameNavigated, this); }, dispose: function() { this._reset(); }, _reset: function() { for (var connection of this._connections.values()) connection._close(); this._connections.clear(); this._targetsByWorkerId.clear(); }, _onSuspendStateChanged: function() { var suspended = WebInspector.targetManager.allTargetsSuspended(); this.target().workerAgent().setAutoconnectToWorkers(!suspended); }, _workerCreated: function(workerId, url, inspectorConnected) { var connection = new WebInspector.WorkerConnection(this,workerId,inspectorConnected,onConnectionReady.bind(this)); this._connections.set(workerId, connection); function onConnectionReady(connection) { var parsedURL = url.asParsedURL(); var workerName = parsedURL ? parsedURL.lastPathComponentWithFragment() : "#" + (++this._lastAnonymousTargetId); var title = WebInspector.UIString("\u2699 %s", workerName); WebInspector.targetManager.createTarget(title, WebInspector.Target.Type.DedicatedWorker, connection, this.target(), targetCreated.bind(this)); } function targetCreated(target) { if (!target) return; this._targetsByWorkerId.set(workerId, target); if (inspectorConnected) target.runtimeAgent().isRunRequired(pauseInDebuggerAndRunIfRequired.bind(null , target)); } function pauseInDebuggerAndRunIfRequired(target, error, required) { var mainIsServiceWorker = WebInspector.targetManager.mainTarget().isServiceWorker(); if (mainIsServiceWorker && required) target.debuggerAgent().pause(); target.runtimeAgent().run(); } }, _workerTerminated: function(workerId) { var connection = this._connections.get(workerId); if (connection) connection._close(); this._connections.delete(workerId); this._targetsByWorkerId.delete(workerId); }, _dispatchMessageFromWorker: function(workerId, message) { var connection = this._connections.get(workerId); if (connection) connection.dispatch(message); }, _mainFrameNavigated: function(event) { this._reset(); }, targetByWorkerId: function(workerId) { return this._targetsByWorkerId.get(workerId) || null ; }, __proto__: WebInspector.SDKObject.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); }}WebInspector.WorkerConnection = function(workerManager, workerId, inspectorConnected, onConnectionReady) { InspectorBackendClass.Connection.call(this); this.suppressErrorsForDomains(["Worker", "Page", "CSS", "DOM", "DOMStorage", "Database", "Network", "IndexedDB"]); this._agent = workerManager.target().workerAgent(); this._workerId = workerId; if (!inspectorConnected) this._agent.connectToWorker(workerId, onConnectionReady.bind(null , this)); else onConnectionReady.call(null , this);}WebInspector.WorkerConnection.prototype = { sendMessage: function(messageObject) { this._agent.sendMessageToWorker(this._workerId, JSON.stringify(messageObject)); }, _close: function() { this.connectionClosed("worker_terminated"); }, __proto__: InspectorBackendClass.Connection.prototype};WebInspector.RuntimeModel = function(target) { WebInspector.SDKModel.call(this, WebInspector.RuntimeModel, target); this._agent = target.runtimeAgent(); this.target().registerRuntimeDispatcher(new WebInspector.RuntimeDispatcher(this)); if (target.hasJSContext()) this._agent.enable(); this._executionContextById = {}; if (!Runtime.experiments.isEnabled("customObjectFormatters")) return; if (WebInspector.moduleSetting("customFormatters").get()) this._agent.setCustomObjectFormatterEnabled(true); WebInspector.moduleSetting("customFormatters").addChangeListener(this._customFormattersStateChanged.bind(this));}WebInspector.RuntimeModel.Events = { ExecutionContextCreated: "ExecutionContextCreated", ExecutionContextDestroyed: "ExecutionContextDestroyed",}WebInspector.RuntimeModel._privateScript = "private script";WebInspector.RuntimeModel.prototype = { executionContexts: function() { return Object.values(this._executionContextById); }, _executionContextCreated: function(context) { if (context.name == WebInspector.RuntimeModel._privateScript && !context.origin && !Runtime.experiments.isEnabled("privateScriptInspection")) { return; } var executionContext = new WebInspector.ExecutionContext(this.target(),context.id,context.name,context.origin,!context.type,context.frameId); this._executionContextById[executionContext.id] = executionContext; this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.ExecutionContextCreated, executionContext); }, _executionContextDestroyed: function(executionContextId) { var executionContext = this._executionContextById[executionContextId]; if (!executionContext) return; 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,payload.customPreview); }, 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)); }, _customFormattersStateChanged: function(event) { var enabled = (event.data); this._agent.setCustomObjectFormatterEnabled(enabled); }, __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, origin, isPageContext, frameId) { WebInspector.SDKObject.call(this, target); this.id = id; this.name = name; this.origin = origin; this.isMainWorldContext = isPageContext; this.runtimeModel = target.runtimeModel; this.debuggerModel = WebInspector.DebuggerModel.fromTarget(target); this.frameId = frameId;}WebInspector.ExecutionContext.comparator = function(a, b) { function targetWeight(target) { if (target.isPage()) return 3; if (target.isDedicatedWorker()) return 2; return 1; } var weightDiff = targetWeight(a.target()) - targetWeight(b.target()); if (weightDiff) return -weightDiff; var frameIdDiff = String.hashCode(a.frameId) - String.hashCode(b.frameId); if (frameIdDiff) return frameIdDiff; 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; } this._evaluateGlobal.apply(this, arguments); }, globalObject: function(objectGroup, returnByValue, generatePreview, callback) { this._evaluateGlobal("this", objectGroup, false, true, returnByValue, generatePreview, callback); }, _evaluateGlobal: function(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback) { 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.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.selectedCallFrame().variableNames(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(type) { var object; if (type === "string") object = new String(""); else if (type === "number") object = new Number(0); else if (type === "boolean") object = new Boolean(false); else object = this; var resultSet = {}; for (var o = object; o; o = o.__proto__) { try { if (type === "array" && o === object && ArrayBuffer.isView(o) && o.length > 9999) continue;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, [WebInspector.RemoteObject.toCallArgument(result.subtype)], 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.split("\n").join("\\n")); } completionsReadyCallback(results); }, __proto__: WebInspector.SDKObject.prototype}WebInspector.EventListener = function(debuggerModel, payload, objectId) { WebInspector.SDKObject.call(this, debuggerModel.target()); this._type = payload.type; this._useCapture = payload.useCapture; this._location = WebInspector.DebuggerModel.Location.fromPayload(debuggerModel, payload.location); this._handler = payload.handler ? this.target().runtimeModel.createRemoteObject(payload.handler) : null ; var script = debuggerModel.scriptForId(payload.location.scriptId); this._sourceName = script ? script.contentURL() : ""; this._objectId = objectId;}WebInspector.EventListener.prototype = { type: function() { return this._type; }, useCapture: function() { return this._useCapture; }, location: function() { return this._location; }, handler: function() { return this._handler; }, sourceName: function() { return this._sourceName; }, objectId: function() { return this._objectId; }, __proto__: WebInspector.SDKObject.prototype};WebInspector.Script = function(debuggerModel, scriptId, sourceURL, startLine, startColumn, endLine, endColumn, isContentScript, isInternalScript, sourceMapURL, hasSourceURL) { WebInspector.SDKObject.call(this, debuggerModel.target()); this.debuggerModel = debuggerModel; this.scriptId = scriptId; this.sourceURL = sourceURL; this.lineOffset = startLine; this.columnOffset = startColumn; this.endLine = endLine; this.endColumn = endColumn; this._isContentScript = isContentScript; this._isInternalScript = isInternalScript; this.sourceMapURL = sourceMapURL; this.hasSourceURL = hasSourceURL;}WebInspector.Script.Events = { ScriptEdited: "ScriptEdited", SourceMapURLAdded: "SourceMapURLAdded",}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; }, isInternalScript: function() { return this._isInternalScript; }, 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); callback([]); return; } 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.debuggerModel,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; }, isInlineScriptWithSourceURL: function() { return !!this.hasSourceURL && this.isInlineScript(); }, __proto__: WebInspector.SDKObject.prototype};WebInspector.ServiceWorkerCacheModel = function(target) { WebInspector.SDKModel.call(this, WebInspector.ServiceWorkerCacheModel, target); this._caches = new Map(); this._agent = target.cacheStorageAgent(); this._enabled = false;}WebInspector.ServiceWorkerCacheModel.EventTypes = { CacheAdded: "CacheAdded", CacheRemoved: "CacheRemoved"}WebInspector.ServiceWorkerCacheModel.prototype = { enable: function() { if (this._enabled) return; this.target().resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginAdded, this._securityOriginAdded, this); this.target().resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginRemoved, this._securityOriginRemoved, this); var securityOrigins = this.target().resourceTreeModel.securityOrigins(); for (var i = 0; i < securityOrigins.length; ++i) this._addOrigin(securityOrigins[i]); this._enabled = true; }, refreshCacheNames: function() { var securityOrigins = this.target().resourceTreeModel.securityOrigins(); for (var securityOrigin of securityOrigins) this._loadCacheNames(securityOrigin); }, deleteCache: function(cache) { function callback(error) { if (error) { console.error("ServiceWorkerCacheAgent error deleting cache ", cache.toString(), ": ", error); return; } this._caches.delete(cache.cacheId); this._cacheRemoved(cache); } this._agent.deleteCache(cache.cacheId, callback.bind(this)); }, deleteCacheEntry: function(cache, request, callback) { function myCallback(error) { if (error) { WebInspector.console.error(WebInspector.UIString("ServiceWorkerCacheAgent error deleting cache entry %s in cache: %s", cache.toString(), error)); return; } callback(); } this._agent.deleteEntry(cache.cacheId, request, myCallback); }, loadCacheData: function(cache, skipCount, pageSize, callback) { this._requestEntries(cache, skipCount, pageSize, callback); }, caches: function() { var caches = new Array(); for (var cache of this._caches.values()) caches.push(cache); return caches; }, dispose: function() { for (var cache of this._caches.values()) this._cacheRemoved(cache); this._caches.clear(); if (this._enabled) { this.target().resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginAdded, this._securityOriginAdded, this); this.target().resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.SecurityOriginRemoved, this._securityOriginRemoved, this); } }, _addOrigin: function(securityOrigin) { this._loadCacheNames(securityOrigin); }, _removeOrigin: function(securityOrigin) { for (var opaqueId of this._caches.keys()) { var cache = this._caches.get(opaqueId); if (cache.securityOrigin == securityOrigin) { this._caches.delete(opaqueId); this._cacheRemoved(cache); } } }, _loadCacheNames: function(securityOrigin) { function callback(error, caches) { if (error) { console.error("ServiceWorkerCacheAgent error while loading caches: ", error); return; } this._updateCacheNames(securityOrigin, caches); } this._agent.requestCacheNames(securityOrigin, callback.bind(this)); }, _updateCacheNames: function(securityOrigin, cachesJson) { function deleteAndSaveOldCaches(cache) { if (cache.securityOrigin == securityOrigin && !updatingCachesIds.has(cache.cacheId)) { oldCaches.set(cache.cacheId, cache); this._caches.delete(cache.cacheId); } } var updatingCachesIds = new Set(); var newCaches = new Map(); var oldCaches = new Map(); for (var cacheJson of cachesJson) { var cache = new WebInspector.ServiceWorkerCacheModel.Cache(cacheJson.securityOrigin,cacheJson.cacheName,cacheJson.cacheId); updatingCachesIds.add(cache.cacheId); if (this._caches.has(cache.cacheId)) continue;newCaches.set(cache.cacheId, cache); this._caches.set(cache.cacheId, cache); } this._caches.forEach(deleteAndSaveOldCaches, this); newCaches.forEach(this._cacheAdded, this); oldCaches.forEach(this._cacheRemoved, this); }, _securityOriginAdded: function(event) { var securityOrigin = (event.data); this._addOrigin(securityOrigin); }, _securityOriginRemoved: function(event) { var securityOrigin = (event.data); this._removeOrigin(securityOrigin); }, _cacheAdded: function(cache) { this.dispatchEventToListeners(WebInspector.ServiceWorkerCacheModel.EventTypes.CacheAdded, cache); }, _cacheRemoved: function(cache) { this.dispatchEventToListeners(WebInspector.ServiceWorkerCacheModel.EventTypes.CacheRemoved, cache); }, _requestEntries: function(cache, skipCount, pageSize, callback) { function innerCallback(error, dataEntries, hasMore) { if (error) { console.error("ServiceWorkerCacheAgent error while requesting entries: ", error); return; } var entries = []; for (var i = 0; i < dataEntries.length; ++i) { entries.push(new WebInspector.ServiceWorkerCacheModel.Entry(dataEntries[i].request,dataEntries[i].response)); } callback(entries, hasMore); } this._agent.requestEntries(cache.cacheId, skipCount, pageSize, innerCallback); }, __proto__: WebInspector.SDKModel.prototype}WebInspector.ServiceWorkerCacheModel.Entry = function(request, response) { this.request = request; this.response = response;}WebInspector.ServiceWorkerCacheModel.Cache = function(securityOrigin, cacheName, cacheId) { this.securityOrigin = securityOrigin; this.cacheName = cacheName; this.cacheId = cacheId;}WebInspector.ServiceWorkerCacheModel.Cache.prototype = { equals: function(cache) { return this.cacheId == cache.cacheId; }, toString: function() { return this.securityOrigin + this.cacheName; }}WebInspector.ServiceWorkerCacheModel._symbol = Symbol("CacheStorageModel");WebInspector.ServiceWorkerCacheModel.fromTarget = function(target) { if (!target[WebInspector.ServiceWorkerCacheModel._symbol]) target[WebInspector.ServiceWorkerCacheModel._symbol] = new WebInspector.ServiceWorkerCacheModel(target); return target[WebInspector.ServiceWorkerCacheModel._symbol];};WebInspector.RemoteObject = function() {}WebInspector.RemoteObject.prototype = { customPreview: function() { return null ; }, 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"; }, eventListeners: function() { 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"); }, debuggerModel: function() { throw new Error("DebuggerModel-less object"); }, isNode: function() { return false; }, functionDetails: function(callback) { callback(null ); }, generatorObjectDetails: function(callback) { callback(null ); }, collectionEntries: 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.arrayLength = function(object) { if (object.subtype !== "array") return 0; var matches = object.description.match(/\[([0-9]+)\]/); if (!matches) return 0; return parseInt(matches[1], 10);}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, customPreview) { WebInspector.RemoteObject.call(this); this._target = target; this._runtimeAgent = target.runtimeAgent(); this._debuggerModel = WebInspector.DebuggerModel.fromTarget(target); this._type = type; this._subtype = subtype; if (objectId) { this._objectId = objectId; this._description = description; this._hasChildren = (type !== "symbol"); this._preview = preview; } else { this._description = description || (value + ""); this._hasChildren = false; if (type === "number" && typeof value !== "number") this.value = Number(value); else this.value = value; } this._customPreview = customPreview || null ;}WebInspector.RemoteObjectImpl.prototype = { customPreview: function() { return this._customPreview; }, 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, false, callback); }, getAllProperties: function(accessorPropertiesOnly, callback) { this.doGetProperties(false, accessorPropertiesOnly, false, callback); }, eventListeners: function() { return new Promise(eventListeners.bind(this)); function eventListeners(fulfill, reject) { if (!this._objectId) { reject(null ); return; } this.target().domdebuggerAgent().getEventListeners(this._objectId, mycallback.bind(this)); function mycallback(error, payloads) { if (error) { reject(null ); return; } fulfill(payloads.map(createEventListener.bind(this))); } function createEventListener(payload) { return new WebInspector.EventListener(this._debuggerModel,payload,this._objectId); } } }, 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, generatePreview, callback) { if (!this._objectId) { callback(null , null ); return; } function remoteObjectBinder(error, properties, internalProperties, exceptionDetails) { if (error) { callback(null , null ); return; } if (exceptionDetails) { var msg = new WebInspector.ConsoleMessage(this._target,WebInspector.ConsoleMessage.MessageSource.JS,WebInspector.ConsoleMessage.MessageLevel.Error,exceptionDetails.text); this._target.consoleModel.addMessage(msg); 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, generatePreview, 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; } if (typeof name === "string") name = WebInspector.RemoteObject.toCallArgument(name); 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(); } }, 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() { return WebInspector.RemoteObject.arrayLength(this); }, target: function() { return this._target; }, debuggerModel: function() { return this._debuggerModel; }, isNode: function() { return !!this._objectId && this.type === "object" && this.subtype === "node"; }, functionDetails: function(callback) { this._debuggerModel.functionDetails(this, callback); }, generatorObjectDetails: function(callback) { this._debuggerModel.generatorObjectDetails(this, callback); }, collectionEntries: function(callback) { if (!this._objectId) { callback(null ); return; } this._debuggerModel.getCollectionEntries(this._objectId, callback); }, __proto__: WebInspector.RemoteObject.prototype};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;};WebInspector.ScopeRemoteObject.prototype = { doGetProperties: function(ownProperties, accessorPropertiesOnly, generatePreview, callback) { if (accessorPropertiesOnly) { callback([], []); return; } if (this._savedScopeProperties) { callback(this._savedScopeProperties.slice(), []); return; } function wrappedCallback(properties, internalProperties) { if (this._scopeRef && Array.isArray(properties)) this._savedScopeProperties = properties.slice(); callback(properties, internalProperties); } generatePreview = true; WebInspector.RemoteObjectImpl.prototype.doGetProperties.call(this, ownProperties, accessorPropertiesOnly, generatePreview, wrappedCallback.bind(this)); }, doSetObjectPropertyValue: function(result, name, callback) { this._debuggerModel.setVariableValue(this._scopeRef.number, (name.value), 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 this._formatValue(property.value); } function formatObjectItem(property) { var name = property.name; if (/^\s|\s$|^$|\n/.test(name)) name = "\"" + name.replace(/\n/g, "\u21B5") + "\""; return name + ": " + this._formatValue(property.value); } if (this.type === "object") { switch (this.subtype) { case "array": this._cachedDescription = this._concatenate("[", "]", formatArrayItem.bind(this)); break; case "date": this._cachedDescription = "" + this._value; break; case "null": this._cachedDescription = "null"; break; default: this._cachedDescription = this._concatenate("{", "}", formatObjectItem.bind(this)); } } else { this._cachedDescription = String(this._value); } return this._cachedDescription; }, _formatValue: function(value) { if (!value) return "undefined"; var description = value.description || ""; if (value.type === "string") return "\"" + description.replace(/\n/g, "\u21B5") + "\""; return description; }, _concatenate: function(prefix, suffix, formatProperty) { var 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 (Array.isArray(this._value)) 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(), null ); }, 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) { var propValue = value[propName]; if (!(propValue instanceof WebInspector.RemoteObject)) propValue = WebInspector.RemoteObject.fromLocalObject(propValue); return new WebInspector.RemoteObjectProperty(propName,propValue); } if (!this._cachedChildren) this._cachedChildren = Object.keys(value).map(buildProperty); return this._cachedChildren; }, isError: function() { return false; }, arrayLength: function() { return Array.isArray(this._value) ? 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.MapEntryLocalJSONObject = function(value) { WebInspector.LocalJSONObject.call(this, value);}WebInspector.MapEntryLocalJSONObject.prototype = { get description() { if (!this._cachedDescription) { var children = this._children(); this._cachedDescription = "{" + this._formatValue(children[0].value) + " => " + this._formatValue(children[1].value) + "}"; } return this._cachedDescription; }, __proto__: WebInspector.LocalJSONObject.prototype};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, charset) { const maxDataUrlSize = 1024 * 1024; if (content === null || content.length > maxDataUrlSize) return null ; return "data:" + mimeType + (charset ? ";charset=" + charset : "") + (contentEncoded ? ";base64" : "") + "," + content;}WebInspector.Resource.populateImageSource = function(url, mimeType, contentProvider, image) { function onResourceContent(content) { var imageSrc = WebInspector.Resource.contentAsDataURL(content, mimeType, true); if (imageSrc === null ) imageSrc = url; image.src = imageSrc; } contentProvider.requestContent(onResourceContent);}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; }, resourceType: function() { return this._request ? this._request.resourceType() : 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.resourceType(); }, 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.resourceType().canonicalMimeType() || this.mimeType; }, searchInContent: function(query, caseSensitive, isRegex, callback) { function callbackWrapper(error, searchMatches) { callback(searchMatches || []); } if (this.resourceType() === 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) { WebInspector.Resource.populateImageSource(this._url, this._mimeType, this, image); }, _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; }, hasTextContent: function() { if (this._type.isTextType()) return true; if (this._type === WebInspector.resourceTypes.Other) return !!this._content && !this._contentEncoded; return false; }, __proto__: WebInspector.SDKObject.prototype};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", ColorPicked: "ColorPicked"}WebInspector.ResourceTreeModel.frames = function() { var result = []; for (var target of WebInspector.targetManager.targets()) result = result.concat(Object.values(target.resourceTreeModel._frames)); return result;}WebInspector.ResourceTreeModel.resourceForURL = function(url) { for (var target of WebInspector.targetManager.targets()) { var mainFrame = target.resourceTreeModel.mainFrame; var result = mainFrame ? mainFrame.resourceForURL(url) : null ; if (result) return result; } return null ;}WebInspector.ResourceTreeModel.prototype = { _fetchResourceTree: function() { this._frames = {}; this._cachedResourcesProcessed = false; this._agent.getResourceTree(this._processCachedResources.bind(this)); }, _processCachedResources: function(error, mainFramePayload) { if (error) { if (this.target().isPage() || this.target().isServiceWorker()) console.error(JSON.stringify(error)); this._cachedResourcesProcessed = true; return; } this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.WillLoadCachedResources); this._inspectedPageURL = mainFramePayload.frame.url; if (this.target().isPage()) this._addFramesRecursively(null , mainFramePayload); else this._addSecurityOrigin(mainFramePayload.frame.securityOrigin); this._dispatchInspectedURLChanged(); this._cachedResourcesProcessed = true; this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded); }, 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, mainFrame); }, _frameAttached: function(frameId, parentFrameId) { if (!this._cachedResourcesProcessed && parentFrameId) 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 && framePayload.parentId) 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.resourceType() === 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) { this.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.WillReloadPage); this._agent.reload(ignoreCache, scriptToEvaluateOnLoad); }, __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.resourceType(),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, dialogType) {}, javascriptDialogClosed: function(result) {}, screencastFrame: function(data, metadata, frameNumber) { this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ScreencastFrame, { data: data, metadata: metadata, frameNumber: frameNumber }); }, screencastVisibilityChanged: function(visible) { this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ScreencastVisibilityChanged, { visible: visible }); }, colorPicked: function(color) { this._resourceTreeModel.dispatchEventToListeners(WebInspector.ResourceTreeModel.EventTypes.ColorPicked, color); }, interstitialShown: function() {}, interstitialHidden: function() {}};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 parsedURL = new WebInspector.ParsedURL(sourceMapURL); if (parsedURL.isDataURL()) { var xhr = new XMLHttpRequest(); xhr.open("GET", sourceMapURL, false); xhr.send(null ); contentLoaded(xhr.status, {}, xhr.responseText); return; } WebInspector.ResourceLoader.loadUsingTargetUA(sourceMapURL, null , contentLoaded); function contentLoaded(statusCode, headers, content) { if (!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]; if (!mappings) return null ; 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.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.moduleSetting("cacheDisabled").get()) this._networkAgent.setCacheDisabled(true); if (WebInspector.moduleSetting("monitoringXHREnabled").get()) this._networkAgent.setMonitoringXHREnabled(true); this._initNetworkConditions(); this._networkAgent.enable(); WebInspector.moduleSetting("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 }, "image/svg+xml": { "document": true }, "text/css": { "stylesheet": true }, "text/xsl": { "stylesheet": true }, "text/vtt": { "texttrack": true },}WebInspector.NetworkManager.Conditions;WebInspector.NetworkManager.IsThrottlingEnabled = function(conditions) { return conditions.throughput >= 0;}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.moduleSetting("cacheDisabled").removeChangeListener(this._cacheDisabledSettingChanged, this); }, clearBrowserCache: function() { this._networkAgent.clearBrowserCache(); }, clearBrowserCookies: function() { this._networkAgent.clearBrowserCookies(); }, _initNetworkConditions: function() { this._networkAgent.canEmulateNetworkConditions(callback.bind(this)); function callback(error, canEmulate) { if (error || !canEmulate) return; WebInspector.moduleSetting("networkConditions").addChangeListener(this._networkConditionsSettingChanged, this); var conditions = WebInspector.moduleSetting("networkConditions").get(); if (conditions.throughput < 0) return; this._updateNetworkConditions(conditions); } }, _updateNetworkConditions: function(conditions) { if (conditions.throughput < 0) { this._networkAgent.emulateNetworkConditions(false, 0, 0, 0); } else { var offline = !conditions.throughput && !conditions.latency; this._networkAgent.emulateNetworkConditions(!!offline, conditions.latency, conditions.throughput, conditions.throughput); } }, _networkConditionsSettingChanged: function(event) { this._updateNetworkConditions((event.data)); }, __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 = String(response.connectionId); if (response.remoteIPAddress) networkRequest.setRemoteAddress(response.remoteIPAddress, response.remotePort || -1); if (response.fromServiceWorker) networkRequest.fetchedViaServiceWorker = true; if (response.fromDiskCache) networkRequest.setFromDiskCache(); networkRequest.timing = response.timing; networkRequest.protocol = response.protocol; 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.resourceType().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; var resourceType = networkRequest.resourceType(); if (resourceType !== WebInspector.resourceTypes.Stylesheet && resourceType !== WebInspector.resourceTypes.Document && resourceType !== WebInspector.resourceTypes.TextTrack) { return true; } if (!networkRequest.mimeType) return true; if (networkRequest.mimeType in WebInspector.NetworkManager._MIMETypes) return resourceType.name() in WebInspector.NetworkManager._MIMETypes[networkRequest.mimeType]; return false; }, requestWillBeSent: function(requestId, frameId, loaderId, documentURL, request, time, wallTime, initiator, redirectResponse, resourceType) { 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.setIssueTime(time, wallTime); networkRequest.setResourceType(WebInspector.resourceTypes[resourceType]); this._startNetworkRequest(networkRequest); }, requestServedFromCache: function(requestId) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.setFromMemoryCache(); }, 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.setResourceType(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.setResourceType(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,"","","",null ); networkRequest.setResourceType(WebInspector.resourceTypes.WebSocket); this._startNetworkRequest(networkRequest); }, webSocketWillSendHandshakeRequest: function(requestId, time, wallTime, request) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.requestMethod = "GET"; networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers)); networkRequest.setIssueTime(time, wallTime); 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; networkRequest.protocol = "websocket"; 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); }, eventSourceMessageReceived: function(requestId, time, eventName, eventId, data) { var networkRequest = this._inflightRequestsById[requestId]; if (!networkRequest) return; networkRequest.addEventSourceMessage(time, eventName, eventId, data); }, _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) { return new WebInspector.NetworkRequest(this._manager._target,requestId,url,documentURL,frameId,loaderId,initiator); }}WebInspector.MultitargetNetworkManager = function() { WebInspector.targetManager.observeTargets(this);}WebInspector.MultitargetNetworkManager.prototype = { targetAdded: function(target) { var networkAgent = target.networkAgent(); if (this._extraHeaders) networkAgent.setExtraHTTPHeaders(this._extraHeaders); if (typeof this._userAgent !== "undefined") networkAgent.setUserAgentOverride(this._userAgent); }, targetRemoved: function(target) {}, setExtraHTTPHeaders: function(headers) { this._extraHeaders = headers; for (var target of WebInspector.targetManager.targets()) target.networkAgent().setExtraHTTPHeaders(this._extraHeaders); }, setUserAgentOverride: function(userAgent) { WebInspector.ResourceLoader.targetUserAgent = userAgent; this._userAgent = userAgent; for (var target of WebInspector.targetManager.targets()) target.networkAgent().setUserAgentOverride(this._userAgent); }}WebInspector.multitargetNetworkManager;;WebInspector.NetworkRequest = function(target, requestId, url, documentURL, frameId, loaderId, initiator) { WebInspector.SDKObject.call(this, target); this._requestId = requestId; this.url = url; this._documentURL = documentURL; this._frameId = frameId; this._loaderId = loaderId; this._initiator = initiator; this._issueTime = -1; this._startTime = -1; this._endTime = -1; this.statusCode = 0; this.statusText = ""; this.requestMethod = ""; this.requestTime = 0; this.protocol = ""; this._resourceType = WebInspector.resourceTypes.Other; this._contentEncoded = false; this._pendingContentCallbacks = []; this._frames = []; this._eventSourceMessages = []; this._responseHeaderValues = {}; this._remoteAddress = ""; this.connectionId = "0";}WebInspector.NetworkRequest.Events = { FinishedLoading: "FinishedLoading", TimingChanged: "TimingChanged", RemoteAddressChanged: "RemoteAddressChanged", RequestHeadersChanged: "RequestHeadersChanged", ResponseHeadersChanged: "ResponseHeadersChanged", WebsocketFrameAdded: "WebsocketFrameAdded", EventSourceMessageAdded: "EventSourceMessageAdded",}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.EventSourceMessage;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; }, setIssueTime: function(monotonicTime, wallTime) { this._issueTime = monotonicTime; this._wallIssueTime = wallTime; this._startTime = monotonicTime; }, issueTime: function() { return this._issueTime; }, pseudoWallTime: function(monotonicTime) { return this._wallIssueTime ? this._wallIssueTime - this._issueTime + monotonicTime : monotonicTime; }, 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; }, cached: function() { return (!!this._fromMemoryCache || !!this._fromDiskCache) && !this._transferSize; }, setFromMemoryCache: function() { this._fromMemoryCache = true; delete this._timing; }, setFromDiskCache: function() { this._fromDiskCache = true; }, get fetchedViaServiceWorker() { return this._fetchedViaServiceWorker; }, set fetchedViaServiceWorker(x) { this._fetchedViaServiceWorker = x; }, get timing() { return this._timing; }, set timing(x) { if (x && !this._fromMemoryCache) { 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) : ""; }, resourceType: function() { return this._resourceType; }, setResourceType: function(resourceType) { this._resourceType = resourceType; }, 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.target(), 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.target(), 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._resourceType; }, requestContent: function(callback) { if (this._resourceType === 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"); }, hasErrorStatusCode: function() { return this.statusCode >= 400; }, populateImageSource: function(image) { WebInspector.Resource.populateImageSource(this._url, this._mimeType, this, image); }, asDataURL: function() { var content = this._content; var charset = null ; if (!this._contentEncoded) { content = content.toBase64(); charset = "utf-8"; } return WebInspector.Resource.contentAsDataURL(content, this.mimeType, true, charset); }, _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; } this.target().networkAgent().getResponseBody(this._requestId, onResourceContent.bind(this)); }, initiator: function() { return this._initiator; }, initiatorInfo: function() { if (this._initiatorInfo) return this._initiatorInfo; var type = WebInspector.NetworkRequest.InitiatorType.Other; var url = ""; var lineNumber = -Infinity; var columnNumber = -Infinity; var initiator = this._initiator; if (this.redirectSource) { type = WebInspector.NetworkRequest.InitiatorType.Redirect; url = this.redirectSource.url; } else if (initiator) { if (initiator.type === NetworkAgent.InitiatorType.Parser) { type = WebInspector.NetworkRequest.InitiatorType.Parser; url = initiator.url ? initiator.url : url; lineNumber = initiator.lineNumber ? initiator.lineNumber : lineNumber; } else if (initiator.type === NetworkAgent.InitiatorType.Script) { var topFrame = 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._addFrame({ type: WebInspector.NetworkRequest.WebSocketFrameType.Error, text: errorMessage, time: this.pseudoWallTime(time), opCode: -1, mask: false }); }, addFrame: function(response, time, sent) { var type = sent ? WebInspector.NetworkRequest.WebSocketFrameType.Send : WebInspector.NetworkRequest.WebSocketFrameType.Receive; this._addFrame({ type: type, text: response.payloadData, time: this.pseudoWallTime(time), opCode: response.opcode, mask: response.mask }); }, _addFrame: function(frame) { this._frames.push(frame); this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.WebsocketFrameAdded, frame); }, eventSourceMessages: function() { return this._eventSourceMessages; }, addEventSourceMessage: function(time, eventName, eventId, data) { var message = { time: this.pseudoWallTime(time), eventName: eventName, eventId: eventId, data: data }; this._eventSourceMessages.push(message); this.dispatchEventToListeners(WebInspector.NetworkRequest.Events.EventSourceMessageAdded, message); }, replayXHR: function() { this.target().networkAgent().replayXHR(this.requestId); }, __proto__: WebInspector.SDKObject.prototype};WebInspector.PictureFragment;WebInspector.PaintProfilerSnapshot = function(target, snapshotId) { this._target = target; this._id = snapshotId;}WebInspector.PaintProfilerSnapshot.loadFromFragments = function(target, fragments, callback) { var wrappedCallback = InspectorBackend.wrapClientCallback(callback, "LayerTreeAgent.loadSnapshot(): ", WebInspector.PaintProfilerSnapshot.bind(null , target)); target.layerTreeAgent().loadSnapshot(fragments, wrappedCallback);}WebInspector.PaintProfilerSnapshot.load = function(target, encodedPicture, callback) { var fragment = { x: 0, y: 0, picture: encodedPicture }; WebInspector.PaintProfilerSnapshot.loadFromFragments(target, [fragment], callback);}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(clipRect, callback) { var wrappedCallback = InspectorBackend.wrapClientCallback(callback, "LayerTreeAgent.profileSnapshot(): "); this._target.layerTreeAgent().profileSnapshot(this._id, 5, 1, clipRect || undefined, 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.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.CSSMetadata.initializeWithSupportedProperties([{ "name": "color"}, { "name": "direction"}, { "name": "font-family"}, { "name": "font-kerning"}, { "name": "font-size"}, { "name": "font-size-adjust"}, { "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": "align-content"}, { "name": "align-items"}, { "name": "alignment-baseline"}, { "name": "align-self"}, { "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": "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": "cx"}, { "name": "cy"}, { "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": "line-height"}, { "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": "motion-offset"}, { "name": "motion-path"}, { "name": "motion-rotation"}, { "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": "r"}, { "name": "rx"}, { "name": "ry"}, { "name": "scroll-behavior"}, { "name": "scroll-blocks-on"}, { "name": "scroll-snap-type"}, { "name": "scroll-snap-points-x"}, { "name": "scroll-snap-points-y"}, { "name": "scroll-snap-destination"}, { "name": "scroll-snap-coordinate"}, { "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": "transform"}, { "name": "transform-origin"}, { "name": "transform-style"}, { "name": "translate"}, { "name": "rotate"}, { "name": "scale"}, { "name": "transition-delay"}, { "name": "transition-duration"}, { "name": "transition-property"}, { "name": "transition-timing-function"}, { "name": "unicode-bidi"}, { "name": "vector-effect"}, { "name": "vertical-align"}, { "name": "visibility"}, { "name": "x"}, { "name": "y"}, { "name": "-webkit-appearance"}, { "name": "-webkit-app-region"}, { "name": "-webkit-background-clip"}, { "name": "-webkit-background-composite"}, { "name": "-webkit-background-origin"}, { "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-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-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-origin-x"}, { "name": "-webkit-transform-origin-y"}, { "name": "-webkit-transform-origin-z"}, { "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": "-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": "enable-background"}, { "name": "max-zoom"}, { "name": "min-zoom"}, { "name": "orientation"}, { "name": "page"}, { "name": "src"}, { "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": ["font-style", "font-variant", "font-weight", "font-stretch", "font-size", "line-height", "font-family"], "name": "font"}, { "longhands": ["grid-template-columns", "grid-template-rows", "grid-template-areas", "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": ["motion-path", "motion-offset", "motion-rotation"], "name": "motion"}, { "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-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": ["-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"}]);;WebInspector.ExcludedFolderManager = function() { WebInspector.Object.call(this); this._excludedFoldersSetting = WebInspector.settings.createLocalSetting("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("|"); this._workspaceFolderExcludePatternSetting = WebInspector.settings.createRegExpSetting("workspaceFolderExcludePattern", defaultExcludedFoldersPattern, WebInspector.isWin() ? "i" : ""); this._excludedFolders = {}; this._loadFromSettings();}WebInspector.ExcludedFolderManager.Events = { ExcludedFolderAdded: "ExcludedFolderAdded", ExcludedFolderRemoved: "ExcludedFolderRemoved"}WebInspector.ExcludedFolderManager.prototype = { workspaceFolderExcludePatternSetting: function() { return this._workspaceFolderExcludePatternSetting; }, _loadFromSettings: function() { 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.ExcludedFolderManager.Entry(savedEntry.fileSystemPath,savedEntry.path); excludedFolders.push(entry); } } }, _saveToSettings: function() { var savedExcludedFolders = this._excludedFolders; this._excludedFoldersSetting.set(savedExcludedFolders); }, addExcludedFolder: function(fileSystemPath, excludedFolderPath) { if (!this._excludedFolders[fileSystemPath]) this._excludedFolders[fileSystemPath] = []; var entry = new WebInspector.ExcludedFolderManager.Entry(fileSystemPath,excludedFolderPath); this._excludedFolders[fileSystemPath].push(entry); this._saveToSettings(); this.dispatchEventToListeners(WebInspector.ExcludedFolderManager.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.ExcludedFolderManager.Events.ExcludedFolderRemoved, entry); }, removeFileSystem: function(fileSystemPath) { delete this._excludedFolders[fileSystemPath]; this._saveToSettings(); }, _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 ; }, 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 = this._workspaceFolderExcludePatternSetting.asRegExp(); return !!(regex && regex.test(folderPath)); }, excludedFolders: function(fileSystemPath) { var excludedFolders = this._excludedFolders[fileSystemPath]; return excludedFolders ? excludedFolders.slice() : []; }, __proto__: WebInspector.Object.prototype}WebInspector.ExcludedFolderManager.Entry = function(fileSystemPath, path) { this.fileSystemPath = fileSystemPath; this.path = path;};WebInspector.FileManager = function() { this._savedURLsSetting = WebInspector.settings.createLocalSetting("savedURLs", {}); 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 = { save: function(url, content, forceSaveAs, callback) { var savedURLs = this._savedURLsSetting.get(); delete savedURLs[url]; this._savedURLsSetting.set(savedURLs); this._saveCallbacks[url] = callback || null ; InspectorFrontendHost.save(url, content, forceSaveAs); }, _savedURL: function(event) { var url = (event.data); var savedURLs = this._savedURLsSetting.get(); savedURLs[url] = true; this._savedURLsSetting.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 = this._savedURLsSetting.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 = null ;;WebInspector.FileSystemMapping = function() { WebInspector.Object.call(this); this._fileSystemMappingSetting = WebInspector.settings.createLocalSetting("fileSystemMapping", {}); this._fileSystemMappings = {}; this._loadFromSettings();}WebInspector.FileSystemMapping.Events = { FileMappingAdded: "FileMappingAdded", FileMappingRemoved: "FileMappingRemoved"}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); } } this._rebuildIndexes(); }, _saveToSettings: function() { var savedMapping = this._fileSystemMappings; this._fileSystemMappingSetting.set(savedMapping); 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]; 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); }, 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 ; }, _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 ; }, 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.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.excludedFolderManager().isFileExcluded(this._path, entry.fullPath)) continue;fileCallback(entry.fullPath.substr(1)); } else { if (this._manager.excludedFolderManager().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() { var string = null ; try { string = (this.result); } catch (e) { console.error("Can't read file: " + path + ": " + e); } callback(string); } 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 = fileWritten; var blob = new Blob([content],{ type: "text/plain" }); fileWriter.write(blob); function fileWritten() { fileWriter.onwriteend = writerEnd; fileWriter.truncate(blob.size); } } 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; 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._excludedFolderManager = new WebInspector.ExcludedFolderManager(); 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; }, excludedFolderManager: function() { return this._excludedFolderManager; }, _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"]); if (errorMessage) WebInspector.console.error(errorMessage, true); else if (fileSystem) this._innerAddFileSystem(fileSystem); }, _onFileSystemRemoved: function(event) { this._fileSystemRemoved((event.data)); }, _fileSystemRemoved: function(fileSystemPath) { this._fileSystemMapping.removeFileSystem(fileSystemPath); this._excludedFolderManager.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.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 = "-?f(ile)?:(([^\\\\ ]|\\\\.)+)"; var quotedPattern = "\"(([^\\\\\"]|\\\\.)+)\""; var unquotedWordPattern = "((?!-?f(ile)?:)[^\\\\ ]|\\\\.)+"; 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(/^(-)?f(ile)?:/); 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.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.history = [];}WebInspector.UISourceCode.Events = { WorkingCopyChanged: "WorkingCopyChanged", WorkingCopyCommitted: "WorkingCopyCommitted", TitleChanged: "TitleChanged", SavedStateUpdated: "SavedStateUpdated", SourceMappingChanged: "SourceMappingChanged",}WebInspector.UISourceCode.prototype = { networkURL: function() { 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.url()) return path; if (!path) return this._project.url(); return this._project.url() + "/" + 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) { this._savedWithFileManager = accepted; if (accepted) this._hasCommittedChanges = false; 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); } WebInspector.userMetrics.RevisionApplied.record(); this.requestOriginalContent(callback.bind(this)); }, revertAndClearHistory: function(callback) { function revert(content) { if (typeof content !== "string") return; this.addRevision(content); this.history = []; callback(this); } WebInspector.userMetrics.RevisionApplied.record(); 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"; }, extension: 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); return extension; }, content: function() { return this._content; }, searchInContent: function(query, caseSensitive, isRegex, callback) { var content = this.content(); if (content) { WebInspector.StaticContentProvider.searchInContent(content, 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; }, uiLocation: function(lineNumber, columnNumber) { if (typeof columnNumber === "undefined") columnNumber = 0; return new WebInspector.UILocation(this,lineNumber,columnNumber); }, __proto__: WebInspector.Object.prototype}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.project().id() + ":" + this.uiSourceCode.uri() + ":" + this.lineNumber + ":" + this.columnNumber; }, toUIString: function() { return this.uiSourceCode.uri() + ":" + (this.lineNumber + 1); }}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); } WebInspector.userMetrics.RevisionApplied.record(); 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.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.Events = { FileAdded: "FileAdded", FileRemoved: "FileRemoved",}WebInspector.ProjectDelegate.prototype = { type: function() {}, displayName: function() {}, url: 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.Project = function(workspace, projectId, projectDelegate) { this._uiSourceCodesMap = new Map(); this._uiSourceCodesList = []; this._workspace = workspace; this._projectId = projectId; this._projectDelegate = projectDelegate; this._url = this._projectDelegate.url(); this._displayName = this._projectDelegate.displayName(); projectDelegate.addEventListener(WebInspector.ProjectDelegate.Events.FileAdded, this._fileAdded, this); projectDelegate.addEventListener(WebInspector.ProjectDelegate.Events.FileRemoved, this._fileRemoved, this);}WebInspector.Project.Events = { DisplayNameUpdated: "DisplayNameUpdated"};WebInspector.Project.prototype = { id: function() { return this._projectId; }, type: function() { return this._projectDelegate.type(); }, displayName: function() { return this._displayName; }, setDisplayName: function(displayName) { if (this._displayName === displayName) return; this._displayName = displayName; this.dispatchEventToListeners(WebInspector.Project.Events.DisplayNameUpdated); }, url: function() { return this._url; }, isServiceProject: function() { return this._projectDelegate.type() === WebInspector.projectTypes.Debugger || this._projectDelegate.type() === WebInspector.projectTypes.Formatter || this._projectDelegate.type() === WebInspector.projectTypes.Service; }, _fileAdded: function(event) { var fileDescriptor = (event.data); var path = fileDescriptor.parentPath ? fileDescriptor.parentPath + "/" + fileDescriptor.name : fileDescriptor.name; var uiSourceCode = this.uiSourceCode(path); if (uiSourceCode) return; uiSourceCode = new WebInspector.UISourceCode(this,fileDescriptor.parentPath,fileDescriptor.name,fileDescriptor.originURL,fileDescriptor.url,fileDescriptor.contentType); this._uiSourceCodesMap.set(path, { uiSourceCode: uiSourceCode, index: this._uiSourceCodesList.length }); this._uiSourceCodesList.push(uiSourceCode); this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.UISourceCodeAdded, uiSourceCode); }, _fileRemoved: function(event) { var path = (event.data); this._removeFile(path); }, _removeFile: function(path) { var uiSourceCode = this.uiSourceCode(path); if (!uiSourceCode) return; var entry = this._uiSourceCodesMap.get(path); var movedUISourceCode = this._uiSourceCodesList[this._uiSourceCodesList.length - 1]; this._uiSourceCodesList[entry.index] = movedUISourceCode; var movedEntry = this._uiSourceCodesMap.get(movedUISourceCode.path()); movedEntry.index = entry.index; this._uiSourceCodesList.splice(this._uiSourceCodesList.length - 1, 1); this._uiSourceCodesMap.delete(path); this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.UISourceCodeRemoved, entry.uiSourceCode); }, _remove: function() { this._projectDelegate.removeEventListener(WebInspector.ProjectDelegate.Events.FileAdded, this._fileAdded, this); this._projectDelegate.removeEventListener(WebInspector.ProjectDelegate.Events.FileRemoved, this._fileRemoved, this); this._workspace.dispatchEventToListeners(WebInspector.Workspace.Events.ProjectRemoved, this); this._uiSourceCodesMap = new Map(); this._uiSourceCodesList = []; }, workspace: function() { return this._workspace; }, uiSourceCode: function(path) { var entry = this._uiSourceCodesMap.get(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.networkURL(), 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; var value = (this._uiSourceCodesMap.get(oldPath)); this._uiSourceCodesMap.set(newPath, value); this._uiSourceCodesMap.delete(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); }, __proto__: WebInspector.Object.prototype}WebInspector.projectTypes = { Debugger: "debugger", Formatter: "formatter", Network: "network", Snippets: "snippets", FileSystem: "filesystem", ContentScripts: "contentscripts", Service: "service"}WebInspector.Workspace = function(fileSystemMapping) { this._fileSystemMapping = fileSystemMapping; this._projects = {}; this._hasResourceContentTrackingExtensions = false;}WebInspector.Workspace.Events = { UISourceCodeAdded: "UISourceCodeAdded", UISourceCodeRemoved: "UISourceCodeRemoved", UISourceCodeContentCommitted: "UISourceCodeContentCommitted", ProjectAdded: "ProjectAdded", ProjectRemoved: "ProjectRemoved"}WebInspector.Workspace.prototype = { unsavedSourceCodes: function() { function filterUnsaved(sourceCode) { return sourceCode.isDirty(); } var unsavedSourceCodes = []; var projects = this.projectsForType(WebInspector.projectTypes.FileSystem); for (var i = 0; i < projects.length; ++i) unsavedSourceCodes = unsavedSourceCodes.concat(projects[i].uiSourceCodes().filter(filterUnsaved)); return unsavedSourceCodes; }, 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; this.dispatchEventToListeners(WebInspector.Workspace.Events.ProjectAdded, project); return project; }, 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; }, setHasResourceContentTrackingExtensions: function(hasExtensions) { this._hasResourceContentTrackingExtensions = hasExtensions; }, hasResourceContentTrackingExtensions: function() { return this._hasResourceContentTrackingExtensions; }, __proto__: WebInspector.Object.prototype}WebInspector.workspace;;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.CompilerScriptMapping = function(debuggerModel, workspace, networkMapping, networkProject, debuggerWorkspaceBinding) { this._target = debuggerModel.target(); this._debuggerModel = debuggerModel; this._workspace = workspace; this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAddedToWorkspace, this); this._networkMapping = networkMapping; this._networkProject = networkProject; this._debuggerWorkspaceBinding = debuggerWorkspaceBinding; this._sourceMapForSourceMapURL = {}; this._pendingSourceMapLoadingCallbacks = {}; this._sourceMapForScriptId = {}; this._scriptForSourceMap = new Map(); this._sourceMapForURL = new Map(); this._stubUISourceCodes = new Map(); this._stubProjectID = "compiler-script-project"; this._stubProjectDelegate = new WebInspector.ContentProviderBasedProjectDelegate(this._workspace,this._stubProjectID,WebInspector.projectTypes.Service); debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this);}WebInspector.CompilerScriptMapping.prototype = { mapsToSourceCode: function(rawLocation) { var sourceMap = this._sourceMapForScriptId[rawLocation.scriptId]; if (!sourceMap) { return true; } return !!sourceMap.findEntry(rawLocation.lineNumber, rawLocation.columnNumber); }, rawLocationToUILocation: function(rawLocation) { var debuggerModelLocation = (rawLocation); var stubUISourceCode = this._stubUISourceCodes.get(debuggerModelLocation.scriptId); if (stubUISourceCode) return new WebInspector.UILocation(stubUISourceCode,rawLocation.lineNumber,rawLocation.columnNumber); 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._networkMapping.uiSourceCodeForURL(url, this._target); if (!uiSourceCode) return null ; return uiSourceCode.uiLocation((entry[3]), (entry[4])); }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { if (uiSourceCode.project().type() === WebInspector.projectTypes.Service) return null ; var networkURL = this._networkMapping.networkURL(uiSourceCode); if (!networkURL) return null ; var sourceMap = this._sourceMapForURL.get(networkURL); if (!sourceMap) return null ; var script = (this._scriptForSourceMap.get(sourceMap)); console.assert(script); var mappingSearchLinesCount = 5; var entry = sourceMap.findEntryReversed(networkURL, lineNumber, mappingSearchLinesCount); if (!entry) return null ; return this._debuggerModel.createRawLocation(script, (entry[0]), (entry[1])); }, addScript: function(script) { if (!script.sourceMapURL) { script.addEventListener(WebInspector.Script.Events.SourceMapURLAdded, this._sourceMapURLAdded.bind(this)); return; } this._processScript(script); }, _sourceMapURLAdded: function(event) { var script = (event.target); if (!script.sourceMapURL) return; this._processScript(script); }, _processScript: function(script) { var url = script.sourceURL; var splitURL = WebInspector.ParsedURL.splitURLIntoPathComponents(url); var parentPath = splitURL.slice(1, -1).join("/"); var name = splitURL.peekLast() || ""; var uiSourceCodePath = this._stubProjectDelegate.addContentProvider(parentPath, name, url, url, new WebInspector.StaticContentProvider(WebInspector.resourceTypes.Script,"\n\n\n\n\n// Please wait a bit.\n// Compiled script is not shown while source map is being loaded!",url)); var stubUISourceCode = (this._workspace.uiSourceCode(this._stubProjectID, uiSourceCodePath)); this._stubUISourceCodes.set(script.scriptId, stubUISourceCode); this._debuggerWorkspaceBinding.pushSourceMapping(script, this); this._loadSourceMapForScript(script, this._sourceMapLoaded.bind(this, script, uiSourceCodePath)); }, _sourceMapLoaded: function(script, uiSourceCodePath, sourceMap) { this._stubUISourceCodes.delete(script.scriptId); this._stubProjectDelegate.removeFile(uiSourceCodePath); if (!sourceMap) { this._debuggerWorkspaceBinding.updateLocations(script); return; } if (this._scriptForSourceMap.get(sourceMap)) { this._sourceMapForScriptId[script.scriptId] = sourceMap; this._debuggerWorkspaceBinding.updateLocations(script); return; } this._sourceMapForScriptId[script.scriptId] = sourceMap; this._scriptForSourceMap.set(sourceMap, script); var sourceURLs = sourceMap.sources(); var missingSources = []; for (var i = 0; i < sourceURLs.length; ++i) { var sourceURL = sourceURLs[i]; if (this._sourceMapForURL.get(sourceURL)) continue;this._sourceMapForURL.set(sourceURL, sourceMap); if (!this._networkMapping.hasMappingForURL(sourceURL) && !this._networkMapping.uiSourceCodeForURL(sourceURL, script.target())) { var contentProvider = sourceMap.sourceContentProvider(sourceURL, WebInspector.resourceTypes.Script); this._networkProject.addFileForURL(sourceURL, contentProvider, script.isContentScript()); } var uiSourceCode = this._networkMapping.uiSourceCodeForURL(sourceURL, this._target); if (uiSourceCode) { this._bindUISourceCode(uiSourceCode); } else { if (missingSources.length < 3) missingSources.push(sourceURL); else if (missingSources.peekLast() !== "\u2026") missingSources.push("\u2026"); } } if (missingSources.length) { WebInspector.console.warn(WebInspector.UIString("Source map %s points to the files missing from the workspace: [%s]", sourceMap.url(), missingSources.join(", "))); } this._debuggerWorkspaceBinding.updateLocations(script); }, isIdentity: function() { return false; }, uiLineHasMapping: function(uiSourceCode, lineNumber) { var networkURL = this._networkMapping.networkURL(uiSourceCode); if (!networkURL) return true; var sourceMap = this._sourceMapForURL.get(networkURL); if (!sourceMap) return true; return !!sourceMap.findEntryReversed(networkURL, 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); var networkURL = this._networkMapping.networkURL(uiSourceCode); if (!networkURL || !this._sourceMapForURL.get(networkURL)) return; this._bindUISourceCode(uiSourceCode); }, _loadSourceMapForScript: function(script, callback) { var scriptURL = WebInspector.ParsedURL.completeURL(this._target.resourceTreeModel.inspectedPageURL(), script.sourceURL); if (!scriptURL) { callback(null ); return; } console.assert(script.sourceMapURL); var scriptSourceMapURL = (script.sourceMapURL); var sourceMapURL = WebInspector.ParsedURL.completeURL(scriptURL, scriptSourceMapURL); 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._networkMapping.uiSourceCodeForURL(sourceURL, this._target); if (!uiSourceCode) return; this._unbindUISourceCode(uiSourceCode); } this._sourceMapForURL.keysArray().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.ResourceScriptMapping = function(debuggerModel, workspace, networkMapping, 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._networkMapping = networkMapping; this._debuggerWorkspaceBinding = debuggerWorkspaceBinding; this._boundURLs = new Set(); 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 ; var lineNumber = debuggerModelLocation.lineNumber - (script.isInlineScriptWithSourceURL() ? script.lineOffset : 0); var columnNumber = debuggerModelLocation.columnNumber || 0; if (script.isInlineScriptWithSourceURL() && !lineNumber && columnNumber) columnNumber -= script.columnOffset; return uiSourceCode.uiLocation(lineNumber, columnNumber); }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { var scripts = this._scriptsForUISourceCode(uiSourceCode); console.assert(scripts.length); var script = scripts[0]; if (script.isInlineScriptWithSourceURL()) return this._debuggerModel.createRawLocation(script, lineNumber + script.lineOffset, lineNumber ? columnNumber : columnNumber + script.columnOffset); return this._debuggerModel.createRawLocation(script, 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.set(uiSourceCode, scriptFile); else this._uiSourceCodeToScriptFile.remove(uiSourceCode); }, _uiSourceCodeAdded: function(event) { var uiSourceCode = (event.data); if (!this._networkMapping.networkURL(uiSourceCode)) 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 (!this._networkMapping.networkURL(uiSourceCode)) 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._networkMapping.uiSourceCodeForURL(script.sourceURL, this._target); }, _scriptsForUISourceCode: function(uiSourceCode) { var target = WebInspector.NetworkProject.targetForUISourceCode(uiSourceCode); if (target && target !== this._debuggerModel.target()) return []; if (!this._networkMapping.networkURL(uiSourceCode)) return []; return this._debuggerModel.scriptsForSourceURL(this._networkMapping.networkURL(uiSourceCode)); }, _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(this._networkMapping.networkURL(uiSourceCode)); }, _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.valuesArray(); for (var i = 0; i < boundURLs.length; ++i) { var uiSourceCode = this._networkMapping.uiSourceCodeForURL(boundURLs[i], this._target); 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) { function innerCallback(error, errorData) { if (!error) this._scriptSource = source; this._update(); if (callback) callback(error, errorData, this._script); } if (!this._script) return; var debuggerModel = this._resourceScriptMapping._debuggerModel; var source = this._uiSourceCode.workingCopy(); 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.SASSSourceMapping = function(cssModel, workspace, networkMapping, networkProject) { this.pollPeriodMs = 30 * 1000; this.pollIntervalMs = 200; this._cssModel = cssModel; this._workspace = workspace; this._networkProject = networkProject; this._addingRevisionCounter = 0; this._reset(); WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.SavedURL, this._fileSaveFinished, this); WebInspector.moduleSetting("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); this._networkMapping = networkMapping;}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.moduleSetting("cssReloadEnabled").get()) return; var sassFile = this._networkMapping.uiSourceCodeForURL(sassURL, this._cssModel.target()); console.assert(sassFile); if (wasLoadedFromFileSystem) sassFile.requestMetadata(metadataReceived.bind(this)); else WebInspector.ResourceLoader.loadUsingTargetUA(sassURL, null , sassLoadedViaNetwork.bind(this)); function sassLoadedViaNetwork(statusCode, headers, content) { if (statusCode >= 400) { console.error("Could not load content for " + sassURL + " : " + "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) { this._stopPolling(cssURL, sassURL); return; } if ((now = new Date().getTime()) > pollData.deadlineMs) { WebInspector.console.warn(WebInspector.UIString("%s hasn't been updated in %d seconds.", cssURL, this.pollPeriodMs / 1000)); this._stopPolling(cssURL, 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); }, _stopPolling: function(cssURL, sassURL) { var pollData = this._pollDataForSASSURL[sassURL]; delete pollData.dataByURL[cssURL]; if (!Object.keys(pollData.dataByURL).length) delete this._pollDataForSASSURL[sassURL]; }, _reloadCSS: function(cssURL, sassURL, callback) { var cssUISourceCode = this._networkMapping.uiSourceCodeForURL(cssURL, this._cssModel.target()); if (!cssUISourceCode) { WebInspector.console.warn(WebInspector.UIString("%s resource missing. Please reload the page.", cssURL)); callback(cssURL, sassURL, true); return; } if (this._networkMapping.hasMappingForURL(sassURL)) this._reloadCSSFromFileSystem(cssUISourceCode, sassURL, callback); else this._reloadCSSFromNetwork(cssUISourceCode, sassURL, callback); }, _reloadCSSFromNetwork: function(cssUISourceCode, sassURL, callback) { var cssURL = this._networkMapping.networkURL(cssUISourceCode); var data = this._pollDataForSASSURL[sassURL]; if (!data) { callback(cssURL, sassURL, true); return; } var headers = { "if-modified-since": new Date(data.sassTimestamp.getTime() - 1000).toUTCString() }; WebInspector.ResourceLoader.loadUsingTargetUA(cssURL, headers, contentLoaded.bind(this)); function contentLoaded(statusCode, headers, content) { if (statusCode >= 400) { console.error("Could not load content for " + cssURL + " : " + "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); var networkURL = this._networkMapping.networkURL(cssUISourceCode); this._cssUISourceCodeUpdated(networkURL, sassURL, callback); }, _reloadCSSFromFileSystem: function(cssUISourceCode, sassURL, callback) { cssUISourceCode.requestMetadata(metadataCallback.bind(this)); function metadataCallback(timestamp) { var cssURL = this._networkMapping.networkURL(cssUISourceCode); 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 || !WebInspector.moduleSetting("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 || !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._networkMapping.hasMappingForURL(url) && !this._networkMapping.uiSourceCodeForURL(url, header.target())) { var contentProvider = sourceMap.sourceContentProvider(url, WebInspector.resourceTypes.Stylesheet); this._networkProject.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._networkMapping.uiSourceCodeForURL(entry[2], rawLocation.target()); if (!uiSourceCode) return null ; return uiSourceCode.uiLocation(entry[3], entry[4]); }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { return null ; }, isIdentity: function() { return false; }, uiLineHasMapping: function(uiSourceCode, lineNumber) { return true; }, target: function() { return this._cssModel.target(); }, _uiSourceCodeAdded: function(event) { var uiSourceCode = (event.data); var networkURL = this._networkMapping.networkURL(uiSourceCode); var cssURLs = this._cssURLsForSASSURL[networkURL]; 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) { var networkURL = this._networkMapping.networkURL(uiSourceCode); this._sassFileSaved(networkURL, true); } }, _reset: function() { this._addingRevisionCounter = 0; this._completeSourceMapURLForCSSURL = {}; this._cssURLsForSASSURL = {}; this._pendingSourceMapLoadingCallbacks = {}; this._pollDataForSASSURL = {}; this._sourceMapByURL = {}; this._sourceMapByStyleSheetURL = {}; }};WebInspector.StylesSourceMapping = function(cssModel, workspace, networkMapping) { 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); this._networkMapping = networkMapping; cssModel.target().resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this); this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._styleSheetChanged, this); this._initialize();}WebInspector.StylesSourceMapping.ChangeUpdateTimeoutMs = 200;WebInspector.StylesSourceMapping.prototype = { rawLocationToUILocation: function(rawLocation) { var uiSourceCode = this._networkMapping.uiSourceCodeForURL(rawLocation.url, rawLocation.target()); if (!uiSourceCode) return null ; var lineNumber = rawLocation.lineNumber; var columnNumber = rawLocation.columnNumber; var header = this._cssModel.styleSheetHeaderForId(rawLocation.styleSheetId); if (header && header.isInline && header.hasSourceURL) { lineNumber -= header.lineNumberInSource(0); columnNumber -= header.columnNumberInSource(lineNumber, 0); } return uiSourceCode.uiLocation(lineNumber, columnNumber); }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { return null ; }, 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 Map()); this._urlToHeadersByFrameId[url] = map; } var headersById = map.get(header.frameId); if (!headersById) { headersById = (new Map()); map.set(header.frameId, headersById); } headersById.set(header.id, header); var uiSourceCode = this._networkMapping.uiSourceCodeForURL(url, header.target()); 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._networkMapping.uiSourceCodeForURL(url, header.target()); 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 networkURL = this._networkMapping.networkURL(uiSourceCode); if (!networkURL || !this._urlToHeadersByFrameId[networkURL]) return; this._bindUISourceCode(uiSourceCode, this._urlToHeadersByFrameId[networkURL].valuesArray()[0].valuesArray()[0]); }, _bindUISourceCode: function(uiSourceCode, header) { if (this._styleFiles.get(uiSourceCode) || (header.isInline && !header.hasSourceURL)) return; this._styleFiles.set(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._networkMapping.uiSourceCodeForURL(url, this._cssModel.target()); if (!uiSourceCode) continue;this._unbindUISourceCode(uiSourceCode); } this._initialize(); }, _setStyleContent: function(uiSourceCode, content, majorChange) { var networkURL = this._networkMapping.networkURL(uiSourceCode); var styleSheetIds = this._cssModel.styleSheetIdsForURL(networkURL); if (!styleSheetIds.length) return Promise.resolve(("No stylesheet found: " + networkURL)); this._isSettingContent = true; function callback(error) { delete this._isSettingContent; return error || null ; } var promises = []; for (var i = 0; i < styleSheetIds.length; ++i) promises.push(this._cssModel.setStyleSheetText(styleSheetIds[i], content, majorChange)); return Promise.all(promises).spread(callback.bind(this)); }, _styleSheetChanged: function(event) { if (this._isSettingContent) 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.ChangeUpdateTimeoutMs); }, _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._networkMapping.uiSourceCodeForURL(styleSheetURL, header.target()); 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).then(this._styleContentSet.bind(this)).then(finishCallback).catch((finishCallback)); this._isMajorChangePending = false; }, _styleContentSet: function(error) { if (error) WebInspector.console.error(error); }, 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.CSSWorkspaceBinding = function(targetManager, workspace, networkMapping) { this._workspace = workspace; this._networkMapping = networkMapping; this._modelToTargetInfo = new Map(); targetManager.observeTargets(this); targetManager.addModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameCreatedOrNavigated, this);}WebInspector.CSSWorkspaceBinding.prototype = { targetAdded: function(target) { var cssModel = WebInspector.CSSStyleModel.fromTarget(target); if (cssModel) this._modelToTargetInfo.set(cssModel, new WebInspector.CSSWorkspaceBinding.TargetInfo(cssModel,this._workspace,this._networkMapping)); }, targetRemoved: function(target) { var cssModel = WebInspector.CSSStyleModel.fromTarget(target); if (cssModel) this._modelToTargetInfo.remove(cssModel)._dispose(); }, pushSourceMapping: function(header, mapping) { this._ensureInfoForHeader(header)._pushSourceMapping(mapping); }, _headerInfo: function(header) { var map = this._modelToTargetInfo.get(header.cssModel()); return map._headerInfo(header.id) || null ; }, _ensureInfoForHeader: function(header) { var targetInfo = this._modelToTargetInfo.get(header.cssModel()); if (!targetInfo) { targetInfo = new WebInspector.CSSWorkspaceBinding.TargetInfo(header.cssModel(),this._workspace,this._networkMapping); this._modelToTargetInfo.set(header.cssModel(), targetInfo); } return targetInfo._ensureInfoForHeader(header); }, _mainFrameCreatedOrNavigated: function(event) { var target = (event.target).target(); var cssModel = WebInspector.CSSStyleModel.fromTarget(target); if (cssModel) this._modelToTargetInfo.get(cssModel)._reset(); }, updateLocations: function(header) { var info = this._headerInfo(header); if (info) info._updateLocations(); }, createLiveLocation: function(rawLocation, updateDelegate) { var header = rawLocation.styleSheetId ? rawLocation.cssModel().styleSheetHeaderForId(rawLocation.styleSheetId) : null ; return new WebInspector.CSSWorkspaceBinding.LiveLocation(rawLocation.cssModel(),header,rawLocation,this,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 header = style.cssModel().styleSheetHeaderForId(style.styleSheetId); var rawLocation = new WebInspector.CSSLocation(style.cssModel(),style.styleSheetId,url,header.lineNumberInSource(line),header.columnNumberInSource(line, column)); return this.rawLocationToUILocation(rawLocation); }, rawLocationToUILocation: function(rawLocation) { if (!rawLocation) return null ; var header = rawLocation.cssModel().styleSheetHeaderForId(rawLocation.styleSheetId); if (!header) return null ; var info = this._headerInfo(header); return info ? info._rawLocationToUILocation(rawLocation.lineNumber, rawLocation.columnNumber) : null ; }}WebInspector.CSSWorkspaceBinding.TargetInfo = function(cssModel, workspace, networkMapping) { this._cssModel = cssModel; this._stylesSourceMapping = new WebInspector.StylesSourceMapping(cssModel,workspace,networkMapping); this._sassSourceMapping = new WebInspector.SASSSourceMapping(cssModel,workspace,networkMapping,WebInspector.NetworkProject.forTarget(cssModel.target())); this._headerInfoById = new Map(); 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.set(header.id, info); } return info; }, _dispose: function() { this._reset(); this._cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._styleSheetAdded, this); this._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.delete(location); }, _updateLocations: function() { var items = this._locations.valuesArray(); 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.cssModel(),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, binding, updateDelegate) { WebInspector.LiveLocation.call(this, updateDelegate); this._cssModel = cssModel; this._rawLocation = rawLocation; this._binding = binding; 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; this._binding._removeLiveLocation(this); this._clearStyleSheet(); }, _setStyleSheet: function(header) { this._header = header; this._binding._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 = this._binding._headerInfo(this._header); return headerInfo._rawLocationToUILocation(cssLocation.lineNumber, cssLocation.columnNumber); } var uiSourceCode = this._binding._networkMapping.uiSourceCodeForURL(cssLocation.url, cssLocation.target()); if (!uiSourceCode) return null ; return uiSourceCode.uiLocation(cssLocation.lineNumber, cssLocation.columnNumber); }, dispose: function() { WebInspector.LiveLocation.prototype.dispose.call(this); if (this._header) this._binding._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.DebuggerWorkspaceBinding = function(targetManager, workspace, networkMapping) { this._workspace = workspace; this._networkMapping = networkMapping; 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.BeforeDebuggerPaused, this._beforeDebuggerPaused, this); targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.DebuggerResumed, this._debuggerResumed, this); workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); workspace.addEventListener(WebInspector.Workspace.Events.ProjectRemoved, this._projectRemoved, this);}WebInspector.DebuggerWorkspaceBinding.prototype = { targetAdded: function(target) { var debuggerModel = WebInspector.DebuggerModel.fromTarget(target); if (debuggerModel) this._targetToData.set(target, new WebInspector.DebuggerWorkspaceBinding.TargetData(debuggerModel,this)); }, targetRemoved: function(target) { if (!WebInspector.DebuggerModel.fromTarget(target)) return; var targetData = this._targetToData.get(target); targetData._dispose(); this._targetToData.remove(target); }, _uiSourceCodeRemoved: function(event) { var uiSourceCode = (event.data); var targetDatas = this._targetToData.valuesArray(); for (var i = 0; i < targetDatas.length; ++i) targetDatas[i]._uiSourceCodeRemoved(uiSourceCode); }, _projectRemoved: function(event) { var project = (event.data); var targetDatas = this._targetToData.valuesArray(); var uiSourceCodes = project.uiSourceCodes(); for (var i = 0; i < targetDatas.length; ++i) { for (var j = 0; j < uiSourceCodes.length; ++j) targetDatas[i]._uiSourceCodeRemoved(uiSourceCodes[j]); } }, 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.valuesArray(); for (var i = 0; i < targetDatas.length; ++i) { var rawLocation = targetDatas[i]._uiLocationToRawLocation(uiSourceCode, lineNumber, columnNumber); if (rawLocation) result.push(rawLocation); } return result; }, normalizeUILocation: function(uiLocation) { var target = WebInspector.NetworkProject.targetForUISourceCode(uiLocation.uiSourceCode); if (target) { var rawLocation = this.uiLocationToRawLocation(target, uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber); if (rawLocation) return this.rawLocationToUILocation(rawLocation); } return uiLocation; }, uiLineHasMapping: function(uiSourceCode, lineNumber) { var targetDatas = this._targetToData.valuesArray(); for (var i = 0; i < targetDatas.length; ++i) { if (!targetDatas[i]._uiLineHasMapping(uiSourceCode, lineNumber)) return false; } return true; }, 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.valuesArray().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.set(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()); }, _beforeDebuggerPaused: function(event) { var rawLocation = event.data.callFrames[0].location(); var targetData = this._targetToData.get(rawLocation.target()); if (!targetData._compilerMapping.mapsToSourceCode(rawLocation)) { event.stopPropagation(); event.preventDefault(); } }}WebInspector.DebuggerWorkspaceBinding.TargetData = function(debuggerModel, debuggerWorkspaceBinding) { this._target = debuggerModel.target(); this.scriptDataMap = new Map(); this.callFrameLocations = new Set(); var workspace = debuggerWorkspaceBinding._workspace; var networkMapping = debuggerWorkspaceBinding._networkMapping; this._defaultMapping = new WebInspector.DefaultScriptMapping(debuggerModel,workspace,debuggerWorkspaceBinding); this._resourceMapping = new WebInspector.ResourceScriptMapping(debuggerModel,workspace,networkMapping,debuggerWorkspaceBinding); this._compilerMapping = new WebInspector.CompilerScriptMapping(debuggerModel,workspace,networkMapping,WebInspector.NetworkProject.forTarget(this._target),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); this._resourceMapping.addScript(script); if (WebInspector.moduleSetting("jsSourceMapsEnabled").get()) this._compilerMapping.addScript(script); }, _setSourceMapping: function(uiSourceCode, sourceMapping) { if (this._uiSourceCodeToSourceMapping.get(uiSourceCode) === sourceMapping) return; if (sourceMapping) this._uiSourceCodeToSourceMapping.set(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.delete(location); }, _updateLocations: function() { for (var location of this._locations) location.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;;WebInspector.BreakpointManager = function(breakpointsSetting, workspace, networkMapping, targetManager, debuggerWorkspaceBinding) { this._storage = new WebInspector.BreakpointManager.Storage(this,breakpointsSetting); this._workspace = workspace; this._networkMapping = networkMapping; this._targetManager = targetManager; this._debuggerWorkspaceBinding = debuggerWorkspaceBinding; this._breakpointsActive = true; this._breakpointsForUISourceCode = new Map(); this._breakpointsForPrimaryUISourceCode = new Map(); this._provisionalBreakpoints = new Multimap(); 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._breakpointStorageId = function(sourceFileId, lineNumber, columnNumber) { if (!sourceFileId) return ""; return sourceFileId + ":" + lineNumber + ":" + columnNumber;}WebInspector.BreakpointManager.prototype = { _sourceFileId: function(uiSourceCode) { var networkURL = this._networkMapping.networkURL(uiSourceCode) if (!networkURL) return ""; return uiSourceCode.uri(); }, targetAdded: function(target) { var debuggerModel = WebInspector.DebuggerModel.fromTarget(target); if (debuggerModel && !this._breakpointsActive) debuggerModel.setBreakpointsActive(this._breakpointsActive); }, targetRemoved: function(target) {}, _provisionalBreakpointsForSourceFileId: function(sourceFileId) { var result = new Map(); var breakpoints = this._provisionalBreakpoints.get(sourceFileId).valuesArray(); for (var i = 0; i < breakpoints.length; ++i) result.set(breakpoints[i]._breakpointStorageId(), breakpoints[i]); return result; }, removeProvisionalBreakpointsForTest: function() { var breakpoints = this._provisionalBreakpoints.valuesArray(); for (var i = 0; i < breakpoints.length; ++i) breakpoints[i].remove(); this._provisionalBreakpoints.clear(); }, _restoreBreakpoints: function(uiSourceCode) { var sourceFileId = this._sourceFileId(uiSourceCode); if (!sourceFileId) return; this._storage.mute(); var breakpointItems = this._storage.breakpointItems(this._sourceFileId(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.set(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 = this._sourceFileId(uiSourceCode); for (var i = 0; i < breakpoints.length; ++i) { breakpoints[i]._resetLocations(); if (breakpoints[i].enabled()) this._provisionalBreakpoints.set(sourceFileId, breakpoints[i]); } uiSourceCode.removeEventListener(WebInspector.UISourceCode.Events.SourceMappingChanged, this._uiSourceCodeMappingChanged, this); this._breakpointsForPrimaryUISourceCode.remove(uiSourceCode); }, setBreakpoint: function(uiSourceCode, lineNumber, columnNumber, condition, enabled) { var uiLocation = new WebInspector.UILocation(uiSourceCode,lineNumber,columnNumber); var normalizedLocation = this._debuggerWorkspaceBinding.normalizeUILocation(uiLocation); if (normalizedLocation.id() !== uiLocation.id()) { WebInspector.Revealer.reveal(normalizedLocation); uiLocation = normalizedLocation; } this.setBreakpointsActive(true); return this._innerSetBreakpoint(uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.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 = this._sourceFileId(uiSourceCode); breakpoint = new WebInspector.BreakpointManager.Breakpoint(this,projectId,path,sourceFileId,lineNumber,columnNumber,condition,enabled); if (!this._breakpointsForPrimaryUISourceCode.get(uiSourceCode)) this._breakpointsForPrimaryUISourceCode.set(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.valuesArray()[0][0] : null ; }, breakpointsForUISourceCode: function(uiSourceCode) { var result = []; var uiSourceCodeBreakpoints = this._breakpointsForUISourceCode.get(uiSourceCode); var breakpoints = uiSourceCodeBreakpoints ? uiSourceCodeBreakpoints.valuesArray() : []; for (var i = 0; i < breakpoints.length; ++i) { var lineBreakpoints = breakpoints[i]; var columnBreakpointArrays = lineBreakpoints ? lineBreakpoints.valuesArray() : []; result = result.concat.apply(result, columnBreakpointArrays); } return result; }, allBreakpoints: function() { var result = []; var uiSourceCodes = this._breakpointsForUISourceCode.keysArray(); 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.keysArray() : []; var result = []; for (var i = 0; i < lineNumbers.length; ++i) { var lineBreakpoints = uiSourceCodeBreakpoints.get(lineNumbers[i]); var columnNumbers = lineBreakpoints.keysArray(); 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.keysArray(); 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 Map(); this._breakpointsForUISourceCode.set(uiLocation.uiSourceCode, breakpoints); } var lineBreakpoints = breakpoints.get(String(uiLocation.lineNumber)); if (!lineBreakpoints) { lineBreakpoints = new Map(); breakpoints.set(String(uiLocation.lineNumber), lineBreakpoints); } var columnBreakpoints = lineBreakpoints.get(String(uiLocation.columnNumber)); if (!columnBreakpoints) { columnBreakpoints = []; lineBreakpoints.set(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 debuggerModels = WebInspector.DebuggerModel.instances(); for (var i = 0; i < debuggerModels.length; ++i) debuggerModels[i].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) { var debuggerModel = WebInspector.DebuggerModel.fromTarget(target); if (!debuggerModel) return; var networkMapping = this._breakpointManager._networkMapping; var debuggerWorkspaceBinding = this._breakpointManager._debuggerWorkspaceBinding; this._targetBreakpoints.set(target, new WebInspector.BreakpointManager.TargetBreakpoint(debuggerModel,this,networkMapping,debuggerWorkspaceBinding)); }, targetRemoved: function(target) { var debuggerModel = WebInspector.DebuggerModel.fromTarget(target); if (!debuggerModel) return; 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.valuesArray(); 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.valuesArray(); 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); if (this._fakePrimaryLocation) 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.valuesArray(); for (var i = 0; i < targetBreakpoints.length; ++i) targetBreakpoints[i]._resetLocations(); }}WebInspector.BreakpointManager.TargetBreakpoint = function(debuggerModel, breakpoint, networkMapping, debuggerWorkspaceBinding) { WebInspector.SDKObject.call(this, debuggerModel.target()); this._debuggerModel = debuggerModel; this._breakpoint = breakpoint; this._networkMapping = networkMapping; this._debuggerWorkspaceBinding = debuggerWorkspaceBinding; this._liveLocations = []; this._uiLocations = {}; this._debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasDisabled, this._cleanUpAfterDebuggerIsGone, this); this._debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasEnabled, this._scheduleUpdateInDebugger, this); this._hasPendingUpdate = false; this._isUpdating = false; this._cancelCallback = false; this._currentState = null ; if (this._debuggerModel.debuggerEnabled()) this._scheduleUpdateInDebugger();}WebInspector.BreakpointManager.TargetBreakpoint.prototype = { _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) { var networkURL = this._networkMapping.networkURL(uiSourceCode); if (networkURL) newState = new WebInspector.BreakpointManager.Breakpoint.State(networkURL,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._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._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._debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.DebuggerWasDisabled, this._cleanUpAfterDebuggerIsGone, this); this._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 || WebInspector.settings.createLocalSetting("breakpoints", []); 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(sourceFileId) { var result = []; 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.ContentProviderBasedProjectDelegate = function(workspace, id, type) { WebInspector.Object.call(this); this._type = type; this._contentProviders = {}; this._workspace = workspace; this._id = id; workspace.addProject(id, this);}WebInspector.ContentProviderBasedProjectDelegate.prototype = { type: function() { return this._type; }, displayName: function() { return ""; }, url: 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, originURL, url, contentProvider) { var path = parentPath ? parentPath + "/" + name : name; if (this._contentProviders[path]) return path; var fileDescriptor = new WebInspector.FileDescriptor(parentPath,name,originURL,url,contentProvider.contentType()); this._contentProviders[path] = contentProvider; this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.FileAdded, fileDescriptor); return path; }, removeFile: function(path) { delete this._contentProviders[path]; this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.FileRemoved, path); }, contentProviders: function() { return this._contentProviders; }, reset: function() { this._contentProviders = {}; this._workspace.removeProject(this._id); this._workspace.addProject(this._id, this); }, __proto__: WebInspector.Object.prototype};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.get(script.scriptId); var lineNumber = debuggerModelLocation.lineNumber - (script.isInlineScriptWithSourceURL() ? script.lineOffset : 0); var columnNumber = debuggerModelLocation.columnNumber || 0; if (script.isInlineScriptWithSourceURL() && !lineNumber && columnNumber) columnNumber -= script.columnOffset; return uiSourceCode.uiLocation(lineNumber, columnNumber); }, uiLocationToRawLocation: function(uiSourceCode, lineNumber, columnNumber) { var scriptId = this._scriptIdForUISourceCode.get(uiSourceCode); var script = this._debuggerModel.scriptForId(scriptId); if (script.isInlineScriptWithSourceURL()) return this._debuggerModel.createRawLocation(script, lineNumber + script.lineOffset, lineNumber ? columnNumber : columnNumber + script.columnOffset); return this._debuggerModel.createRawLocation(script, lineNumber, columnNumber); }, addScript: function(script) { var path = this._projectDelegate.addScript(script); var uiSourceCode = this._workspace.uiSourceCode(this._projectId, path); console.assert(uiSourceCode); uiSourceCode = (uiSourceCode); this._uiSourceCodeForScriptId.set(script.scriptId, uiSourceCode); this._scriptIdForUISourceCode.set(uiSourceCode, script.scriptId); this._debuggerWorkspaceBinding.setSourceMapping(this._debuggerModel.target(), uiSourceCode, this); this._debuggerWorkspaceBinding.pushSourceMapping(script, this); script.addEventListener(WebInspector.Script.Events.ScriptEdited, this._scriptEdited, this); }, isIdentity: function() { return true; }, uiLineHasMapping: function(uiSourceCode, lineNumber) { return true; }, _scriptEdited: function(event) { var script = (event.target); var content = (event.data); this._uiSourceCodeForScriptId.get(script.scriptId).addRevision(content); }, _debuggerReset: function() { this._uiSourceCodeForScriptId = new Map(); 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 ""; }, url: function() { return "debugger:"; }, addScript: function(script) { var contentProvider = script.isInlineScript() && !script.hasSourceURL ? new WebInspector.ConcatenatedScriptsContentProvider([script]) : script; var splitURL = WebInspector.ParsedURL.splitURLIntoPathComponents(script.sourceURL); var name = splitURL[splitURL.length - 1]; name = "VM" + script.scriptId + (name ? " " + name : ""); return this.addContentProvider("", name, script.sourceURL, script.sourceURL, contentProvider); }, __proto__: WebInspector.ContentProviderBasedProjectDelegate.prototype};WebInspector.FileSystemWorkspaceBinding = function(isolatedFileSystemManager, workspace, networkMapping) { this._isolatedFileSystemManager = isolatedFileSystemManager; this._workspace = workspace; this._networkMapping = networkMapping; this._isolatedFileSystemManager.addEventListener(WebInspector.IsolatedFileSystemManager.Events.FileSystemAdded, this._fileSystemAdded, this); this._isolatedFileSystemManager.addEventListener(WebInspector.IsolatedFileSystemManager.Events.FileSystemRemoved, this._fileSystemRemoved, this); this._boundFileSystems = new Map(); 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._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._networkMapping); this._boundFileSystems.set(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); 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 totalWork = (event.data["totalWork"]); var progress = this._progresses[requestId]; if (!progress) return; progress.setTotalWork(totalWork); }, _onIndexingWorked: function(event) { var requestId = (event.data["requestId"]); var worked = (event.data["worked"]); var progress = this._progresses[requestId]; if (!progress) return; progress.worked(worked); if (progress.isCanceled()) { InspectorFrontendHost.stopIndexing(requestId); this._onIndexingDone(event); } }, _onIndexingDone: function(event) { var requestId = (event.data["requestId"]); var progress = this._progresses[requestId]; if (!progress) return; progress.done(); delete this._progresses[requestId]; }, _onSearchCompleted: function(event) { var requestId = (event.data["requestId"]); 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, networkMapping) { WebInspector.Object.call(this); this._fileSystemWorkspaceBinding = fileSystemWorkspaceBinding; this._fileSystem = isolatedFileSystem; this._fileSystemBaseURL = "file://" + this._fileSystem.normalizedPath() + "/"; this._fileSystemProjectURL = "filesystem:" + this._fileSystem.normalizedPath(); this._workspace = workspace; this._networkMapping = networkMapping; this._projectId = WebInspector.FileSystemWorkspaceBinding.projectId(this._fileSystem.path()); console.assert(!this._workspace.project(this._projectId)); 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); }, url: function() { return this._fileSystemProjectURL; }, _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._networkMapping.urlForPath(this._fileSystem.path(), filePath); var extension = this._extensionForPath(validNewName); var newOriginURL = this._fileSystemBaseURL + 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); InspectorFrontendHost.indexPath(requestId, this._fileSystem.path()); }, _extensionForPath: function(path) { var extensionIndex = path.lastIndexOf("."); if (extensionIndex === -1) return ""; return path.substring(extensionIndex + 1).toLowerCase(); }, _contentTypeForExtension: function(extension) { if (WebInspector.FileSystemWorkspaceBinding._styleSheetExtensions[extension]) return WebInspector.resourceTypes.Stylesheet; if (WebInspector.FileSystemWorkspaceBinding._documentExtensions[extension]) return WebInspector.resourceTypes.Document; return WebInspector.resourceTypes.Script; }, 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.excludedFolderManager().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._networkMapping.urlForPath(this._fileSystem.path(), filePath); var extension = this._extensionForPath(name); var contentType = this._contentTypeForExtension(extension); var fileDescriptor = new WebInspector.FileDescriptor(parentPath,name,this._fileSystemBaseURL + filePath,url,contentType); this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.FileAdded, fileDescriptor); }, _removeFile: function(path) { this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.FileRemoved, path); }, dispose: function() { this._workspace.removeProject(this._projectId); }, __proto__: WebInspector.Object.prototype}WebInspector.fileSystemWorkspaceBinding;;WebInspector.OutputStreamDelegate = function() {}WebInspector.OutputStreamDelegate.prototype = { onTransferStarted: function() {}, onTransferFinished: function() {}, onChunkTransferred: function(reader) {}, onError: function(reader, event) {},}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._decoder = new TextDecoder(); 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 buffer = event.target.result; this._loadedSize += buffer.byteLength; var endOfFile = this._loadedSize === this._fileSize; var decodedString = this._decoder.decode(buffer, { stream: !endOfFile }); this._output.write(decodedString); if (this._isCanceled) return; this._delegate.onChunkTransferred(this); if (endOfFile) { 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.readAsArrayBuffer(nextPart); }}WebInspector.createFileSelectorElement = function(callback) { var fileSelectorElement = 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.BlackboxSupport = {}WebInspector.BlackboxSupport._urlToRegExpString = function(url) { var parsedURL = new WebInspector.ParsedURL(url); if (parsedURL.isAboutBlank() || parsedURL.isDataURL() || !url) return ""; if (!parsedURL.isValid) return "^" + url.escapeForRegExp() + "$"; var name = parsedURL.lastPathComponent; if (name) name = "/" + name; else if (parsedURL.folderPathComponents) name = parsedURL.folderPathComponents + "/"; if (!name) name = parsedURL.host; if (!name) return ""; var scheme = parsedURL.scheme; var prefix = ""; if (scheme && scheme !== "http" && scheme !== "https") { prefix = "^" + scheme + "://"; if (scheme === "chrome-extension") prefix += parsedURL.host + "\\b"; prefix += ".*"; } return prefix + name.escapeForRegExp() + (url.endsWith(name) ? "$" : "\\b");}WebInspector.BlackboxSupport.canBlackboxURL = function(url) { return !!WebInspector.BlackboxSupport._urlToRegExpString(url);}WebInspector.BlackboxSupport.blackboxURL = function(url) { var regexPatterns = WebInspector.moduleSetting("skipStackFramesPattern").getAsArray(); var regexValue = WebInspector.BlackboxSupport._urlToRegExpString(url); if (!regexValue) return; 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.moduleSetting("skipStackFramesPattern").setAsArray(regexPatterns);}WebInspector.BlackboxSupport.unblackbox = function(url, isContentScript) { if (isContentScript) WebInspector.moduleSetting("skipContentScripts").set(false); var regexPatterns = WebInspector.moduleSetting("skipStackFramesPattern").getAsArray(); var regexValue = WebInspector.BlackboxSupport._urlToRegExpString(url); if (!regexValue) return; 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.moduleSetting("skipStackFramesPattern").setAsArray(regexPatterns);}WebInspector.BlackboxSupport.isBlackboxedURL = function(url) { var regex = WebInspector.moduleSetting("skipStackFramesPattern").asRegExp(); return (url && regex) ? regex.test(url) : false;}WebInspector.BlackboxSupport.isBlackboxed = function(url, isContentScript) { if (isContentScript && WebInspector.moduleSetting("skipContentScripts").get()) return true; return WebInspector.BlackboxSupport.isBlackboxedURL(url);}WebInspector.BlackboxSupport.addChangeListener = function(listener, thisObject) { WebInspector.moduleSetting("skipStackFramesPattern").addChangeListener(listener, thisObject);}WebInspector.BlackboxSupport.removeChangeListener = function(listener, thisObject) { WebInspector.moduleSetting("skipStackFramesPattern").removeChangeListener(listener, thisObject);};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 = 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._uiLocationSymbol = Symbol("uiLocation");WebInspector.Linkifier._fallbackAnchorSymbol = Symbol("fallbackAnchor");;WebInspector.Linkifier.prototype = { targetAdded: function(target) { this._liveLocationsByTarget.set(target, new Map()); }, targetRemoved: function(target) { var liveLocations = this._liveLocationsByTarget.remove(target); var anchors = liveLocations.keysArray(); for (var i = 0; i < anchors.length; ++i) { var anchor = anchors[i]; var location = liveLocations.get(anchor); delete anchor[WebInspector.Linkifier._uiLocationSymbol]; var fallbackAnchor = anchor[WebInspector.Linkifier._fallbackAnchorSymbol]; if (fallbackAnchor) { anchor.href = fallbackAnchor.href; anchor.lineNumber = fallbackAnchor.lineNumber; anchor.title = fallbackAnchor.title; anchor.className = fallbackAnchor.className; anchor.textContent = fallbackAnchor.textContent; delete anchor[WebInspector.Linkifier._fallbackAnchorSymbol]; } location.dispose(); } }, linkifyScriptLocation: function(target, scriptId, sourceURL, lineNumber, columnNumber, classes) { var fallbackAnchor = WebInspector.linkifyResourceAsNode(sourceURL, lineNumber, classes); if (!target || target.isDetached()) return fallbackAnchor; var debuggerModel = WebInspector.DebuggerModel.fromTarget(target); if (!debuggerModel) return fallbackAnchor; var rawLocation = scriptId ? debuggerModel.createRawLocationByScriptId(scriptId, lineNumber, columnNumber || 0) : debuggerModel.createRawLocationByURL(sourceURL, lineNumber, columnNumber || 0); 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()).set(anchor, liveLocation); anchor[WebInspector.Linkifier._fallbackAnchorSymbol] = 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); var debuggerModel = WebInspector.DebuggerModel.fromTarget(target); var script = debuggerModel && debuggerModel.scriptForId(callFrame.scriptId); var blackboxed = script ? WebInspector.BlackboxSupport.isBlackboxed(script.sourceURL, script.isContentScript()) : WebInspector.BlackboxSupport.isBlackboxedURL(callFrame.url); if (blackboxed) 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)); this._liveLocationsByTarget.get(rawLocation.target()).set(anchor, 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); }, disposeAnchor: function(target, anchor) { delete anchor[WebInspector.Linkifier._uiLocationSymbol]; delete anchor[WebInspector.Linkifier._fallbackAnchorSymbol]; var liveLocations = this._liveLocationsByTarget.get(target); if (!liveLocations) return; var location = liveLocations.remove(anchor); if (location) location.dispose(); }, _createAnchor: function(classes) { var anchor = createElement("a"); anchor.className = (classes || "") + " webkit-html-resource-link"; function clickHandler(event) { var uiLocation = anchor[WebInspector.Linkifier._uiLocationSymbol]; if (!uiLocation) return; event.consume(true); var networkURL = WebInspector.networkMapping.networkURL(uiLocation.uiSourceCode); if (WebInspector.Linkifier.handleLink(networkURL, uiLocation.lineNumber)) return; WebInspector.Revealer.reveal(uiLocation); } anchor.addEventListener("click", clickHandler, false); return anchor; }, reset: function() { var targets = this._liveLocationsByTarget.keysArray(); for (var i = 0; i < targets.length; ++i) { var target = targets[i]; this.targetRemoved(target); this.targetAdded(target); } }, dispose: function() { this.reset(); WebInspector.targetManager.unobserveTargets(this); this._liveLocationsByTarget.clear(); }, _updateAnchor: function(anchor, uiLocation) { anchor[WebInspector.Linkifier._uiLocationSymbol] = uiLocation; this._formatter.formatLiveAnchor(anchor, uiLocation); }}WebInspector.Linkifier.uiLocationByAnchor = function(anchor) { return anchor[WebInspector.Linkifier._uiLocationSymbol];}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 debuggerModel = WebInspector.DebuggerModel.fromTarget(target); if (!debuggerModel) return ""; var script = debuggerModel.scriptForId(scriptId); if (!script) return ""; var location = (debuggerModel.createRawLocation(script, lineNumber, columnNumber || 0)); var uiLocation = (WebInspector.debuggerWorkspaceBinding.rawLocationToUILocation(location)); return uiLocation.linkText();};WebInspector.NetworkMapping = function(workspace, fileSystemMapping) { this._workspace = workspace; this._fileSystemMapping = fileSystemMapping; InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.RevealSourceLine, this._revealSourceLine, this);}WebInspector.NetworkMapping.prototype = { networkURL: function(uiSourceCode) { return uiSourceCode.networkURL(); }, hasMappingForURL: function(url) { return this._fileSystemMapping.hasMappingForURL(url); }, _networkUISourceCodeForURL: function(url, target) { var splitURL = WebInspector.ParsedURL.splitURLIntoPathComponents(url); var projectId = WebInspector.NetworkProject.projectId(target, splitURL[0], false); var project = this._workspace.project(projectId); return project ? project.uiSourceCode(splitURL.slice(1).join("/")) : null ; }, _contentScriptUISourceCodeForURL: function(url, target) { var splitURL = WebInspector.ParsedURL.splitURLIntoPathComponents(url); var projectId = WebInspector.NetworkProject.projectId(target, splitURL[0], true); var project = this._workspace.project(projectId); return project ? project.uiSourceCode(splitURL.slice(1).join("/")) : null ; }, uiSourceCodeForURL: function(url, target) { var file = this._fileSystemMapping.fileForURL(url); if (file) { var projectId = WebInspector.FileSystemWorkspaceBinding.projectId(file.fileSystemPath); var project = this._workspace.project(projectId); return project ? project.uiSourceCode(file.filePath) : null ; } return this._networkUISourceCodeForURL(url, target) || this._contentScriptUISourceCodeForURL(url, target); }, uiSourceCodeForURLForAnyTarget: function(url) { for (var target of WebInspector.targetManager.targets()) { var result = this.uiSourceCodeForURL(url, target); if (result) return result; } return null ; }, urlForPath: function(fileSystemPath, filePath) { return this._fileSystemMapping.urlForPath(fileSystemPath, filePath); }, addMapping: function(networkUISourceCode, uiSourceCode, fileSystemWorkspaceBinding) { var url = this.networkURL(networkUISourceCode); var path = uiSourceCode.path(); var fileSystemPath = fileSystemWorkspaceBinding.fileSystemPath(uiSourceCode.project().id()); this._fileSystemMapping.addMappingForResource(url, fileSystemPath, path); }, removeMapping: function(uiSourceCode) { var networkURL = this.networkURL(uiSourceCode); this._fileSystemMapping.removeMappingForURL(networkURL); }, _revealSourceLine: function(event) { var url = (event.data["url"]); var lineNumber = (event.data["lineNumber"]); var columnNumber = (event.data["columnNumber"]); var uiSourceCode = this.uiSourceCodeForURLForAnyTarget(url); if (uiSourceCode) { WebInspector.Revealer.reveal(uiSourceCode.uiLocation(lineNumber, columnNumber)); return; } function listener(event) { var uiSourceCode = (event.data); if (this.networkURL(uiSourceCode) === url) { WebInspector.Revealer.reveal(uiSourceCode.uiLocation(lineNumber, columnNumber)); this._workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, listener, this); } } this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, listener, this); },}WebInspector.networkMapping;;WebInspector.NetworkProjectDelegate = function(target, workspace, projectId, projectURL, projectType) { this._url = projectURL; this._target = target; this._id = projectId; WebInspector.ContentProviderBasedProjectDelegate.call(this, workspace, projectId, projectType);}WebInspector.NetworkProjectDelegate.prototype = { target: function() { return this._target; }, id: function() { return this._id; }, displayName: function() { if (typeof this._displayName !== "undefined") return this._displayName; var targetSuffix = this._target.isPage() ? "" : " \u2014 " + this._target.name(); if (!this._url) { this._displayName = WebInspector.UIString("(no domain)") + targetSuffix; return this._displayName; } var parsedURL = new WebInspector.ParsedURL(this._url); var prettyURL = parsedURL.isValid ? parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") : ""; this._displayName = (prettyURL || this._url) + targetSuffix; return this._displayName; }, url: function() { return this._url; }, addFile: function(parentPath, name, url, contentProvider) { return this.addContentProvider(parentPath, name, url, url, contentProvider); }, __proto__: WebInspector.ContentProviderBasedProjectDelegate.prototype}WebInspector.NetworkProjectManager = function(targetManager, workspace, networkMapping) { this._workspace = workspace; this._networkMapping = networkMapping; targetManager.observeTargets(this);}WebInspector.NetworkProjectManager.prototype = { targetAdded: function(target) { new WebInspector.NetworkProject(target,this._workspace,this._networkMapping); }, targetRemoved: function(target) { WebInspector.NetworkProject.forTarget(target)._dispose(); }}WebInspector.NetworkProject = function(target, workspace, networkMapping) { WebInspector.SDKObject.call(this, target); this._workspace = workspace; this._networkMapping = networkMapping; this._projectDelegates = {}; this._processedURLs = {}; target[WebInspector.NetworkProject._networkProjectSymbol] = this; target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, this._resourceAdded, this); target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this); var debuggerModel = WebInspector.DebuggerModel.fromTarget(target); if (debuggerModel) { debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this); debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this); } var cssModel = WebInspector.CSSStyleModel.fromTarget(target); if (cssModel) { cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._styleSheetAdded, this); cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._styleSheetRemoved, this); }}WebInspector.NetworkProject._networkProjectSymbol = Symbol("networkProject");WebInspector.NetworkProject._contentTypeSymbol = Symbol("networkContentType");WebInspector.NetworkProject.projectId = function(target, projectURL, isContentScripts) { return target.id() + ":" + (isContentScripts ? "contentscripts:" : "") + projectURL;}WebInspector.NetworkProject._targetForProject = function(project) { var targetId = parseInt(project.id(), 10); return WebInspector.targetManager.targetById(targetId);}WebInspector.NetworkProject.forTarget = function(target) { return target[WebInspector.NetworkProject._networkProjectSymbol];}WebInspector.NetworkProject.targetForUISourceCode = function(uiSourceCode) { if (uiSourceCode.project().type() !== WebInspector.projectTypes.ContentScripts && uiSourceCode.project().type() !== WebInspector.projectTypes.Network) return null ; return WebInspector.NetworkProject._targetForProject(uiSourceCode.project());}WebInspector.NetworkProject.uiSourceCodeContentType = function(uiSourceCode) { return uiSourceCode[WebInspector.NetworkProject._contentTypeSymbol];}WebInspector.NetworkProject.prototype = { _projectDelegate: function(projectURL, isContentScripts) { var projectId = WebInspector.NetworkProject.projectId(this.target(), projectURL, isContentScripts); var projectType = isContentScripts ? WebInspector.projectTypes.ContentScripts : WebInspector.projectTypes.Network; if (this._projectDelegates[projectId]) return this._projectDelegates[projectId]; var projectDelegate = new WebInspector.NetworkProjectDelegate(this.target(),this._workspace,projectId,projectURL,projectType); this._projectDelegates[projectId] = projectDelegate; return projectDelegate; }, addFileForURL: function(url, contentProvider, isContentScript) { var splitURL = WebInspector.ParsedURL.splitURLIntoPathComponents(url); var projectURL = splitURL[0]; var parentPath = splitURL.slice(1, -1).join("/"); var name = splitURL.peekLast() || ""; var projectDelegate = this._projectDelegate(projectURL, isContentScript || false); var path = projectDelegate.addFile(parentPath, name, url, contentProvider); var uiSourceCode = (this._workspace.uiSourceCode(projectDelegate.id(), path)); console.assert(uiSourceCode); return uiSourceCode; }, _removeFileForURL: function(url) { var splitURL = WebInspector.ParsedURL.splitURLIntoPathComponents(url); var projectURL = splitURL[0]; var path = splitURL.slice(1).join("/"); var projectDelegate = this._projectDelegates[WebInspector.NetworkProject.projectId(this.target(), projectURL, false)]; projectDelegate.removeFile(path); }, _populate: function() { 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.NetworkProject.FallbackResource(resources[i])); } var mainFrame = this.target().resourceTreeModel.mainFrame; if (mainFrame) populateFrame.call(this, mainFrame); }, _parsedScriptSource: function(event) { var script = (event.data); if (!script.sourceURL || (script.isInlineScript() && !script.hasSourceURL)) 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.hasSourceURL && header.origin !== "inspector") return; this._addFile(header.resourceURL(), header, false); }, _styleSheetRemoved: function(event) { var header = (event.data); if (header.isInline && !header.hasSourceURL && header.origin !== "inspector") return; this._removeFile(header.resourceURL()); }, _resourceAdded: function(event) { var resource = (event.data); this._addFile(resource.url, new WebInspector.NetworkProject.FallbackResource(resource)); }, _mainFrameNavigated: function(event) { this._reset(); this._populate(); }, _addFile: function(url, contentProvider, isContentScript) { if (this._networkMapping.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; var uiSourceCode = this.addFileForURL(url, contentProvider, isContentScript); uiSourceCode[WebInspector.NetworkProject._contentTypeSymbol] = type; }, _removeFile: function(url) { if (!this._processedURLs[url]) return; delete this._processedURLs[url]; this._removeFileForURL(url); }, _dispose: function() { this._reset(); var target = this.target(); target.resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.ResourceAdded, this._resourceAdded, this); target.resourceTreeModel.removeEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._mainFrameNavigated, this); var debuggerModel = WebInspector.DebuggerModel.fromTarget(target); if (debuggerModel) { debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this); debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.FailedToParseScriptSource, this._parsedScriptSource, this); } var cssModel = WebInspector.CSSStyleModel.fromTarget(target); if (cssModel) { cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._styleSheetAdded, this); cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._styleSheetRemoved, this); } }, _reset: function() { this._processedURLs = {}; for (var projectId in this._projectDelegates) this._projectDelegates[projectId].reset(); this._projectDelegates = {}; }, __proto__: WebInspector.SDKObject.prototype}WebInspector.NetworkProject.FallbackResource = function(resource) { this._resource = resource;}WebInspector.NetworkProject.FallbackResource.prototype = { contentURL: function() { return this._resource.contentURL(); }, contentType: function() { return this._resource.resourceType(); }, requestContent: function(callback) { function loadFallbackContent() { var debuggerModel = WebInspector.DebuggerModel.fromTarget(this._resource.target()); if (!debuggerModel) { callback(null ); return; } var scripts = debuggerModel.scriptsForSourceURL(this._resource.url); if (!scripts.length) { callback(null ); return; } var contentProvider; var type = this._resource.resourceType(); if (type === WebInspector.resourceTypes.Document) contentProvider = new WebInspector.ConcatenatedScriptsContentProvider(scripts); else if (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.PresentationConsoleMessageHelper = function(workspace) { this._workspace = workspace; this._pendingConsoleMessages = {}; this._presentationConsoleMessages = []; this._uiSourceCodeToMessages = new Map(); this._uiSourceCodeToEventTarget = new Map(); workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); workspace.addEventListener(WebInspector.Workspace.Events.ProjectRemoved, this._projectRemoved, this); 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.Events = { ConsoleMessageAdded: "ConsoleMessageAdded", ConsoleMessageRemoved: "ConsoleMessageRemoved", ConsoleMessagesCleared: "ConsoleMessagesCleared",}WebInspector.PresentationConsoleMessageHelper.prototype = { addConsoleMessageEventListener: function(eventType, uiSourceCode, listener, thisObject) { var target = this._uiSourceCodeToEventTarget.get(uiSourceCode); if (!target) { target = new WebInspector.Object(); this._uiSourceCodeToEventTarget.set(uiSourceCode, target); } target.addEventListener(eventType, listener, thisObject); }, removeConsoleMessageEventListener: function(eventType, uiSourceCode, listener, thisObject) { var target = this._uiSourceCodeToEventTarget.get(uiSourceCode); if (!target) return; target.removeEventListener(eventType, listener, thisObject); }, consoleMessages: function(uiSourceCode) { return this._uiSourceCodeToMessages.get(uiSourceCode) || []; }, _dispatchConsoleEvent: function(eventType, uiSourceCode, message) { var target = this._uiSourceCodeToEventTarget.get(uiSourceCode); if (!target) return; target.dispatchEventToListeners(eventType, message); }, _uiSourceCodeRemoved: function(event) { var uiSourceCode = (event.data); this._uiSourceCodeToEventTarget.remove(uiSourceCode); this._uiSourceCodeToMessages.remove(uiSourceCode); }, _projectRemoved: function(event) { var project = (event.data); var uiSourceCodes = project.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) { this._uiSourceCodeToEventTarget.remove(uiSourceCodes[i]); this._uiSourceCodeToMessages.remove(uiSourceCodes[i]); } }, _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 debuggerModel = WebInspector.DebuggerModel.fromTarget(message.target()); if (!debuggerModel) return null ; 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; if (message.scriptId) return debuggerModel.createRawLocationByScriptId(message.scriptId, lineNumber, columnNumber); return 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 (!rawLocation) continue;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]; }, _presentationConsoleMessageAdded: function(message) { var uiSourceCode = message._uiLocation.uiSourceCode; var messages = this._uiSourceCodeToMessages.get(uiSourceCode); if (!messages) { messages = []; this._uiSourceCodeToMessages.set(uiSourceCode, messages); } messages.push(message); this._dispatchConsoleEvent(WebInspector.PresentationConsoleMessageHelper.Events.ConsoleMessageAdded, uiSourceCode, message); }, _presentationConsoleMessageRemoved: function(message) { var uiSourceCode = message._uiLocation.uiSourceCode; var messages = this._uiSourceCodeToMessages.get(uiSourceCode); if (!messages) return; messages.remove(message); this._dispatchConsoleEvent(WebInspector.PresentationConsoleMessageHelper.Events.ConsoleMessageRemoved, uiSourceCode, message); }, _consoleCleared: function() { this._pendingConsoleMessages = {}; for (var i = 0; i < this._presentationConsoleMessages.length; ++i) this._presentationConsoleMessages[i].dispose(); this._presentationConsoleMessages = []; var targets = this._uiSourceCodeToEventTarget.valuesArray(); for (var i = 0; i < targets.length; ++i) targets[i].dispatchEventToListeners(WebInspector.PresentationConsoleMessageHelper.Events.ConsoleMessagesCleared); this._uiSourceCodeToMessages.clear(); }, _debuggerReset: function() { this._consoleCleared(); }}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) WebInspector.presentationConsoleMessageHelper._presentationConsoleMessageRemoved(this); this._uiLocation = uiLocation; WebInspector.presentationConsoleMessageHelper._presentationConsoleMessageAdded(this); }, lineNumber: function() { return this._uiLocation.lineNumber; }, columnNumber: function() { return this._uiLocation.columnNumber; }, dispose: function() { this._liveLocation.dispose(); }}WebInspector.presentationConsoleMessageHelper;;WebInspector.resourceForURL = function(url) { var targets = WebInspector.targetManager.targets(); for (var i = 0; i < targets.length; ++i) { var resource = targets[i].resourceTreeModel.resourceForURL(url); if (resource) return resource; } return null ;}WebInspector.forAllResources = function(callback) { var targets = WebInspector.targetManager.targets(); for (var i = 0; i < targets.length; ++i) targets[i].resourceTreeModel.forAllResources(callback);}WebInspector.displayNameForURL = function(url) { if (!url) return ""; var resource = WebInspector.resourceForURL(url); if (resource) return resource.displayName; var uiSourceCode = WebInspector.networkMapping.uiSourceCodeForURLForAnyTarget(url); if (uiSourceCode) return uiSourceCode.displayName(); if (!WebInspector.targetManager.inspectedPageURL()) return url.trimURL(""); var parsedURL = WebInspector.targetManager.inspectedPageURL().asParsedURL(); var lastPathComponent = parsedURL ? parsedURL.lastPathComponent : parsedURL; var index = WebInspector.targetManager.inspectedPageURL().indexOf(lastPathComponent); if (index !== -1 && index + lastPathComponent.length === WebInspector.targetManager.inspectedPageURL().length) { var baseURL = WebInspector.targetManager.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 = createDocumentFragment(); var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|data:|www\.)[\w$\-_+*'=\|\/\\(){}[\]^%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({^%@&#~]/; 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(createTextNode(nonLink)); var title = linkString; var realURL = (linkString.startsWith("www.") ? "http://" + linkString : linkString); var splitResult = WebInspector.ParsedURL.splitLineAndColumn(realURL); var linkNode; if (splitResult) linkNode = linkifier(title, splitResult.url, splitResult.lineNumber, splitResult.columnNumber); else linkNode = linkifier(title, realURL); container.appendChild(linkNode); string = string.substring(linkIndex + linkString.length, string.length); } if (string) container.appendChild(createTextNode(string)); return container;}WebInspector.linkifyStringAsFragment = function(string) { function linkifier(title, url, lineNumber, columnNumber) { var isExternal = !WebInspector.resourceForURL(url) && !WebInspector.networkMapping.uiSourceCodeForURLForAnyTarget(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 = 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.linkifyDocumentationURLAsNode = function(article, title) { return WebInspector.linkifyURLAsNode("https://developer.chrome.com/devtools/docs/" + article, title, undefined, true);}WebInspector.linkifyResourceAsNode = function(url, lineNumber, classes, tooltipText, urlDisplayName) { var linkText = urlDisplayName ? urlDisplayName : url ? WebInspector.displayNameForURL(url) : WebInspector.UIString("(program)"); if (typeof lineNumber === "number") linkText += ":" + (lineNumber + 1); 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;};window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;WebInspector.TempFile = function() { this._fileEntry = null ; this._writer = null ;}WebInspector.TempFile.create = function(dirPath, name) { var file = new WebInspector.TempFile(); function requestTempFileSystem() { return new Promise(window.requestFileSystem.bind(window, window.TEMPORARY, 10)); } function getDirectoryEntry(fs) { return new Promise(fs.root.getDirectory.bind(fs.root, dirPath, { create: true })); } function getFileEntry(dir) { return new Promise(dir.getFile.bind(dir, name, { create: true })); } function createFileWriter(fileEntry) { file._fileEntry = fileEntry; return new Promise(fileEntry.createWriter.bind(fileEntry)); } function truncateFile(writer) { if (!writer.length) { file._writer = writer; return Promise.resolve(file); } function truncate(fulfill, reject) { writer.onwriteend = fulfill; writer.onerror = reject; writer.truncate(0); } function didTruncate() { file._writer = writer; writer.onwriteend = null ; writer.onerror = null ; return Promise.resolve(file); } function onTruncateError(e) { writer.onwriteend = null ; writer.onerror = null ; throw e; } return new Promise(truncate).then(didTruncate, onTruncateError); } return WebInspector.TempFile.ensureTempStorageCleared().then(requestTempFileSystem).then(getDirectoryEntry).then(getFileEntry).then(createFileWriter).then(truncateFile);}WebInspector.TempFile.prototype = { write: function(strings, callback) { var blob = new Blob(strings,{ type: 'text/plain' }); this._writer.onerror = function(e) { WebInspector.console.error("Failed to write into a temp file: " + e.target.error.message); callback(-1); } this._writer.onwriteend = function(e) { callback(e.target.length); } this._writer.write(blob); }, finishWriting: function() { this._writer = null ; }, read: function(callback) { this.readRange(undefined, undefined, callback); }, readRange: function(startOffset, endOffset, callback) { function didGetFile(file) { var reader = new FileReader(); if (typeof startOffset === "number" || typeof endOffset === "number") file = file.slice((startOffset), (endOffset)); 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.DeferredTempFile = function(dirPath, name) { this._chunks = []; this._tempFile = null ; this._isWriting = false; this._finishCallback = null ; this._finishedWriting = false; this._callsPendingOpen = []; this._pendingReads = []; WebInspector.TempFile.create(dirPath, name).then(this._didCreateTempFile.bind(this), this._failedToCreateTempFile.bind(this));}WebInspector.DeferredTempFile.prototype = { write: function(strings, callback) { if (!this._chunks) return; if (this._finishCallback) throw new Error("No writes are allowed after close."); this._chunks.push({ strings: strings, callback: callback }); if (this._tempFile && !this._isWriting) this._writeNextChunk(); }, finishWriting: function(callback) { this._finishCallback = callback; if (this._finishedWriting) callback(this._tempFile); else if (!this._isWriting && !this._chunks.length) this._notifyFinished(); }, _failedToCreateTempFile: function(e) { WebInspector.console.error("Failed to create temp file " + e.code + " : " + e.message); this._notifyFinished(); }, _didCreateTempFile: function(tempFile) { this._tempFile = tempFile; var callsPendingOpen = this._callsPendingOpen; this._callsPendingOpen = null ; for (var i = 0; i < callsPendingOpen.length; ++i) callsPendingOpen[i](); if (this._chunks.length) this._writeNextChunk(); }, _writeNextChunk: function() { var chunk = this._chunks.shift(); this._isWriting = true; this._tempFile.write((chunk.strings), this._didWriteChunk.bind(this, chunk.callback)); }, _didWriteChunk: function(callback, size) { this._isWriting = false; if (size === -1) { this._tempFile = null ; this._notifyFinished(); return; } if (callback) callback(size); if (this._chunks.length) this._writeNextChunk(); else if (this._finishCallback) this._notifyFinished(); }, _notifyFinished: function() { this._finishedWriting = true; if (this._tempFile) this._tempFile.finishWriting(); var chunks = this._chunks; this._chunks = []; for (var i = 0; i < chunks.length; ++i) { if (chunks[i].callback) chunks[i].callback(-1); } if (this._finishCallback) this._finishCallback(this._tempFile); var pendingReads = this._pendingReads; this._pendingReads = []; for (var i = 0; i < pendingReads.length; ++i) pendingReads[i](); }, readRange: function(startOffset, endOffset, callback) { if (!this._finishedWriting) { this._pendingReads.push(this.readRange.bind(this, startOffset, endOffset, callback)); return; } if (!this._tempFile) { callback(null ); return; } this._tempFile.readRange(startOffset, endOffset, callback); }, writeToOutputStream: function(outputStream, delegate) { if (this._callsPendingOpen) { this._callsPendingOpen.push(this.writeToOutputStream.bind(this, outputStream, delegate)); return; } if (this._tempFile) this._tempFile.writeToOutputSteam(outputStream, delegate); }, remove: function() { if (this._callsPendingOpen) { this._callsPendingOpen.push(this.remove.bind(this)); return; } if (this._tempFile) this._tempFile.remove(); }}WebInspector.TempFile._clearTempStorage = function(fulfill, reject) { function handleError(event) { WebInspector.console.error(WebInspector.UIString("Failed to clear temp storage: %s", event.data)); reject(event.data); } function handleMessage(event) { if (event.data.type === "tempStorageCleared") { if (event.data.error) WebInspector.console.error(event.data.error); else fulfill(undefined); return; } reject(event.data); } try { var worker = new WorkerRuntime.Worker("temp_storage_shared_worker","TempStorageCleaner"); worker.onerror = handleError; worker.port.onmessage = handleMessage; worker.port.onerror = handleError; } catch (e) { if (e.name === "URLMismatchError") console.log("Shared worker wasn't started due to url difference. " + e); else throw e; }}WebInspector.TempFile.ensureTempStorageCleared = function() { if (!WebInspector.TempFile._storageCleanerPromise) WebInspector.TempFile._storageCleanerPromise = new Promise(WebInspector.TempFile._clearTempStorage); return WebInspector.TempFile._storageCleanerPromise;}WebInspector.TempFileBackingStorage = function(dirName) { this._dirName = dirName; this.reset();}WebInspector.TempFileBackingStorage.Chunk;WebInspector.TempFileBackingStorage.prototype = { appendString: function(string) { this._strings.push(string); this._stringsLength += string.length; var flushStringLength = 10 * 1024 * 1024; if (this._stringsLength > flushStringLength) this._flush(false); }, appendAccessibleString: function(string) { this._flush(false); this._strings.push(string); var chunk = (this._flush(true)); function readString(chunk, file) { if (chunk.string) return ( Promise.resolve(chunk.string)) ; console.assert(chunk.endOffset); if (!chunk.endOffset) return Promise.reject("Nor string nor offset to the string in the file were found."); function readRange(fulfill, reject) { file.readRange(chunk.startOffset, chunk.endOffset, fulfill); } return new Promise(readRange); } return readString.bind(null , chunk, this._file); }, _flush: function(createChunk) { if (!this._strings.length) return null ; var chunk = null ; if (createChunk) { console.assert(this._strings.length === 1); chunk = { string: this._strings[0], startOffset: 0, endOffset: 0 }; } function didWrite(chunk, fileSize) { if (fileSize === -1) return; if (chunk) { chunk.startOffset = this._fileSize; chunk.endOffset = fileSize; chunk.string = null ; } this._fileSize = fileSize; } this._file.write(this._strings, didWrite.bind(this, chunk)); this._strings = []; this._stringsLength = 0; return chunk; }, finishWriting: function() { this._flush(false); this._file.finishWriting(function() {} ); }, reset: function() { if (this._file) this._file.remove(); this._file = new WebInspector.DeferredTempFile(this._dirName,String(Date.now())); this._strings = []; this._stringsLength = 0; this._fileSize = 0; }, writeToStream: function(outputStream, delegate) { this._file.writeToOutputStream(outputStream, delegate); }};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.ContentScriptProjectDecorator = function() { WebInspector.targetManager.addModelListener(WebInspector.RuntimeModel, WebInspector.RuntimeModel.Events.ExecutionContextCreated, this._onContextCreated, this); WebInspector.workspace.addEventListener(WebInspector.Workspace.Events.ProjectAdded, this._onProjectAdded, this);}WebInspector.ContentScriptProjectDecorator._updateProjectWithExtensionName = function(project, context) { if (project.url().startsWith(context.origin)) project.setDisplayName(context.name);}WebInspector.ContentScriptProjectDecorator.prototype = { _onContextCreated: function(event) { var context = (event.data); if (!context.origin || !context.name) return; var projects = WebInspector.workspace.projects(); projects = projects.filter(contentProjectWithName); for (var i = 0; i < projects.length; ++i) WebInspector.ContentScriptProjectDecorator._updateProjectWithExtensionName(projects[i], context); function contentProjectWithName(project) { return !!project.url() && project.type() === WebInspector.projectTypes.ContentScripts; } }, _onProjectAdded: function(event) { var project = (event.data); if (project.type() !== WebInspector.projectTypes.ContentScripts) return; var targets = WebInspector.targetManager.targets(); var contexts = []; for (var i = 0; i < targets.length; ++i) contexts = contexts.concat(targets[i].runtimeModel.executionContexts()); contexts = contexts.filter(contextWithOriginAndName); for (var i = 0; i < contexts.length; ++i) WebInspector.ContentScriptProjectDecorator._updateProjectWithExtensionName(project, contexts[i]); function contextWithOriginAndName(context) { return !!context.origin && !!context.name; } }};WebInspector.BreakpointsSidebarPaneBase = function(title) { WebInspector.SidebarPane.call(this, title); this.registerRequiredCSS("components/breakpointsList.css"); this.listElement = createElement("ol"); this.listElement.className = "breakpoint-list"; this.emptyElement = createElement("div"); this.emptyElement.className = "info"; this.emptyElement.textContent = WebInspector.UIString("No Breakpoints"); this.element.appendChild(this.emptyElement);}WebInspector.BreakpointsSidebarPaneBase.prototype = { addListElement: function(element, beforeNode) { if (beforeNode) { this.listElement.insertBefore(element, beforeNode); } else { if (!this.listElement.firstChild) { this.element.removeChild(this.emptyElement); this.element.appendChild(this.listElement); } this.listElement.appendChild(element); } }, removeListElement: function(element) { this.listElement.removeChild(element); if (!this.listElement.firstChild) { this.element.removeChild(this.listElement); this.element.appendChild(this.emptyElement); } }, reset: function() { this.listElement.removeChildren(); if (this.listElement.parentElement) { this.element.removeChild(this.listElement); this.element.appendChild(this.emptyElement); } }, __proto__: WebInspector.SidebarPane.prototype};WebInspector.CustomPreviewSection = function(object) { this._sectionElement = createElementWithClass("span", "custom-expandable-section"); this._object = object; this._expanded = false; this._cachedContent = null ; var customPreview = object.customPreview(); try { var headerJSON = JSON.parse(customPreview.header); } catch (e) { WebInspector.console.error("Broken formatter: header is invalid json " + e); return; } this._header = this._renderJSONMLTag(headerJSON); if (this._header.nodeType === Node.TEXT_NODE) { WebInspector.console.error("Broken formatter: header should be an element node."); return; } if (customPreview.hasBody) { this._header.classList.add("custom-expandable-section-header"); this._header.addEventListener("click", this._onClick.bind(this), false); } this._sectionElement.appendChild(this._header);}WebInspector.CustomPreviewComponent = function(object) { this._object = object; this._customPreviewSection = new WebInspector.CustomPreviewSection(object); this.element = createElementWithClass("span", "source-code"); var shadowRoot = WebInspector.createShadowRootWithCoreStyles(this.element); this.element.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), false); shadowRoot.appendChild(WebInspector.Widget.createStyleElement("components/customPreviewSection.css")); shadowRoot.appendChild(this._customPreviewSection.element());}WebInspector.CustomPreviewComponent.prototype = { expandIfPossible: function() { if (this._object.customPreview().hasBody && this._customPreviewSection) this._customPreviewSection._loadBody(); }, _contextMenuEventFired: function(event) { var contextMenu = new WebInspector.ContextMenu(event); if (this._customPreviewSection) contextMenu.appendItem(WebInspector.UIString.capitalize("Show as Javascript ^object"), this._disassemble.bind(this)); contextMenu.appendApplicableItems(this._object); contextMenu.show(); }, _disassemble: function() { this.element.shadowRoot.textContent = ""; this._customPreviewSection = null ; this.element.shadowRoot.appendChild(WebInspector.ObjectPropertiesSection.defaultObjectPresentation(this._object)); }}WebInspector.CustomPreviewSection._tagsWhiteList = new Set(["span", "div", "ol", "li", "table", "tr", "td"]);WebInspector.CustomPreviewSection.prototype = { element: function() { return this._sectionElement; }, _renderJSONMLTag: function(jsonML) { if (!Array.isArray(jsonML)) return createTextNode(jsonML + ""); var array = (jsonML); if (array[0] === "object") return this._layoutObjectTag(array); else return this._renderElement(array); }, _renderElement: function(object) { var tagName = object.shift(); if (!WebInspector.CustomPreviewSection._tagsWhiteList.has(tagName)) { WebInspector.console.error("Broken formatter: element " + tagName + " is not allowed!"); return createElement("span"); } var element = createElement((tagName)); if ((typeof object[0] == "object") && !Array.isArray(object[0])) { var attributes = object.shift(); for (var key in attributes) { var value = attributes[key]; if ((key !== "style") || (typeof value !== "string")) continue;element.setAttribute(key, value); } } this._appendJsonMLTags(element, object); return element; }, _layoutObjectTag: function(objectTag) { objectTag.shift(); var attributes = objectTag.shift(); var remoteObject = this._object.target().runtimeModel.createRemoteObject((attributes)); if (remoteObject.customPreview()) return (new WebInspector.CustomPreviewSection(remoteObject)).element(); var sectionElement = WebInspector.ObjectPropertiesSection.defaultObjectPresentation(remoteObject); sectionElement.classList.toggle("custom-expandable-section-standard-section", remoteObject.hasChildren); return sectionElement; }, _appendJsonMLTags: function(parentElement, jsonMLTags) { for (var i = 0; i < jsonMLTags.length; ++i) parentElement.appendChild(this._renderJSONMLTag(jsonMLTags[i])); }, _onClick: function(event) { event.consume(true); if (this._cachedContent) this._toggleExpand(); else this._loadBody(); }, _toggleExpand: function() { this._expanded = !this._expanded; this._header.classList.toggle("expanded", this._expanded); this._cachedContent.classList.toggle("hidden", !this._expanded); }, _loadBody: function() { function load(formatter, config) { function substituteObjectTagsInCustomPreview(jsonMLObject) { if (!jsonMLObject || (typeof jsonMLObject !== "object") || (typeof jsonMLObject.splice !== "function")) return; var obj = jsonMLObject.length; if (!(typeof obj === "number" && obj >>> 0 === obj && (obj > 0 || 1 / obj > 0))) return; var startIndex = 1; if (jsonMLObject[0] === "object") { var attributes = jsonMLObject[1]; var originObject = attributes["object"]; var config = attributes["config"]; if (typeof originObject === "undefined") throw "Illegal format: obligatory attribute \"object\" isn't specified"; jsonMLObject[1] = bindRemoteObject(originObject, false, false, null , false, config); startIndex = 2; } for (var i = startIndex; i < jsonMLObject.length; ++i) substituteObjectTagsInCustomPreview(jsonMLObject[i]); } try { var body = formatter.body(this, config); substituteObjectTagsInCustomPreview(body); return body; } catch (e) { console.error("Custom Formatter Failed: " + e); return null ; } } var customPreview = this._object.customPreview(); var args = [{ objectId: customPreview.formatterObjectId }]; if (customPreview.configObjectId) args.push({ objectId: customPreview.configObjectId }); this._object.callFunctionJSON(load, args, onBodyLoaded.bind(this)); function onBodyLoaded(bodyJsonML) { if (!bodyJsonML) return; this._cachedContent = this._renderJSONMLTag(bodyJsonML); this._sectionElement.appendChild(this._cachedContent); this._toggleExpand(); } }};WebInspector.DataSaverInfobar = function() { WebInspector.Infobar.call(this, WebInspector.Infobar.Type.Warning, WebInspector.settings.moduleSetting("disableDataSaverInfobar")); this.element.createTextChild(WebInspector.UIString("Consider disabling ")); this.element.appendChild(WebInspector.linkifyURLAsNode("https://support.google.com/chrome/answer/2392284?hl=en", "Chrome Data Saver", undefined, true)); this.element.createTextChild(WebInspector.UIString(" while debugging."));}WebInspector.DataSaverInfobar._infobars = [];WebInspector.DataSaverInfobar.maybeShowInPanel = function(panel) { if (Runtime.queryParam("remoteFrontend")) { var infobar = new WebInspector.DataSaverInfobar(); WebInspector.DataSaverInfobar._infobars.push(infobar); panel.showInfobar(infobar); }}WebInspector.DataSaverInfobar.prototype = { close: function() { for (var infobar of WebInspector.DataSaverInfobar._infobars) WebInspector.Infobar.prototype.close.call(infobar); }, __proto__: WebInspector.Infobar.prototype};WebInspector.DebuggerPresentationUtils = {}WebInspector.DebuggerPresentationUtils.callFrameAnchorFromStackTrace = function(debuggerModel, stackTrace, asyncStackTrace, showBlackboxed) { function innerCallFrameAnchorFromStackTrace(stackTrace) { if (!stackTrace || !stackTrace.length) return null ; if (showBlackboxed) return stackTrace[0]; for (var i = 0; i < stackTrace.length; ++i) { var script = debuggerModel && debuggerModel.scriptForId(stackTrace[i].scriptId); var blackboxed = script ? WebInspector.BlackboxSupport.isBlackboxed(script.sourceURL, script.isContentScript()) : WebInspector.BlackboxSupport.isBlackboxedURL(stackTrace[i].url); if (!blackboxed) return stackTrace[i]; } return null ; } var callFrame = innerCallFrameAnchorFromStackTrace(stackTrace); if (callFrame) return callFrame; while (asyncStackTrace) { callFrame = innerCallFrameAnchorFromStackTrace(asyncStackTrace.callFrames); if (callFrame) return callFrame; asyncStackTrace = asyncStackTrace.asyncStackTrace; } return stackTrace ? stackTrace[0] : null ;};WebInspector.DOMBreakpointsSidebarPane = function() { WebInspector.BreakpointsSidebarPaneBase.call(this, WebInspector.UIString("DOM Breakpoints")); this._domBreakpointsSetting = WebInspector.settings.createLocalSetting("domBreakpoints", []); this.listElement.classList.add("dom-breakpoints-list"); 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.capitalize("Subtree ^modifications"); this._contextMenuLabels[this._breakpointTypes.AttributeModified] = WebInspector.UIString.capitalize("Attributes ^modifications"); this._contextMenuLabels[this._breakpointTypes.NodeRemoved] = WebInspector.UIString.capitalize("Node ^removal"); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.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 && element._checkboxElement.checked) 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 = WebInspector.DOMModel.fromTarget(details.target()); if (!domModel) return; if (auxData.type === this._breakpointTypes.SubtreeModified) { var targetNodeObject = details.target().runtimeModel.createRemoteObject(auxData["targetNode"]); domModel.pushObjectAsNodeToFrontend(targetNodeObject, 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 = WebInspector.formatLocalized(message, substitutions, ""); 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); var breakpointElement = this._breakpointElements[breakpointId]; if (!breakpointElement) { breakpointElement = this._createBreakpointElement(node, type, enabled); this._breakpointElements[breakpointId] = breakpointElement; } else { breakpointElement._checkboxElement.checked = enabled; } if (enabled) node.target().domdebuggerAgent().setDOMBreakpoint(node.id, type); }, _createBreakpointElement: function(node, type, enabled) { var element = createElement("li"); element._node = node; element._type = type; element.addEventListener("contextmenu", this._contextMenu.bind(this, node, type), true); var checkboxLabel = createCheckboxLabel("", enabled); checkboxLabel.addEventListener("click", this._checkboxClicked.bind(this, node, type), false); element._checkboxElement = checkboxLabel.checkboxElement; element.appendChild(checkboxLabel); var labelElement = createElementWithClass("div", "dom-breakpoint"); element.appendChild(labelElement); var linkifiedNode = WebInspector.DOMPresentationUtils.linkifyNodeReference(node); linkifiedNode.classList.add("monospace"); linkifiedNode.style.display = "block"; labelElement.appendChild(linkifiedNode); var description = createElement("div"); 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); return element; }, _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) node.target().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.capitalize("Remove ^breakpoint"), removeBreakpoint.bind(this)); contextMenu.appendItem(WebInspector.UIString.capitalize("Remove ^all DOM breakpoints"), this._removeAllBreakpoints.bind(this)); contextMenu.show(); }, _checkboxClicked: function(node, type, event) { if (event.target.checked) node.target().domdebuggerAgent().setDOMBreakpoint(node.id, type); else node.target().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 = this._domBreakpointsSetting.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 }); } this._domBreakpointsSetting.set(breakpoints); }, restoreBreakpoints: function(domModel) { var pathToBreakpoints = {}; function didPushNodeByPathToFrontend(path, nodeId) { var node = nodeId ? 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 = this._domBreakpointsSetting.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] = []; 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.BreakpointsSidebarPaneBase.prototype}WebInspector.DOMBreakpointsSidebarPane.Proxy = function(pane, panel) { WebInspector.SidebarPane.call(this, pane.title()); this.registerRequiredCSS("components/breakpointsList.css"); this._wrappedPane = pane; this._panel = panel;}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._wrappedPane.element.parentNode !== this.element) this._wrappedPane.show(this.element); }, __proto__: WebInspector.SidebarPane.prototype}WebInspector.domBreakpointsSidebarPane;;WebInspector.DOMPresentationUtils = {}WebInspector.DOMPresentationUtils.decorateNodeLabel = function(node, parentElement) { var title = node.nodeNameInCorrectCase(); var nameElement = createElement("span"); nameElement.textContent = title; parentElement.appendChild(nameElement); var idAttribute = node.getAttribute("id"); if (idAttribute) { var idElement = createElement("span"); parentElement.appendChild(idElement); var part = "#" + idAttribute; title += part; idElement.createTextChild(part); nameElement.className = "extra"; } var classAttribute = node.getAttribute("class"); if (classAttribute) { var classes = classAttribute.split(/\s+/); var foundClasses = {}; if (classes.length) { var classesElement = 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.createTextChild(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 createTextNode(WebInspector.UIString("<node>")); var root = createElement("span"); var shadowRoot = WebInspector.createShadowRootWithCoreStyles(root); shadowRoot.appendChild(WebInspector.Widget.createStyleElement("components/domUtils.css")); var link = shadowRoot.createChild("div", "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("mouseleave", WebInspector.DOMModel.hideDOMNodeHighlight.bind(WebInspector.DOMModel), false); return root;}WebInspector.DOMPresentationUtils.linkifyDeferredNodeReference = function(deferredNode) { var root = createElement("div"); var shadowRoot = WebInspector.createShadowRootWithCoreStyles(root); shadowRoot.appendChild(WebInspector.Widget.createStyleElement("components/domUtils.css")); var link = shadowRoot.createChild("div", "node-link"); link.createChild("content"); link.addEventListener("click", deferredNode.resolve.bind(deferredNode, onDeferredNodeResolved), false); link.addEventListener("mousedown", consumeEvent, false); function onDeferredNodeResolved(node) { WebInspector.Revealer.reveal(node); } return root;}WebInspector.DOMPresentationUtils.buildImagePreviewContents = function(target, originalImageURL, showDimensions, userCallback, precomputedFeatures) { var resource = target.resourceTreeModel.resourceForURL(originalImageURL); var imageURL = originalImageURL; if (!isImageResource(resource) && precomputedFeatures && precomputedFeatures.currentSrc) { imageURL = precomputedFeatures.currentSrc; resource = target.resourceTreeModel.resourceForURL(imageURL); } if (!isImageResource(resource)) { userCallback(); return; } var imageElement = createElement("img"); imageElement.addEventListener("load", buildContent, false); imageElement.addEventListener("error", errorCallback, false); resource.populateImageSource(imageElement); function errorCallback() { userCallback(); } function isImageResource(resource) { return !!resource && resource.resourceType() === WebInspector.resourceTypes.Image; } function buildContent() { var container = createElement("table"); container.className = "image-preview-container"; var naturalWidth = precomputedFeatures ? precomputedFeatures.naturalWidth : imageElement.naturalWidth; var naturalHeight = precomputedFeatures ? precomputedFeatures.naturalHeight : imageElement.naturalHeight; var offsetWidth = precomputedFeatures ? precomputedFeatures.offsetWidth : naturalWidth; var offsetHeight = precomputedFeatures ? precomputedFeatures.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; if (imageURL !== originalImageURL) container.createChild("tr").createChild("td").createChild("span", "description").textContent = String.sprintf("currentSrc: %s", imageURL.trimMiddle(100)); userCallback(container); }}WebInspector.DOMPresentationUtils.buildStackTracePreviewContents = function(target, linkifier, stackTrace, asyncStackTrace) { var element = createElement("span"); element.style.display = "inline-block"; var shadowRoot = WebInspector.createShadowRootWithCoreStyles(element); shadowRoot.appendChild(WebInspector.Widget.createStyleElement("components/domUtils.css")); var contentElement = shadowRoot.createChild("table", "stack-preview-container"); function appendStackTrace(stackTrace) { for (var stackFrame of stackTrace) { var row = createElement("tr"); row.createChild("td").textContent = WebInspector.beautifyFunctionName(stackFrame.functionName); row.createChild("td").textContent = " @ "; row.createChild("td").appendChild(linkifier.linkifyConsoleCallFrame(target, stackFrame)); contentElement.appendChild(row); } } if (stackTrace) appendStackTrace(stackTrace); while (asyncStackTrace) { var callFrames = asyncStackTrace.callFrames; if (!callFrames || !callFrames.length) break; var row = contentElement.createChild("tr"); row.createChild("td", "stack-preview-async-description").textContent = WebInspector.asyncStackTraceLabel(asyncStackTrace.description); row.createChild("td"); row.createChild("td"); appendStackTrace(callFrames); asyncStackTrace = asyncStackTrace.asyncStackTrace; } return element;}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.DockController = function(canDock) { this._canDock = canDock; this._closeButton = new WebInspector.ToolbarButton(WebInspector.UIString("Close"),"delete-toolbar-item"); this._closeButton.addEventListener("click", InspectorFrontendHost.closeWindow.bind(InspectorFrontendHost)); if (!canDock) { this._dockSide = WebInspector.DockController.State.Undocked; this._updateUI(); return; } this._currentDockStateSetting = WebInspector.settings.createSetting("currentDockState", ""); this._lastDockStateSetting = WebInspector.settings.createSetting("lastDockState", ""); this._dockToggleButton;}WebInspector.DockController.State = { DockedToBottom: "bottom", DockedToRight: "right", 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.DockedToRight, WebInspector.DockController.State.DockedToBottom, WebInspector.DockController.State.Undocked]; this._titles = [WebInspector.UIString("Dock to right"), WebInspector.UIString("Dock to bottom"), WebInspector.UIString("Undock into separate window")]; var initialState = this._currentDockStateSetting.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; }, _dockSideChanged: function(dockSide) { if (this._dockSide === dockSide) return; if (this._dockToggleButton) this._dockToggleButton.setEnabled(false); 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); if (this._dockToggleButton) this._dockToggleButton.setEnabled(true); }, _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.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-bottom"); break; case WebInspector.DockController.State.Undocked: body.classList.add("undocked"); body.classList.remove("dock-to-right"); body.classList.remove("dock-to-bottom"); break; } this._closeButton.setVisible(this._dockSide !== WebInspector.DockController.State.Undocked); }, __proto__: WebInspector.Object.prototype}WebInspector.DockController.ButtonProvider = function() {}WebInspector.DockController.ButtonProvider.prototype = { item: function() { if (!WebInspector.dockController.canDock()) return null ; if (!WebInspector.dockController._dockToggleButton) { WebInspector.dockController._dockToggleButton = new WebInspector.ToolbarStatesSettingButton("dock-toolbar-item",WebInspector.dockController._states,WebInspector.dockController._titles,WebInspector.dockController.dockSide(),WebInspector.dockController._currentDockStateSetting,WebInspector.dockController._lastDockStateSetting,WebInspector.dockController._dockSideChanged.bind(WebInspector.dockController)); } return WebInspector.dockController._dockToggleButton; }}WebInspector.DockController.ToggleDockActionDelegate = function() {}WebInspector.DockController.ToggleDockActionDelegate.prototype = { handleAction: function(context, actionId) { var toggleButton = new WebInspector.DockController.ButtonProvider().item(); if (!toggleButton || !toggleButton.enabled()) return; (toggleButton).toggle(); }}WebInspector.DockController.CloseButtonProvider = function() {}WebInspector.DockController.CloseButtonProvider.prototype = { item: function() { return WebInspector.dockController._closeButton; }}WebInspector.dockController;;WebInspector.Drawer = function(splitWidget) { WebInspector.VBox.call(this); this.element.id = "drawer-contents"; this._splitWidget = splitWidget; splitWidget.hideDefaultResizer(); splitWidget.setSidebarWidget(this); this._toggleDrawerButton = new WebInspector.ToolbarButton(WebInspector.UIString("Show drawer"),"console-toolbar-item"); this._toggleDrawerButton.addEventListener("click", this.toggle, this); this._tabbedPane = new WebInspector.TabbedPane(); this._tabbedPane.element.id = "drawer-tabbed-pane"; this._tabbedPane.setCloseableTabs(false); this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); new WebInspector.ExtensibleTabbedPaneController(this._tabbedPane,"drawer-view"); splitWidget.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.setToggled(true); this._toggleDrawerButton.setTitle(WebInspector.UIString("Hide drawer")); }, willHide: function() { this._toggleDrawerButton.setToggled(false); this._toggleDrawerButton.setTitle(WebInspector.UIString("Show drawer")); }, _innerShow: function(immediate) { if (this.isShowing()) return; this._splitWidget.showBoth(!immediate); if (this._visibleView()) this._visibleView().focus(); }, closeDrawer: function() { if (!this.isShowing()) return; WebInspector.restoreFocusFromElement(this.element); this._splitWidget.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.ExecutionContextSelector = function(targetManager, context) { targetManager.observeTargets(this); context.addFlavorChangeListener(WebInspector.ExecutionContext, this._executionContextChanged, this); context.addFlavorChangeListener(WebInspector.Target, this._targetChanged, this); targetManager.addModelListener(WebInspector.RuntimeModel, WebInspector.RuntimeModel.Events.ExecutionContextCreated, this._onExecutionContextCreated, this); targetManager.addModelListener(WebInspector.RuntimeModel, WebInspector.RuntimeModel.Events.ExecutionContextDestroyed, this._onExecutionContextDestroyed, this); this._targetManager = targetManager; this._context = context;}WebInspector.ExecutionContextSelector.prototype = { targetAdded: function(target) { if (!target.hasJSContext()) return; setImmediate(deferred.bind(this)); function deferred() { if (!this._context.flavor(WebInspector.Target)) this._context.setFlavor(WebInspector.Target, target); } }, targetRemoved: function(target) { if (!target.hasJSContext()) return; var currentExecutionContext = this._context.flavor(WebInspector.ExecutionContext); if (currentExecutionContext && currentExecutionContext.target() === target) this._currentExecutionContextGone(); var targets = this._targetManager.targetsWithJSContext(); if (this._context.flavor(WebInspector.Target) === target && targets.length) this._context.setFlavor(WebInspector.Target, targets[0]); }, _executionContextChanged: function(event) { var newContext = (event.data); if (newContext) { this._context.setFlavor(WebInspector.Target, newContext.target()); if (!this._contextIsGoingAway) this._lastSelectedContextId = this._contextPersistentId(newContext); } }, _contextPersistentId: function(executionContext) { return executionContext.isMainWorldContext ? executionContext.target().name() + ":" + executionContext.frameId : ""; }, _targetChanged: function(event) { var newTarget = (event.data); var currentContext = this._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]; } this._context.setFlavor(WebInspector.ExecutionContext, newContext); }, _onExecutionContextCreated: function(event) { var executionContext = (event.data); if (!this._context.flavor(WebInspector.ExecutionContext) || (this._lastSelectedContextId && this._lastSelectedContextId === this._contextPersistentId(executionContext))) this._context.setFlavor(WebInspector.ExecutionContext, executionContext); }, _onExecutionContextDestroyed: function(event) { var executionContext = (event.data); if (this._context.flavor(WebInspector.ExecutionContext) === executionContext) this._currentExecutionContextGone(); }, _currentExecutionContextGone: function() { var targets = this._targetManager.targetsWithJSContext(); var newContext = null ; for (var i = 0; i < targets.length; ++i) { if (targets[i].isServiceWorker()) continue;var executionContexts = targets[i].runtimeModel.executionContexts(); if (executionContexts.length) { newContext = executionContexts[0]; break; } } this._contextIsGoingAway = true; this._context.setFlavor(WebInspector.ExecutionContext, newContext); this._contextIsGoingAway = false; }}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 pos = expressionString.lastIndexOf("[", expressionString.length - 2); if (pos !== -1) expressionString = expressionString.substr(pos + 1); var prefix = wordRange.toString(); executionContext.completionsForExpression(expressionString, prefix, force, completionsReadyCallback);};WebInspector.ExecutionContextModel = function(selectElement) { this._selectElement = selectElement; this._optionByExecutionContext = new Map(); WebInspector.targetManager.observeTargets(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.targetManager.addModelListener(WebInspector.ResourceTreeModel, WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._onFrameNavigated, this); this._selectElement.addEventListener("change", this._executionContextChanged.bind(this), false); WebInspector.context.addFlavorChangeListener(WebInspector.ExecutionContext, this._executionContextChangedExternally, this);}WebInspector.ExecutionContextModel.prototype = { _titleFor: function(executionContext) { var result; if (executionContext.isMainWorldContext) { if (executionContext.frameId) { var frame = executionContext.target().resourceTreeModel.frameForId(executionContext.frameId); result = frame ? frame.displayName() : (executionContext.origin || executionContext.name); } else { var parsedUrl = executionContext.origin.asParsedURL(); var name = parsedUrl ? parsedUrl.lastPathComponentWithFragment() : executionContext.name; result = executionContext.target().decorateLabel(name); } } else { result = "\u00a0\u00a0\u00a0\u00a0" + (executionContext.name || executionContext.origin); } var maxLength = 50; return result.trimMiddle(maxLength); }, _executionContextCreated: function(executionContext) { if (executionContext.target().isServiceWorker()) return; var newOption = createElement("option"); newOption.__executionContext = executionContext; newOption.text = this._titleFor(executionContext); this._optionByExecutionContext.set(executionContext, newOption); var options = this._selectElement.options; var contexts = Array.prototype.map.call(options, mapping); var index = insertionIndexForObjectInListSortedByFunction(executionContext, contexts, WebInspector.ExecutionContext.comparator); this._selectElement.insertBefore(newOption, options[index]); if (executionContext === WebInspector.context.flavor(WebInspector.ExecutionContext)) this._select(newOption); function mapping(option) { return option.__executionContext; } }, _onExecutionContextCreated: function(event) { var executionContext = (event.data); this._executionContextCreated(executionContext); }, _executionContextDestroyed: function(executionContext) { var option = this._optionByExecutionContext.remove(executionContext); option.remove(); }, _onExecutionContextDestroyed: function(event) { var executionContext = (event.data); this._executionContextDestroyed(executionContext); }, _onFrameNavigated: function(event) { var frame = (event.data); var executionContexts = this._optionByExecutionContext.keysArray(); for (var i = 0; i < executionContexts.length; ++i) { var context = executionContexts[i]; if (context.frameId === frame.id) this._optionByExecutionContext.get(context).text = this._titleFor(context); } }, _executionContextChangedExternally: function(event) { var executionContext = (event.data); if (!executionContext) return; var options = this._selectElement.options; for (var i = 0; i < options.length; ++i) { if (options[i].__executionContext === executionContext) this._select(options[i]); } }, _executionContextChanged: function() { var option = this._selectedOption(); var newContext = option ? option.__executionContext : null ; WebInspector.context.setFlavor(WebInspector.ExecutionContext, newContext); }, targetAdded: function(target) { target.runtimeModel.executionContexts().forEach(this._executionContextCreated, this); }, targetRemoved: function(target) { var executionContexts = this._optionByExecutionContext.keysArray(); for (var i = 0; i < executionContexts.length; ++i) { if (executionContexts[i].target() === target) this._executionContextDestroyed(executionContexts[i]); } }, _select: function(option) { this._selectElement.selectedIndex = Array.prototype.indexOf.call((this._selectElement), option); }, _selectedOption: function() { if (this._selectElement.selectedIndex >= 0) return this._selectElement[this._selectElement.selectedIndex]; return null ; }};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.capitalize("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.capitalize("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 uiLocation = WebInspector.Linkifier.uiLocationByAnchor(anchorElement); var resourceURL = uiLocation ? uiLocation.uiSourceCode.contentURL() : anchorElement.href; var uiSourceCode = uiLocation ? uiLocation.uiSourceCode : (resourceURL ? WebInspector.networkMapping.uiSourceCodeForURLForAnyTarget(resourceURL) : null ); function open() { WebInspector.Revealer.reveal(uiSourceCode); } if (uiSourceCode) contextMenu.appendItem("Open", open); 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 (!targetNode.enclosingNodeOrSelfWithClassList(["resources", "panel"]) && WebInspector.resourceForURL(resourceURL)) contextMenu.appendItem(WebInspector.UIString.capitalize("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 = 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 = 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.OpenAnchorLocationSettingUI = function() {}WebInspector.HandlerRegistry.OpenAnchorLocationSettingUI.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); }}WebInspector.openAnchorLocationRegistry;;WebInspector.InspectElementModeController = function() { this._toggleSearchButton = new WebInspector.ToolbarButton(WebInspector.UIString("Select an element in the page to inspect it"),"node-search-toolbar-item"); InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.EnterInspectElementMode, this._toggleSearch, this); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.SuspendStateChanged, this._suspendStateChanged, this); WebInspector.targetManager.observeTargets(this, WebInspector.Target.Type.Page);}WebInspector.InspectElementModeController.createShortcut = function() { return WebInspector.KeyboardShortcut.makeDescriptor("c", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta | WebInspector.KeyboardShortcut.Modifiers.Shift);}WebInspector.InspectElementModeController.prototype = { targetAdded: function(target) { if (!this.enabled()) return; var domModel = WebInspector.DOMModel.fromTarget(target); domModel.setInspectModeEnabled(true, WebInspector.moduleSetting("showUAShadowDOM").get()); }, targetRemoved: function(target) {}, enabled: function() { return this._toggleSearchButton.toggled(); }, disable: function() { if (this.enabled()) this._toggleSearch(); }, _toggleSearch: function() { var enabled = !this.enabled(); this._toggleSearchButton.setToggled(enabled); for (var domModel of WebInspector.DOMModel.instances()) domModel.setInspectModeEnabled(enabled, WebInspector.moduleSetting("showUAShadowDOM").get()); }, _suspendStateChanged: function() { if (WebInspector.targetManager.allTargetsSuspended()) this._toggleSearchButton.setToggled(false); }}WebInspector.InspectElementModeController.ToggleSearchActionDelegate = function() {}WebInspector.InspectElementModeController.ToggleSearchActionDelegate.prototype = { handleAction: function(context, actionId) { if (!WebInspector.inspectElementModeController) return; WebInspector.inspectElementModeController._toggleSearch(); }}WebInspector.InspectElementModeController.ToggleButtonProvider = function() {}WebInspector.InspectElementModeController.ToggleButtonProvider.prototype = { item: function() { if (!WebInspector.inspectElementModeController) return null ; return WebInspector.inspectElementModeController._toggleSearchButton; }}WebInspector.inspectElementModeController = null ;;WebInspector.InspectorView = function() { WebInspector.VBox.call(this); WebInspector.Dialog.setModalHostView(this); WebInspector.GlassPane.DefaultFocusedViewStack.push(this); this.setMinimumSize(240, 72); this._drawerSplitWidget = new WebInspector.SplitWidget(false,true,"Inspector.drawerSplitViewState",200,200); this._drawerSplitWidget.hideSidebar(); this._drawerSplitWidget.enableShowModeSaving(); this._drawerSplitWidget.show(this.element); this._tabbedPane = new WebInspector.TabbedPane(); this._tabbedPane.registerRequiredCSS("components/inspectorViewTabbedPane.css"); this._tabbedPane.element.classList.add("inspector-view-tabbed-pane"); this._tabbedPane.setRetainTabOrder(true); this._drawerSplitWidget.setMainWidget(this._tabbedPane); this._drawer = new WebInspector.Drawer(this._drawerSplitWidget); this._panels = {}; WebInspector["panels"] = this._panels; this._history = []; this._historyIterator = -1; this._keyDownBound = this._keyDown.bind(this); this._keyPressBound = this._keyPress.bind(this); this._panelDescriptors = {}; this._panelPromises = {}; this._openBracketIdentifiers = ["U+005B", "U+00DB"].keySet(); this._closeBracketIdentifiers = ["U+005D", "U+00DD"].keySet(); this._lastActivePanelSetting = WebInspector.settings.createSetting("lastActivePanel", "elements"); InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.ShowConsole, showConsole.bind(this)); this._loadPanelDesciptors(); function showConsole() { this.showPanel("console"); } WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChanged.bind(this));};WebInspector.InspectorView.prototype = { wasShown: function() { this.element.ownerDocument.addEventListener("keydown", this._keyDownBound, false); this.element.ownerDocument.addEventListener("keypress", this._keyPressBound, false); }, willHide: function() { this.element.ownerDocument.removeEventListener("keydown", this._keyDownBound, false); this.element.ownerDocument.removeEventListener("keypress", this._keyPressBound, false); }, _loadPanelDesciptors: function() { WebInspector.startBatchUpdate(); self.runtime.extensions(WebInspector.PanelFactory).forEach(processPanelExtensions.bind(this)); function processPanelExtensions(extension) { this.addPanel(new WebInspector.RuntimeExtensionPanelDescriptor(extension)); } WebInspector.endBatchUpdate(); }, createToolbars: function() { this._leftToolbar = new WebInspector.ExtensibleToolbar("main-toolbar-left"); this._leftToolbar.element.classList.add("inspector-view-toolbar", "inspector-view-toolbar-left"); this._tabbedPane.insertBeforeTabStrip(this._leftToolbar.element); var rightToolbarContainer = createElementWithClass("div", "hbox flex-none flex-centered"); this._tabbedPane.appendAfterTabStrip(rightToolbarContainer); this._rightToolbar = new WebInspector.ExtensibleToolbar("main-toolbar-right"); this._rightToolbar.element.classList.add("inspector-view-toolbar", "flex-none"); rightToolbarContainer.appendChild(this._rightToolbar.element); }, addPanel: function(panelDescriptor) { var panelName = panelDescriptor.name(); this._panelDescriptors[panelName] = panelDescriptor; this._tabbedPane.appendTab(panelName, panelDescriptor.title(), new WebInspector.Widget()); if (this._lastActivePanelSetting.get() === panelName) this._tabbedPane.selectTab(panelName); }, hasPanel: function(panelName) { return !!this._panelDescriptors[panelName]; }, panel: function(panelName) { var panelDescriptor = this._panelDescriptors[panelName]; if (!panelDescriptor) return Promise.reject(new Error("Can't load panel without the descriptor: " + panelName)); var promise = this._panelPromises[panelName]; if (promise) return promise; promise = panelDescriptor.panel(); this._panelPromises[panelName] = promise; promise.then(cachePanel.bind(this)); function cachePanel(panel) { delete this._panelPromises[panelName]; this._panels[panelName] = panel; return panel; } return promise; }, _onSuspendStateChanged: function(event) { this._currentPanelLocked = WebInspector.targetManager.allTargetsSuspended(); this._tabbedPane.setCurrentTabLocked(this._currentPanelLocked); if (this._leftToolbar) this._leftToolbar.setEnabled(!this._currentPanelLocked); if (this._rightToolbar) this._rightToolbar.setEnabled(!this._currentPanelLocked); }, showPanel: function(panelName) { if (this._currentPanelLocked) { if (this._currentPanel !== this._panels[panelName]) return Promise.reject(new Error("Current panel locked")); return Promise.resolve(this._currentPanel); } this._panelForShowPromise = this.panel(panelName); return this._panelForShowPromise.then(setCurrentPanelIfNecessary.bind(this, this._panelForShowPromise)); function setCurrentPanelIfNecessary(panelPromise, panel) { if (this._panelForShowPromise !== panelPromise) return null ; this.setCurrentPanel(panel); return panel; } }, setPanelIcon: function(panelName, iconType, iconTooltip) { this._tabbedPane.setTabIcon(panelName, iconType, iconTooltip); }, currentPanel: function() { return this._currentPanel; }, showInitialPanel: function() { if (InspectorFrontendHost.isUnderTest()) return; this._showInitialPanel(); }, _showInitialPanel: function() { this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); this._tabSelected(); this._drawer.initialPanelShown(); }, showInitialPanelForTest: function(panelName) { this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); this.setCurrentPanel(this._panels[panelName]); this._drawer.initialPanelShown(); }, _tabSelected: function() { var panelName = this._tabbedPane.selectedTabId; if (!panelName) return; this.showPanel(panelName); }, setCurrentPanel: function(panel) { delete this._panelForShowPromise; if (this._currentPanelLocked) { console.error("Current panel is locked"); return this._currentPanel; } InspectorFrontendHost.bringToFront(); if (this._currentPanel === panel) return panel; this._currentPanel = panel; if (!this._panels[panel.name]) this._panels[panel.name] = panel; this._tabbedPane.changeTabView(panel.name, panel); this._tabbedPane.removeEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); this._tabbedPane.selectTab(panel.name); this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this); this._lastActivePanelSetting.set(panel.name); this._pushToHistory(panel.name); WebInspector.userMetrics.panelShown(panel.name); panel.focus(); return panel; }, 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.moduleSetting("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(context, actionId) { if (WebInspector.inspectorView.drawerVisible()) WebInspector.inspectorView.closeDrawer(); else WebInspector.inspectorView.showDrawer(); }}WebInspector.InspectorView.ToggleDrawerButtonProvider = function() {}WebInspector.InspectorView.ToggleDrawerButtonProvider.prototype = { item: function() { return WebInspector.inspectorView._drawer.toggleButton(); }};WebInspector.NetworkConditionsSelector = function(selectElement) { this._selectElement = selectElement; this._selectElement.addEventListener("change", this._optionSelected.bind(this), false); this._setting = WebInspector.moduleSetting("networkConditions"); this._setting.addChangeListener(this._settingChanged, this); this._populateOptions(); this._settingChanged();}WebInspector.NetworkConditionsSelector._networkConditionsPresets = [{ title: "Offline", value: { throughput: 0 * 1024 / 8, latency: 0 }}, { title: "GPRS", value: { throughput: 50 * 1024 / 8, latency: 500 }}, { title: "Regular 2G", value: { throughput: 250 * 1024 / 8, latency: 300 }}, { title: "Good 2G", value: { throughput: 450 * 1024 / 8, latency: 150 }}, { title: "Regular 3G", value: { throughput: 750 * 1024 / 8, latency: 100 }}, { title: "Good 3G", value: { throughput: 1.5 * 1024 * 1024 / 8, latency: 40 }}, { title: "Regular 4G", value: { throughput: 4 * 1024 * 1024 / 8, latency: 20 }}, { title: "DSL", value: { throughput: 2 * 1024 * 1024 / 8, latency: 5 }}, { title: "WiFi", value: { throughput: 30 * 1024 * 1024 / 8, latency: 2 }}, { title: "No throttling", value: { throughput: -1, latency: 0 }}];WebInspector.NetworkConditionsSelector.prototype = { _populateOptions: function() { var presets = WebInspector.NetworkConditionsSelector._networkConditionsPresets; for (var i = 0; i < presets.length; ++i) { var preset = presets[i]; var throughputInKbps = preset.value.throughput / (1024 / 8); var isThrottling = (throughputInKbps > 0) || preset.value.latency; var option; if (!isThrottling) { option = new Option(preset.title,preset.title); } else { var throughputText = (throughputInKbps < 1024) ? WebInspector.UIString("%d Kbps", throughputInKbps) : WebInspector.UIString("%d Mbps", (throughputInKbps / 1024) | 0); var title = WebInspector.UIString("%s (%s %dms RTT)", preset.title, throughputText, preset.value.latency); option = new Option(title,preset.title); option.title = WebInspector.UIString("Maximum download throughput: %s.\r\nMinimum round-trip time: %dms.", throughputText, preset.value.latency); } option.settingValue = preset.value; this._selectElement.appendChild(option); } }, _optionSelected: function() { this._setting.removeChangeListener(this._settingChanged, this); this._setting.set(this._selectElement.options[this._selectElement.selectedIndex].settingValue); this._setting.addChangeListener(this._settingChanged, this); }, _settingChanged: function() { var value = this._setting.get(); var options = this._selectElement.options; for (var index = 0; index < options.length; ++index) { var option = options[index]; if (option.settingValue.throughput === value.throughput && option.settingValue.latency === value.latency) this._selectElement.selectedIndex = index; } }};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.MaxPopoverTextLength = 10000;WebInspector.ObjectPopoverHelper.prototype = { _showObjectPopover: function(element, popover) { function didGetFunctionProperties(funcObject, popoverContentElement, anchorElement, properties, internalProperties) { if (internalProperties) { for (var i = 0; i < internalProperties.length; i++) { if (internalProperties[i].name === "[[TargetFunction]]") { funcObject = internalProperties[i].value; break; } } } funcObject.functionDetails(didGetFunctionDetails.bind(this, popoverContentElement, anchorElement)); } function didGetFunctionDetails(popoverContentElement, anchorElement, response) { if (!response || popover.disposed) return; var container = createElementWithClass("div", "object-popover-container"); var title = container.createChild("div", "function-popover-title source-code"); var functionName = title.createChild("span", "function-name"); functionName.textContent = WebInspector.beautifyFunctionName(response.functionName); var rawLocation = response.location; var sourceURL = response.sourceURL; if (rawLocation && sourceURL) { var link = this._lazyLinkifier().linkifyRawLocation(rawLocation, sourceURL, "function-location-link"); title.appendChild(link); } container.appendChild(popoverContentElement); popover.showForAnchor(container, anchorElement); } function didGetGeneratorObjectDetails(response) { if (!response || popover.disposed) return; var rawLocation = response.location; var sourceURL = response.sourceURL; if (rawLocation && sourceURL) { var link = this._lazyLinkifier().linkifyRawLocation(rawLocation, sourceURL, "function-location-link"); this._titleElement.appendChild(link); } } function didQueryObject(result, wasThrown, anchorOverride) { if (popover.disposed) return; if (wasThrown) { this.hidePopover(); return; } this._objectTarget = result.target(); var anchorElement = anchorOverride || element; var description = result.description.trimEnd(WebInspector.ObjectPopoverHelper.MaxPopoverTextLength); var popoverContentElement = null ; if (result.type !== "object") { popoverContentElement = createElement("span"); popoverContentElement.appendChild(WebInspector.Widget.createStyleElement("components/objectValue.css")); var valueElement = popoverContentElement.createChild("span", "monospace object-value-" + result.type); valueElement.style.whiteSpace = "pre"; if (result.type === "string") valueElement.createTextChildren("\"", description, "\""); else if (result.type === "function") WebInspector.ObjectPropertiesSection.formatObjectAsFunction(result, valueElement, true); else valueElement.textContent = description; if (result.type === "function") { result.getOwnProperties(didGetFunctionProperties.bind(this, result, popoverContentElement, anchorElement)); return; } popover.showForAnchor(popoverContentElement, anchorElement); } else { if (result.subtype === "node") { WebInspector.DOMModel.highlightObjectAsDOMNode(result); this._resultHighlightedAsDOM = true; } if (result.customPreview()) { var customPreviewComponent = new WebInspector.CustomPreviewComponent(result); customPreviewComponent.expandIfPossible(); popoverContentElement = customPreviewComponent.element; } else { popoverContentElement = createElement("div"); this._titleElement = popoverContentElement.createChild("div", "monospace"); this._titleElement.createChild("span", "source-frame-popover-title").textContent = description; var section = new WebInspector.ObjectPropertiesSection(result,""); section.element.classList.add("source-frame-popover-tree"); section.titleLessMode(); popoverContentElement.appendChild(section.element); if (result.subtype === "generator") result.generatorObjectDetails(didGetGeneratorObjectDetails.bind(this)); } var popoverWidth = 300; var popoverHeight = 250; popover.showForAnchor(popoverContentElement, anchorElement, popoverWidth, popoverHeight); } } this._queryObject(element, didQueryObject.bind(this), this._popoverObjectGroup); }, _onHideObjectPopover: function() { if (this._resultHighlightedAsDOM) { WebInspector.DOMModel.hideDOMNodeHighlight(); delete this._resultHighlightedAsDOM; } if (this._linkifier) { this._linkifier.dispose(); delete this._linkifier; } if (this._onHideCallback) this._onHideCallback(); if (this._objectTarget) { this._objectTarget.runtimeAgent().releaseObjectGroup(this._popoverObjectGroup); delete this._objectTarget; } }, _lazyLinkifier: function() { if (!this._linkifier) this._linkifier = new WebInspector.Linkifier(); return this._linkifier; }, __proto__: WebInspector.PopoverHelper.prototype};WebInspector.ObjectPropertiesSection = function(object, title, emptyPlaceholder, ignoreHasOwnProperty, extraProperties) { this._object = object; this._editable = true; TreeOutlineInShadow.call(this); this.setFocusable(false); this._objectTreeElement = new WebInspector.ObjectPropertiesSection.RootElement(object,emptyPlaceholder,ignoreHasOwnProperty,extraProperties); this.appendChild(this._objectTreeElement); if (typeof title === "string" || !title) this.element.createChild("span").textContent = title || ""; else this.element.appendChild(title); this.element._section = this; this.registerRequiredCSS("components/objectValue.css"); this.registerRequiredCSS("components/objectPropertiesSection.css"); this.rootElement().childrenListElement.classList.add("source-code", "object-properties-section")}WebInspector.ObjectPropertiesSection._arrayLoadThreshold = 100;WebInspector.ObjectPropertiesSection.defaultObjectPresentation = function(object, skipProto) { var componentRoot = createElementWithClass("span", "source-code"); var shadowRoot = WebInspector.createShadowRootWithCoreStyles(componentRoot); shadowRoot.appendChild(WebInspector.Widget.createStyleElement("components/objectValue.css")); shadowRoot.appendChild(WebInspector.ObjectPropertiesSection.createValueElement(object, false)); if (!object.hasChildren) return componentRoot; var objectPropertiesSection = new WebInspector.ObjectPropertiesSection(object,componentRoot); objectPropertiesSection.editable = false; if (skipProto) objectPropertiesSection.skipProto(); return objectPropertiesSection.element;}WebInspector.ObjectPropertiesSection.prototype = { skipProto: function() { this._skipProto = true; }, expand: function() { this._objectTreeElement.expand(); }, objectTreeElement: function() { return this._objectTreeElement; }, 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(); }, titleLessMode: function() { this._objectTreeElement.listItemElement.classList.add("hidden"); this._objectTreeElement.childrenListElement.classList.add("title-less-mode"); this._objectTreeElement.expand(); }, __proto__: TreeOutlineInShadow.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.ObjectPropertiesSection.RootElement = function(object, emptyPlaceholder, ignoreHasOwnProperty, extraProperties) { this._object = object; this._extraProperties = extraProperties || []; this._ignoreHasOwnProperty = !!ignoreHasOwnProperty; this._emptyPlaceholder = emptyPlaceholder; var contentElement = createElement("content"); TreeElement.call(this, contentElement); this.setExpandable(true); this.selectable = false; this.toggleOnClick = true;}WebInspector.ObjectPropertiesSection.RootElement.prototype = { onexpand: function() { if (this.treeOutline) this.treeOutline.element.classList.add("expanded"); }, oncollapse: function() { if (this.treeOutline) this.treeOutline.element.classList.remove("expanded"); }, ondblclick: function(e) { return true; }, onpopulate: function() { WebInspector.ObjectPropertyTreeElement._populate(this, this._object, !!this.treeOutline._skipProto, this._emptyPlaceholder, this._ignoreHasOwnProperty, this._extraProperties); }, __proto__: TreeElement.prototype}WebInspector.ObjectPropertyTreeElement = function(property) { this.property = property; TreeElement.call(this); this.toggleOnClick = true; this.selectable = false;}WebInspector.ObjectPropertyTreeElement.prototype = { onpopulate: function() { var propertyValue = (this.property.value); console.assert(propertyValue); var skipProto = this.treeOutline ? this.treeOutline._skipProto : true; WebInspector.ObjectPropertyTreeElement._populate(this, propertyValue, skipProto); }, ondblclick: function(event) { var editableElement = this.valueElement; if (!this.property.value.customPreview() && (this.property.writable || this.property.setter) && event.target.isSelfOrDescendant(editableElement)) this._startEditing(); return false; }, onattach: function() { this.update(); if (this.property.value) this.setExpandable(!this.property.value.customPreview() && this.property.value.hasChildren && !this.property.wasThrown); }, update: function() { this.nameElement = WebInspector.ObjectPropertiesSection.createNameElement(this.property.name); if (!this.property.enumerable) this.nameElement.classList.add("object-properties-section-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 = createElementWithClass("span", "object-properties-section-separator"); separatorElement.textContent = ": "; if (this.property.value) { this.valueElement = WebInspector.ObjectPropertiesSection.createValueElementWithCustomSupport(this.property.value, this.property.wasThrown, this.listItemElement); this.valueElement.addEventListener("contextmenu", this._contextMenuFired.bind(this, this.property.value), false); } else if (this.property.getter) { this.valueElement = WebInspector.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan(this.property.parentObject, [this.property.name], this._onInvokeGetterClick.bind(this)); } else { this.valueElement = createElementWithClass("span", "object-value-undefined"); this.valueElement.textContent = WebInspector.UIString("<unreadable>"); this.valueElement.title = WebInspector.UIString("No property getter"); } this.listItemElement.removeChildren(); this.listItemElement.appendChildren(this.nameElement, separatorElement, this.valueElement); }, _contextMenuFired: function(value, event) { var contextMenu = new WebInspector.ContextMenu(event); contextMenu.appendApplicableItems(value); contextMenu.show(); }, _startEditing: function() { if (this._prompt || !this.treeOutline._editable || this._readOnly) return; this._editableDiv = this.listItemElement.createChild("span"); var text = this.property.value.description; if (this.property.value.type === "string" && typeof text === "string") text = "\"" + text + "\""; this._editableDiv.setTextContentTruncatedIfNeeded(text, WebInspector.UIString("<string is too large to edit>")); var originalContent = this._editableDiv.textContent; this.valueElement.classList.add("hidden"); this.setExpandable(false); this.listItemElement.classList.add("editing-sub-part"); this._prompt = new WebInspector.ObjectPropertyPrompt(); var proxyElement = this._prompt.attachAndStartEditing(this._editableDiv, this._editingCommitted.bind(this, originalContent)); this.listItemElement.getComponentSelection().setBaseAndExtent(this._editableDiv, 0, this._editableDiv, 1); proxyElement.addEventListener("keydown", this._promptKeyDown.bind(this, originalContent), false); }, _editingEnded: function() { this._prompt.detach(); delete this._prompt; this._editableDiv.remove(); this.setExpandable(this.property.value.hasChildren && !this.property.wasThrown); this.listItemElement.scrollLeft = 0; this.listItemElement.classList.remove("editing-sub-part"); }, _editingCancelled: function() { this.valueElement.classList.remove("hidden"); this._editingEnded(); }, _editingCommitted: function(originalContent) { var userInput = this._prompt.text(); if (userInput === originalContent) { this._editingCancelled(); return; } this._editingEnded(); this._applyExpression(userInput); }, _promptKeyDown: function(originalContent, event) { if (isEnterKey(event)) { event.consume(true); this._editingCommitted(originalContent); return; } if (event.keyIdentifier === "U+001B") { event.consume(); this._editingCancelled(); 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 { var parent = this.parent; parent.invalidateChildren(); parent.expand(); } } ; }, propertyPath: function() { if (this._cachedPropertyPath) 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.invalidateChildren(); }, __proto__: TreeElement.prototype}WebInspector.ObjectPropertyTreeElement._populate = function(treeElement, value, skipProto, emptyPlaceholder, flattenProtoChain, extraProperties) { 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; extraProperties = extraProperties || []; for (var i = 0; i < extraProperties.length; ++i) properties.push(extraProperties[i]); WebInspector.ObjectPropertyTreeElement.populateWithProperties(treeElement, properties, internalProperties, skipProto, value, emptyPlaceholder); } if (flattenProtoChain) value.getAllProperties(false, callback); else WebInspector.RemoteObject.loadFromObjectPerProto(value, callback);}WebInspector.ObjectPropertyTreeElement.populateWithProperties = function(treeNode, properties, internalProperties, skipProto, value, emptyPlaceholder) { properties.sort(WebInspector.ObjectPropertiesSection.CompareProperties); 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; treeNode.appendChild(new WebInspector.ObjectPropertyTreeElement(property)); } if (property.isOwn) { if (property.getter) { var getterProperty = new WebInspector.RemoteObjectProperty("get " + property.name,property.getter); getterProperty.parentObject = value; treeNode.appendChild(new WebInspector.ObjectPropertyTreeElement(getterProperty)); } if (property.setter) { var setterProperty = new WebInspector.RemoteObjectProperty("set " + property.name,property.setter); setterProperty.parentObject = value; treeNode.appendChild(new WebInspector.ObjectPropertyTreeElement(setterProperty)); } } } else { property.parentObject = value; treeNode.appendChild(new WebInspector.ObjectPropertyTreeElement(property)); } } if (internalProperties) { for (var i = 0; i < internalProperties.length; i++) { internalProperties[i].parentObject = value; treeNode.appendChild(new WebInspector.ObjectPropertyTreeElement(internalProperties[i])); } } 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) treeNode.appendChild(new WebInspector.FunctionScopeMainTreeElement(value)); } if (value && value.type === "object" && (value.subtype === "map" || value.subtype === "set" || value.subtype === "iterator")) treeNode.appendChild(new WebInspector.CollectionEntriesMainTreeElement(value)); WebInspector.ObjectPropertyTreeElement._appendEmptyPlaceholderIfNeeded(treeNode, emptyPlaceholder);}WebInspector.ObjectPropertyTreeElement._appendEmptyPlaceholderIfNeeded = function(treeNode, emptyPlaceholder) { if (treeNode.childCount()) return; var title = createElementWithClass("div", "info"); title.textContent = emptyPlaceholder || WebInspector.UIString("No Properties"); var infoElement = new TreeElement(title); treeNode.appendChild(infoElement);}WebInspector.ObjectPropertyTreeElement.createRemoteObjectAccessorPropertySpan = function(object, propertyPath, callback) { var rootElement = createElement("span"); var element = rootElement.createChild("span"); element.textContent = WebInspector.UIString("(...)"); if (!object) return rootElement; element.classList.add("object-value-calculate-value-button"); 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>", true); this.toggleOnClick = true; this.selectable = false; this._remoteObject = remoteObject;}WebInspector.FunctionScopeMainTreeElement.prototype = { onpopulate: function() { function didGetDetails(response) { if (!response) return; this.removeChildren(); var scopeChain = response.scopeChain || []; for (var i = 0; i < scopeChain.length; ++i) { var scope = scopeChain[i]; var title = null ; var isTrueObject = false; switch (scope.type) { case DebuggerAgent.ScopeType.Local: title = WebInspector.UIString("Local"); break; case DebuggerAgent.ScopeType.Closure: title = WebInspector.UIString("Closure"); break; case DebuggerAgent.ScopeType.Catch: title = WebInspector.UIString("Catch"); break; case DebuggerAgent.ScopeType.Block: title = WebInspector.UIString("Block"); break; case DebuggerAgent.ScopeType.Script: title = WebInspector.UIString("Script"); 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 WebInspector.ObjectPropertyTreeElement(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,remoteObject); this.appendChild(scopeTreeElement); } } WebInspector.ObjectPropertyTreeElement._appendEmptyPlaceholderIfNeeded(this, WebInspector.UIString("No Scopes")); } this._remoteObject.functionDetails(didGetDetails.bind(this)); }, __proto__: TreeElement.prototype}WebInspector.CollectionEntriesMainTreeElement = function(remoteObject) { TreeElement.call(this, "<entries>", true); this.toggleOnClick = true; this.selectable = false; this._remoteObject = remoteObject; this.expand();}WebInspector.CollectionEntriesMainTreeElement.prototype = { onpopulate: function() { function didGetCollectionEntries(entries) { if (!entries) return; this.removeChildren(); var entriesLocalObject = []; var runtimeModel = this._remoteObject.target().runtimeModel; for (var i = 0; i < entries.length; ++i) { var entry = entries[i]; if (entry.key) { entriesLocalObject.push(new WebInspector.MapEntryLocalJSONObject({ key: runtimeModel.createRemoteObject(entry.key), value: runtimeModel.createRemoteObject(entry.value) })); } else { entriesLocalObject.push(runtimeModel.createRemoteObject(entry.value)); } } WebInspector.ObjectPropertyTreeElement._populate(this, WebInspector.RemoteObject.fromLocalObject(entriesLocalObject), true, WebInspector.UIString("No Entries")); this.title = "<entries>[" + entriesLocalObject.length + "]"; } this._remoteObject.collectionEntries(didGetCollectionEntries.bind(this)); }, __proto__: TreeElement.prototype}WebInspector.ScopeTreeElement = function(title, remoteObject) { TreeElement.call(this, title, true); this.toggleOnClick = true; this.selectable = false; this._remoteObject = remoteObject;}WebInspector.ScopeTreeElement.prototype = { onpopulate: function() { WebInspector.ObjectPropertyTreeElement._populate(this, this._remoteObject, false); }, __proto__: TreeElement.prototype}WebInspector.ArrayGroupingTreeElement = function(object, fromIndex, toIndex, propertyCount) { TreeElement.call(this, String.sprintf("[%d \u2026 %d]", fromIndex, toIndex), true); this.toggleOnClick = true; this.selectable = false; this._fromIndex = fromIndex; this._toIndex = toIndex; this._object = object; this._readOnly = true; this._propertyCount = propertyCount;}WebInspector.ArrayGroupingTreeElement._bucketThreshold = 100;WebInspector.ArrayGroupingTreeElement._sparseIterationThreshold = 250000;WebInspector.ArrayGroupingTreeElement._getOwnPropertyNamesThreshold = 500000;WebInspector.ArrayGroupingTreeElement._populateArray = function(treeNode, object, fromIndex, toIndex) { WebInspector.ArrayGroupingTreeElement._populateRanges(treeNode, object, fromIndex, toIndex, true);}WebInspector.ArrayGroupingTreeElement._populateRanges = function(treeNode, object, fromIndex, toIndex, topLevel) { object.callFunctionJSON(packRanges, [{ value: fromIndex }, { value: toIndex }, { value: WebInspector.ArrayGroupingTreeElement._bucketThreshold }, { value: WebInspector.ArrayGroupingTreeElement._sparseIterationThreshold }, { value: WebInspector.ArrayGroupingTreeElement._getOwnPropertyNamesThreshold }], callback); function packRanges(fromIndex, toIndex, bucketThreshold, sparseIterationThreshold, getOwnPropertyNamesThreshold) { var ownPropertyNames = null ; var consecutiveRange = (toIndex - fromIndex >= sparseIterationThreshold) && ArrayBuffer.isView(this); var skipGetOwnPropertyNames = consecutiveRange && (toIndex - fromIndex >= getOwnPropertyNamesThreshold); function *arrayIndexes(object) { if (toIndex - fromIndex < sparseIterationThreshold) { for (var i = fromIndex; i <= toIndex; ++i) { if (i in object) yield i; } } else { ownPropertyNames = ownPropertyNames || Object.getOwnPropertyNames(object); for (var i = 0; i < ownPropertyNames.length; ++i) { var name = ownPropertyNames[i]; var index = name >>> 0; if (("" + index) === name && fromIndex <= index && index <= toIndex) yield index; } } } var count = 0; if (consecutiveRange) { count = toIndex - fromIndex + 1; } else { for (var i of arrayIndexes(this)) ++count; } var bucketSize = count; if (count <= bucketThreshold) bucketSize = count; else bucketSize = Math.pow(bucketThreshold, Math.ceil(Math.log(count) / Math.log(bucketThreshold)) - 1); var ranges = []; if (consecutiveRange) { for (var i = fromIndex; i <= toIndex; i += bucketSize) { var groupStart = i; var groupEnd = groupStart + bucketSize - 1; if (groupEnd > toIndex) groupEnd = toIndex; ranges.push([groupStart, groupEnd, groupEnd - groupStart + 1]); } } else { count = 0; var groupStart = -1; var groupEnd = 0; for (var i of arrayIndexes(this)) { if (groupStart === -1) groupStart = i; groupEnd = i; if (++count === bucketSize) { ranges.push([groupStart, groupEnd, count]); count = 0; groupStart = -1; } } if (count > 0) ranges.push([groupStart, groupEnd, count]); } return { ranges: ranges, skipGetOwnPropertyNames: skipGetOwnPropertyNames }; } function callback(result) { if (!result) return; var ranges = (result.ranges); if (ranges.length == 1) { WebInspector.ArrayGroupingTreeElement._populateAsFragment(treeNode, 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(treeNode, object, fromIndex, toIndex); else treeNode.appendChild(new WebInspector.ArrayGroupingTreeElement(object,fromIndex,toIndex,count)); } } if (topLevel) WebInspector.ArrayGroupingTreeElement._populateNonIndexProperties(treeNode, object, result.skipGetOwnPropertyNames); }}WebInspector.ArrayGroupingTreeElement._populateAsFragment = function(treeNode, 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 WebInspector.ObjectPropertyTreeElement(properties[i]); childTreeElement._readOnly = true; treeNode.appendChild(childTreeElement); } }}WebInspector.ArrayGroupingTreeElement._populateNonIndexProperties = function(treeNode, object, skipGetOwnPropertyNames) { object.callFunction(buildObjectFragment, [{ value: skipGetOwnPropertyNames }], processObjectFragment.bind(this)); function buildObjectFragment(skipGetOwnPropertyNames) { var result = { __proto__: this.__proto__ }; if (skipGetOwnPropertyNames) return result; 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 WebInspector.ObjectPropertyTreeElement(properties[i]); childTreeElement._readOnly = true; treeNode.appendChild(childTreeElement); } }}WebInspector.ArrayGroupingTreeElement.prototype = { onpopulate: function() { 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("object-properties-section-name"); }, __proto__: TreeElement.prototype}WebInspector.ObjectPropertyPrompt = function() { WebInspector.TextPrompt.call(this, WebInspector.ExecutionContextSelector.completionsForTextPromptInCurrentContext); this.setSuggestBoxEnabled(true);}WebInspector.ObjectPropertyPrompt.prototype = { __proto__: WebInspector.TextPrompt.prototype}WebInspector.ObjectPropertiesSection.createNameElement = function(name) { var nameElement = createElementWithClass("span", "name"); if (/^\s|\s$|^$|\n/.test(name)) nameElement.createTextChildren("\"", name.replace(/\n/g, "\u21B5"), "\""); else nameElement.textContent = name; return nameElement;}WebInspector.ObjectPropertiesSection.valueTextForFunctionDescription = function(description) { var matches = /function\s([^)]*)/.exec(description); if (!matches) { matches = /[^(]*(\([^)]*)/.exec(description); } var match = matches ? matches[1] : null ; return match ? match.replace(/\n/g, " ") + ")" : (description || "");}WebInspector.ObjectPropertiesSection.createValueElementWithCustomSupport = function(value, wasThrown, parentElement) { if (value.customPreview()) { var result = (new WebInspector.CustomPreviewComponent(value)).element; result.classList.add("object-properties-section-custom-section"); return result } return WebInspector.ObjectPropertiesSection.createValueElement(value, wasThrown, parentElement);}WebInspector.ObjectPropertiesSection.createValueElement = function(value, wasThrown, parentElement) { var valueElement = createElementWithClass("span", "value"); var type = value.type; var subtype = value.subtype; var description = value.description; var prefix; var valueText; var suffix; if (wasThrown) { prefix = "[Exception: "; valueText = description; suffix = "]"; } else if (type === "string" && typeof description === "string") { prefix = "\""; valueText = description.replace(/\n/g, "\u21B5"); suffix = "\""; } else if (type === "function") { valueText = WebInspector.ObjectPropertiesSection.valueTextForFunctionDescription(description); } else if (type !== "object" || subtype !== "node") { valueText = description; } if (type !== "number" || valueText.indexOf("e") === -1) { valueElement.setTextContentTruncatedIfNeeded(valueText || ""); if (prefix) valueElement.insertBefore(createTextNode(prefix), valueElement.firstChild); if (suffix) valueElement.createTextChild(suffix); } else { var numberParts = valueText.split("e"); var mantissa = valueElement.createChild("span", "object-value-scientific-notation-mantissa"); mantissa.textContent = numberParts[0]; var exponent = valueElement.createChild("span", "object-value-scientific-notation-exponent"); exponent.textContent = "e" + numberParts[1]; valueElement.classList.add("object-value-scientific-notation-number"); if (parentElement) parentElement.classList.add("hbox"); } if (wasThrown) valueElement.classList.add("error"); if (subtype || type) valueElement.classList.add("object-value-" + (subtype || type)); if (type === "object" && subtype === "node" && description) { WebInspector.DOMPresentationUtils.createSpansForNodeTitle(valueElement, description); valueElement.addEventListener("click", mouseClick, false); valueElement.addEventListener("mousemove", mouseMove, false); valueElement.addEventListener("mouseleave", mouseLeave, false); } else { valueElement.title = description || ""; } function mouseMove() { WebInspector.DOMModel.highlightObjectAsDOMNode(value); } function mouseLeave() { WebInspector.DOMModel.hideDOMNodeHighlight(); } function mouseClick(event) { WebInspector.Revealer.reveal(value); event.consume(true); } return valueElement;}WebInspector.ObjectPropertiesSection.formatObjectAsFunction = function(func, element, linkify, includePreview) { func.functionDetails(didGetDetails); function didGetDetails(response) { if (!response) { var valueText = WebInspector.ObjectPropertiesSection.valueTextForFunctionDescription(func.description); element.createTextChild(valueText); return; } if (linkify && response && response.location) { var anchor = createElement("span"); element.classList.add("linkified"); element.appendChild(anchor); element.addEventListener("click", WebInspector.Revealer.reveal.bind(WebInspector.Revealer, response.location, undefined)); element = anchor; } var text = func.description.substring(0, 200); if (includePreview) { element.textContent = text.replace(/^function /, "") + (func.description.length > 200 ? "\u2026" : ""); return; } self.runtime.instancePromise(WebInspector.TokenizerFactory).then(processTokens); var params = null ; var functionName = response ? response.functionName : ""; function processTokens(tokenizerFactory) { var tokenize = tokenizerFactory.createTokenizer("text/javascript"); tokenize(text, processToken); element.textContent = (functionName || "anonymous") + "(" + (params || []).join(", ") + ")"; } var doneProcessing = false; function processToken(token, tokenType, column, newColumn) { if (!params && tokenType === "js-variable" && !functionName) functionName = token; doneProcessing = doneProcessing || token === ")"; if (doneProcessing) return; if (token === "(") { params = []; return; } if (params && tokenType === "js-def") params.push(token); } }};WebInspector.RemoteObjectPreviewFormatter = function() {}WebInspector.RemoteObjectPreviewFormatter.prototype = { appendObjectPreview: function(parentElement, preview) { var description = preview.description; if (preview.type !== "object" || preview.subtype === "null") { parentElement.appendChild(this.renderPropertyPreview(preview.type, preview.subtype, description)); return true; } if (description && preview.subtype !== "array") { var text = preview.subtype ? description : this._abbreviateFullQualifiedClassName(description); parentElement.createTextChildren(text, " "); } if (preview.entries) return this._appendEntriesPreview(parentElement, preview); return this._appendPropertiesPreview(parentElement, preview); }, _abbreviateFullQualifiedClassName: function(description) { var abbreviatedDescription = description.split("."); for (var i = 0; i < abbreviatedDescription.length - 1; ++i) abbreviatedDescription[i] = abbreviatedDescription[i].trimMiddle(3); return abbreviatedDescription.join("."); }, _appendPropertiesPreview: function(parentElement, preview) { var isArray = preview.subtype === "array"; var arrayLength = WebInspector.RemoteObject.arrayLength(preview); var properties = preview.properties; if (isArray) properties = properties.slice().stableSort(compareIndexesFirst); function compareIndexesFirst(a, b) { var index1 = toArrayIndex(a.name); var index2 = toArrayIndex(b.name); if (index1 < 0) return index2 < 0 ? 0 : 1; return index2 < 0 ? -1 : index1 - index2; } function toArrayIndex(name) { var index = name >>> 0; if (String(index) === name && index < arrayLength) return index; return -1; } parentElement.createTextChild(isArray ? "[" : "{"); for (var i = 0; i < properties.length; ++i) { if (i > 0) parentElement.createTextChild(", "); var property = properties[i]; var name = property.name; if (!isArray || name != i || i >= arrayLength) { if (/^\s|\s$|^$|\n/.test(name)) parentElement.createChild("span", "name").createTextChildren("\"", name.replace(/\n/g, "\u21B5"), "\""); else parentElement.createChild("span", "name").textContent = name; parentElement.createTextChild(": "); } parentElement.appendChild(this._renderPropertyPreviewOrAccessor([property])); } if (preview.overflow) parentElement.createChild("span").textContent = "\u2026"; parentElement.createTextChild(isArray ? "]" : "}"); return preview.lossless; }, _appendEntriesPreview: function(parentElement, preview) { var lossless = preview.lossless && !preview.properties.length; parentElement.createTextChild("{"); for (var i = 0; i < preview.entries.length; ++i) { if (i > 0) parentElement.createTextChild(", "); var entry = preview.entries[i]; if (entry.key) { this.appendObjectPreview(parentElement, entry.key); parentElement.createTextChild(" => "); } this.appendObjectPreview(parentElement, entry.value); } if (preview.overflow) parentElement.createChild("span").textContent = "\u2026"; parentElement.createTextChild("}"); return lossless; }, _renderPropertyPreviewOrAccessor: function(propertyPath) { var property = propertyPath.peekLast(); return this.renderPropertyPreview(property.type, (property.subtype), property.value); }, renderPropertyPreview: function(type, subtype, description) { var span = createElementWithClass("span", "object-value-" + (subtype || type)); description = description || ""; if (type === "function") { span.textContent = "function"; return span; } if (type === "object" && subtype === "node" && description) { span.classList.add("object-value-preview-node"); WebInspector.DOMPresentationUtils.createSpansForNodeTitle(span, description); return span; } if (type === "string") { span.createTextChildren("\"", description.replace(/\n/g, "\u21B5"), "\""); return span; } if (type === "object" && !subtype) { span.textContent = this._abbreviateFullQualifiedClassName(description); return span; } span.textContent = description; return span; }};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 widget = new WebInspector.Widget(); widget.element.className = "settings-tab-container"; widget.element.createChild("header").createChild("h3").createTextChild(WebInspector.UIString("Shortcuts")); var scrollPane = widget.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"); note.appendChild(WebInspector.linkifyDocumentationURLAsNode("shortcuts", WebInspector.UIString("Full list of keyboard shortcuts and gestures"))); return widget; }}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 = createElement("span"); node.className = className; node.textContent = textContent; return node; }, _joinNodes: function(nodes, delimiter) { var result = 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.shortcutRegistry.shortcutDescriptorsForAction("debugger.step-over"), WebInspector.UIString("Step over")); section.addAlternateKeys(WebInspector.shortcutRegistry.shortcutDescriptorsForAction("debugger.step-into"), WebInspector.UIString("Step into")); section.addAlternateKeys(WebInspector.shortcutRegistry.shortcutDescriptorsForAction("debugger.step-out"), WebInspector.UIString("Step out")); if (Runtime.experiments.isEnabled("stepIntoAsync")) section.addAlternateKeys(WebInspector.shortcutRegistry.shortcutDescriptorsForAction("debugger.step-into"), WebInspector.UIString("Step into")); 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.RecordPageReload, WebInspector.UIString("Record page reload")); section.addAlternateKeys(WebInspector.ShortcutsScreen.TimelinePanelShortcuts.SaveToFile, WebInspector.UIString("Save timeline data")); section.addAlternateKeys(WebInspector.ShortcutsScreen.TimelinePanelShortcuts.LoadFromFile, WebInspector.UIString("Load timeline data")); section.addRelatedKeys(WebInspector.ShortcutsScreen.TimelinePanelShortcuts.JumpToPreviousFrame.concat(WebInspector.ShortcutsScreen.TimelinePanelShortcuts.JumpToNextFrame), WebInspector.UIString("Jump to previous/next frame")); section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Profiles Panel")); section.addAlternateKeys(WebInspector.ShortcutsScreen.ProfilesPanelShortcuts.StartStopRecording, WebInspector.UIString("Start/stop recording")); if (Runtime.experiments.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.PanMode, WebInspector.UIString("Switch to pan mode")); section.addAlternateKeys(WebInspector.ShortcutsScreen.LayersPanelShortcuts.RotateMode, WebInspector.UIString("Switch to rotate mode")); section.addAlternateKeys(WebInspector.ShortcutsScreen.LayersPanelShortcuts.TogglePanRotate, WebInspector.UIString("Temporarily toggle pan/rotate mode while held")); section.addAlternateKeys(WebInspector.ShortcutsScreen.LayersPanelShortcuts.ZoomIn, WebInspector.UIString("Zoom in")); section.addAlternateKeys(WebInspector.ShortcutsScreen.LayersPanelShortcuts.ZoomOut, WebInspector.UIString("Zoom out")); section.addRelatedKeys(WebInspector.ShortcutsScreen.LayersPanelShortcuts.Up.concat(WebInspector.ShortcutsScreen.LayersPanelShortcuts.Down), WebInspector.UIString("Pan or rotate up/down")); section.addRelatedKeys(WebInspector.ShortcutsScreen.LayersPanelShortcuts.Left.concat(WebInspector.ShortcutsScreen.LayersPanelShortcuts.Right), WebInspector.UIString("Pan or rotate left/right")); }}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)], 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)], RecordPageReload: [WebInspector.KeyboardShortcut.makeDescriptor("r", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)], SaveToFile: [WebInspector.KeyboardShortcut.makeDescriptor("s", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)], LoadFromFile: [WebInspector.KeyboardShortcut.makeDescriptor("o", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)], JumpToPreviousFrame: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.LeftSquareBracket)], JumpToNextFrame: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.RightSquareBracket)]};WebInspector.ShortcutsScreen.ProfilesPanelShortcuts = { StartStopRecording: [WebInspector.KeyboardShortcut.makeDescriptor("e", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta)]};WebInspector.ShortcutsScreen.LayersPanelShortcuts = { ResetView: [WebInspector.KeyboardShortcut.makeDescriptor("0")], PanMode: [WebInspector.KeyboardShortcut.makeDescriptor("x")], RotateMode: [WebInspector.KeyboardShortcut.makeDescriptor("v")], TogglePanRotate: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Shift)], 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)], Up: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Up), WebInspector.KeyboardShortcut.makeDescriptor("w")], Down: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Down), WebInspector.KeyboardShortcut.makeDescriptor("s")], Left: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Left), WebInspector.KeyboardShortcut.makeDescriptor("a")], Right: [WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Right), WebInspector.KeyboardShortcut.makeDescriptor("d")]};WebInspector.EventListenersView = function(element) { this._element = element; this._treeOutline = new TreeOutlineInShadow("event-listener-tree"); this._treeOutline.registerRequiredCSS("components/objectValue.css"); this._treeOutline.registerRequiredCSS("components/eventListenersView.css"); this._treeOutline.setComparator(WebInspector.EventListenersTreeElement.comparator); this._treeOutline.element.classList.add("monospace"); this._element.appendChild(this._treeOutline.element) this._emptyHolder = createElementWithClass("div", "info"); this._emptyHolder.textContent = WebInspector.UIString("No Event Listeners"); this._linkifier = new WebInspector.Linkifier(); this._treeItemMap = new Map();}WebInspector.EventListenersView.prototype = { addObjects: function(objects) { var promises = []; for (var i = 0; i < objects.length; ++i) promises.push(objects[i].eventListeners()); return Promise.all(promises).then(listenersCallback.bind(this)); function listenersCallback(listeners) { this.reset(); for (var i = 0; i < listeners.length; ++i) this._addObjectEventListeners(objects[i], listeners[i]); this.addEmptyHolderIfNeeded(); this._eventListenersArrivedForTest(); } }, _addObjectEventListeners: function(object, eventListeners) { if (!eventListeners) return; for (var eventListener of eventListeners) { var treeItem = this._getOrCreateTreeElementForType(eventListener.type()); treeItem.addObjectEventListener(eventListener, object); } }, _getOrCreateTreeElementForType: function(type) { var treeItem = this._treeItemMap.get(type); if (!treeItem) { treeItem = new WebInspector.EventListenersTreeElement(type,this._linkifier); this._treeItemMap.set(type, treeItem); this._treeOutline.appendChild(treeItem); this._emptyHolder.remove(); } return treeItem; }, addEmptyHolderIfNeeded: function() { if (!this._treeOutline.firstChild() && !this._emptyHolder.parentNode) this._element.appendChild(this._emptyHolder); }, reset: function() { this._treeItemMap = new Map(); this._treeOutline.removeChildren(); this._linkifier.reset(); }, _eventListenersArrivedForTest: function() {}}WebInspector.EventListenersTreeElement = function(type, linkifier) { TreeElement.call(this, type); this.toggleOnClick = true; this.selectable = false; this._linkifier = linkifier;}WebInspector.EventListenersTreeElement.comparator = function(element1, element2) { if (element1.title === element2.title) return 0; return element1.title > element2.title ? 1 : -1;}WebInspector.EventListenersTreeElement.prototype = { addObjectEventListener: function(eventListener, object) { var treeElement = new WebInspector.ObjectEventListenerBar(eventListener,object,this._linkifier); this.appendChild((treeElement)); }, __proto__: TreeElement.prototype}WebInspector.ObjectEventListenerBar = function(eventListener, object, linkifier) { TreeElement.call(this, "", true); this._eventListener = eventListener; this.editable = false; this.selectable = false; this._setTitle(object, linkifier);}WebInspector.ObjectEventListenerBar.prototype = { onpopulate: function() { var properties = []; var eventListener = this._eventListener; var runtimeModel = eventListener.target().runtimeModel; properties.push(runtimeModel.createRemotePropertyFromPrimitiveValue("useCapture", eventListener.useCapture())); if (typeof eventListener.handler() !== "undefined") properties.push(new WebInspector.RemoteObjectProperty("handler",eventListener.handler())); WebInspector.ObjectPropertyTreeElement.populateWithProperties(this, properties, [], true, null ); }, _setTitle: function(object, linkifier) { var title = this.listItemElement.createChild("span"); var subtitle = this.listItemElement.createChild("span", "event-listener-tree-subtitle"); subtitle.appendChild(linkifier.linkifyRawLocation(this._eventListener.location(), this._eventListener.sourceName())); title.appendChild(WebInspector.ObjectPropertiesSection.createValueElement(object, false)); }, __proto__: TreeElement.prototype};function defineCommonExtensionSymbols(apiPrivate) { if (!apiPrivate.audits) apiPrivate.audits = {}; apiPrivate.audits.Severity = { Info: "info", Warning: "warning", Severe: "severe" }; if (!apiPrivate.panels) apiPrivate.panels = {}; apiPrivate.panels.SearchAction = { CancelSearch: "cancelSearch", PerformSearch: "performSearch", NextSearchResult: "nextSearchResult", PreviousSearchResult: "previousSearchResult" }; apiPrivate.Events = { AuditStarted: "audit-started-", ButtonClicked: "button-clicked-", PanelObjectSelected: "panel-objectSelected-", NetworkRequestFinished: "network-request-finished", OpenResource: "open-resource", PanelSearch: "panel-search-", ResourceAdded: "resource-added", ResourceContentCommitted: "resource-content-committed", ViewShown: "view-shown-", ViewHidden: "view-hidden-" }; apiPrivate.Commands = { AddAuditCategory: "addAuditCategory", AddAuditResult: "addAuditResult", AddRequestHeaders: "addRequestHeaders", ApplyStyleSheet: "applyStyleSheet", CreatePanel: "createPanel", CreateSidebarPane: "createSidebarPane", CreateToolbarButton: "createToolbarButton", EvaluateOnInspectedPage: "evaluateOnInspectedPage", ForwardKeyboardEvent: "_forwardKeyboardEvent", GetHAR: "getHAR", GetPageResources: "getPageResources", GetRequestContent: "getRequestContent", GetResourceContent: "getResourceContent", InspectedURLChanged: "inspectedURLChanged", OpenResource: "openResource", Reload: "Reload", Subscribe: "subscribe", SetOpenResourceHandler: "setOpenResourceHandler", SetResourceContent: "setResourceContent", SetSidebarContent: "setSidebarContent", SetSidebarHeight: "setSidebarHeight", SetSidebarPage: "setSidebarPage", ShowPanel: "showPanel", StopAuditCategoryRun: "stopAuditCategoryRun", Unsubscribe: "unsubscribe", UpdateAuditProgress: "updateAuditProgress", UpdateButton: "updateButton" };}function injectedExtensionAPI(injectedScriptId) { var apiPrivate = {}; defineCommonExtensionSymbols(apiPrivate); var commands = apiPrivate.Commands; var events = apiPrivate.Events; var userAction = false; function EventSinkImpl(type, customDispatch) { this._type = type; this._listeners = []; this._customDispatch = customDispatch; } EventSinkImpl.prototype = { addListener: function(callback) { if (typeof callback !== "function") throw "addListener: callback is not a function"; if (this._listeners.length === 0) extensionServer.sendRequest({ command: commands.Subscribe, type: this._type }); this._listeners.push(callback); extensionServer.registerHandler("notify-" + this._type, this._dispatch.bind(this)); }, removeListener: function(callback) { var listeners = this._listeners; for (var i = 0; i < listeners.length; ++i) { if (listeners[i] === callback) { listeners.splice(i, 1); break; } } if (this._listeners.length === 0) extensionServer.sendRequest({ command: commands.Unsubscribe, type: this._type }); }, _fire: function(vararg) { var listeners = this._listeners.slice(); for (var i = 0; i < listeners.length; ++i) listeners[i].apply(null , arguments); }, _dispatch: function(request) { if (this._customDispatch) this._customDispatch.call(this, request); else this._fire.apply(this, request.arguments); } } function InspectorExtensionAPI() { this.audits = new Audits(); this.inspectedWindow = new InspectedWindow(); this.panels = new Panels(); this.network = new Network(); defineDeprecatedProperty(this, "webInspector", "resources", "network"); } function Network() { function dispatchRequestEvent(message) { var request = message.arguments[1]; request.__proto__ = new Request(message.arguments[0]); this._fire(request); } this.onRequestFinished = new EventSink(events.NetworkRequestFinished,dispatchRequestEvent); defineDeprecatedProperty(this, "network", "onFinished", "onRequestFinished"); this.onNavigated = new EventSink(events.InspectedURLChanged); } Network.prototype = { getHAR: function(callback) { function callbackWrapper(result) { var entries = (result && result.entries) || []; for (var i = 0; i < entries.length; ++i) { entries[i].__proto__ = new Request(entries[i]._requestId); delete entries[i]._requestId; } callback(result); } extensionServer.sendRequest({ command: commands.GetHAR }, callback && callbackWrapper); }, addRequestHeaders: function(headers) { extensionServer.sendRequest({ command: commands.AddRequestHeaders, headers: headers, extensionId: window.location.hostname }); } } function RequestImpl(id) { this._id = id; } RequestImpl.prototype = { getContent: function(callback) { function callbackWrapper(response) { callback(response.content, response.encoding); } extensionServer.sendRequest({ command: commands.GetRequestContent, id: this._id }, callback && callbackWrapper); } } function Panels() { var panels = { elements: new ElementsPanel(), sources: new SourcesPanel(), }; function panelGetter(name) { return panels[name]; } for (var panel in panels) this.__defineGetter__(panel, panelGetter.bind(null , panel)); this.applyStyleSheet = function(styleSheet) { extensionServer.sendRequest({ command: commands.ApplyStyleSheet, styleSheet: styleSheet }); } ; } Panels.prototype = { create: function(title, icon, page, callback) { var id = "extension-panel-" + extensionServer.nextObjectId(); var request = { command: commands.CreatePanel, id: id, title: title, icon: icon, page: page }; extensionServer.sendRequest(request, callback && callback.bind(this, new ExtensionPanel(id))); }, setOpenResourceHandler: function(callback) { var hadHandler = extensionServer.hasHandler(events.OpenResource); function callbackWrapper(message) { userAction = true; try { callback.call(null , new Resource(message.resource), message.lineNumber); } finally { userAction = false; } } if (!callback) extensionServer.unregisterHandler(events.OpenResource); else extensionServer.registerHandler(events.OpenResource, callbackWrapper); if (hadHandler === !callback) extensionServer.sendRequest({ command: commands.SetOpenResourceHandler, "handlerPresent": !!callback }); }, openResource: function(url, lineNumber, callback) { extensionServer.sendRequest({ command: commands.OpenResource, "url": url, "lineNumber": lineNumber }, callback); }, get SearchAction() { return apiPrivate.panels.SearchAction; } } function ExtensionViewImpl(id) { this._id = id; function dispatchShowEvent(message) { var frameIndex = message.arguments[0]; if (typeof frameIndex === "number") this._fire(window.parent.frames[frameIndex]); else this._fire(); } if (id) { this.onShown = new EventSink(events.ViewShown + id,dispatchShowEvent); this.onHidden = new EventSink(events.ViewHidden + id); } } function PanelWithSidebarImpl(hostPanelName) { ExtensionViewImpl.call(this, null ); this._hostPanelName = hostPanelName; this.onSelectionChanged = new EventSink(events.PanelObjectSelected + hostPanelName); } PanelWithSidebarImpl.prototype = { createSidebarPane: function(title, callback) { var id = "extension-sidebar-" + extensionServer.nextObjectId(); var request = { command: commands.CreateSidebarPane, panel: this._hostPanelName, id: id, title: title }; function callbackWrapper() { callback(new ExtensionSidebarPane(id)); } extensionServer.sendRequest(request, callback && callbackWrapper); }, __proto__: ExtensionViewImpl.prototype } function declareInterfaceClass(implConstructor) { return function() { var impl = { __proto__: implConstructor.prototype }; implConstructor.apply(impl, arguments); populateInterfaceClass(this, impl); } ; } function defineDeprecatedProperty(object, className, oldName, newName) { var warningGiven = false; function getter() { if (!warningGiven) { console.warn(className + "." + oldName + " is deprecated. Use " + className + "." + newName + " instead"); warningGiven = true; } return object[newName]; } object.__defineGetter__(oldName, getter); } function extractCallbackArgument(args) { var lastArgument = args[args.length - 1]; return typeof lastArgument === "function" ? lastArgument : undefined; } var AuditCategory = declareInterfaceClass(AuditCategoryImpl); var AuditResult = declareInterfaceClass(AuditResultImpl); var Button = declareInterfaceClass(ButtonImpl); var EventSink = declareInterfaceClass(EventSinkImpl); var ExtensionPanel = declareInterfaceClass(ExtensionPanelImpl); var ExtensionSidebarPane = declareInterfaceClass(ExtensionSidebarPaneImpl); var PanelWithSidebar = declareInterfaceClass(PanelWithSidebarImpl); var Request = declareInterfaceClass(RequestImpl); var Resource = declareInterfaceClass(ResourceImpl); function ElementsPanel() { PanelWithSidebar.call(this, "elements"); } ElementsPanel.prototype = { __proto__: PanelWithSidebar.prototype } function SourcesPanel() { PanelWithSidebar.call(this, "sources"); } SourcesPanel.prototype = { __proto__: PanelWithSidebar.prototype } function ExtensionPanelImpl(id) { ExtensionViewImpl.call(this, id); this.onSearch = new EventSink(events.PanelSearch + id); } ExtensionPanelImpl.prototype = { createStatusBarButton: function(iconPath, tooltipText, disabled) { var id = "button-" + extensionServer.nextObjectId(); var request = { command: commands.CreateToolbarButton, panel: this._id, id: id, icon: iconPath, tooltip: tooltipText, disabled: !!disabled }; extensionServer.sendRequest(request); return new Button(id); }, show: function() { if (!userAction) return; var request = { command: commands.ShowPanel, id: this._id }; extensionServer.sendRequest(request); }, __proto__: ExtensionViewImpl.prototype } function ExtensionSidebarPaneImpl(id) { ExtensionViewImpl.call(this, id); } ExtensionSidebarPaneImpl.prototype = { setHeight: function(height) { extensionServer.sendRequest({ command: commands.SetSidebarHeight, id: this._id, height: height }); }, setExpression: function(expression, rootTitle, evaluateOptions) { var request = { command: commands.SetSidebarContent, id: this._id, expression: expression, rootTitle: rootTitle, evaluateOnPage: true, }; if (typeof evaluateOptions === "object") request.evaluateOptions = evaluateOptions; extensionServer.sendRequest(request, extractCallbackArgument(arguments)); }, setObject: function(jsonObject, rootTitle, callback) { extensionServer.sendRequest({ command: commands.SetSidebarContent, id: this._id, expression: jsonObject, rootTitle: rootTitle }, callback); }, setPage: function(page) { extensionServer.sendRequest({ command: commands.SetSidebarPage, id: this._id, page: page }); }, __proto__: ExtensionViewImpl.prototype } function ButtonImpl(id) { this._id = id; this.onClicked = new EventSink(events.ButtonClicked + id); } ButtonImpl.prototype = { update: function(iconPath, tooltipText, disabled) { var request = { command: commands.UpdateButton, id: this._id, icon: iconPath, tooltip: tooltipText, disabled: !!disabled }; extensionServer.sendRequest(request); } }; function Audits() {} Audits.prototype = { addCategory: function(displayName, resultCount) { var id = "extension-audit-category-" + extensionServer.nextObjectId(); if (typeof resultCount !== "undefined") console.warn("Passing resultCount to audits.addCategory() is deprecated. Use AuditResult.updateProgress() instead."); extensionServer.sendRequest({ command: commands.AddAuditCategory, id: id, displayName: displayName, resultCount: resultCount }); return new AuditCategory(id); } } function AuditCategoryImpl(id) { function dispatchAuditEvent(request) { var auditResult = new AuditResult(request.arguments[0]); try { this._fire(auditResult); } catch (e) { console.error("Uncaught exception in extension audit event handler: " + e); auditResult.done(); } } this._id = id; this.onAuditStarted = new EventSink(events.AuditStarted + id,dispatchAuditEvent); } function AuditResultImpl(id) { this._id = id; this.createURL = this._nodeFactory.bind(this, "url"); this.createSnippet = this._nodeFactory.bind(this, "snippet"); this.createText = this._nodeFactory.bind(this, "text"); this.createObject = this._nodeFactory.bind(this, "object"); this.createNode = this._nodeFactory.bind(this, "node"); } AuditResultImpl.prototype = { addResult: function(displayName, description, severity, details) { if (details && !(details instanceof AuditResultNode)) details = new AuditResultNode(Array.isArray(details) ? details : [details]); var request = { command: commands.AddAuditResult, resultId: this._id, displayName: displayName, description: description, severity: severity, details: details }; extensionServer.sendRequest(request); }, createResult: function() { return new AuditResultNode(Array.prototype.slice.call(arguments)); }, updateProgress: function(worked, totalWork) { extensionServer.sendRequest({ command: commands.UpdateAuditProgress, resultId: this._id, progress: worked / totalWork }); }, done: function() { extensionServer.sendRequest({ command: commands.StopAuditCategoryRun, resultId: this._id }); }, get Severity() { return apiPrivate.audits.Severity; }, createResourceLink: function(url, lineNumber) { return { type: "resourceLink", arguments: [url, lineNumber && lineNumber - 1] }; }, _nodeFactory: function(type) { return { type: type, arguments: Array.prototype.slice.call(arguments, 1) }; } } function AuditResultNode(contents) { this.contents = contents; this.children = []; this.expanded = false; } AuditResultNode.prototype = { addChild: function() { var node = new AuditResultNode(Array.prototype.slice.call(arguments)); this.children.push(node); return node; } }; function InspectedWindow() { function dispatchResourceEvent(message) { this._fire(new Resource(message.arguments[0])); } function dispatchResourceContentEvent(message) { this._fire(new Resource(message.arguments[0]), message.arguments[1]); } this.onResourceAdded = new EventSink(events.ResourceAdded,dispatchResourceEvent); this.onResourceContentCommitted = new EventSink(events.ResourceContentCommitted,dispatchResourceContentEvent); } InspectedWindow.prototype = { reload: function(optionsOrUserAgent) { var options = null ; if (typeof optionsOrUserAgent === "object") { options = optionsOrUserAgent; } else if (typeof optionsOrUserAgent === "string") { options = { userAgent: optionsOrUserAgent }; console.warn("Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. " + "Use inspectedWindow.reload({ userAgent: value}) instead."); } extensionServer.sendRequest({ command: commands.Reload, options: options }); }, eval: function(expression, evaluateOptions) { var callback = extractCallbackArgument(arguments); function callbackWrapper(result) { if (result.isError || result.isException) callback(undefined, result); else callback(result.value); } var request = { command: commands.EvaluateOnInspectedPage, expression: expression }; if (typeof evaluateOptions === "object") request.evaluateOptions = evaluateOptions; extensionServer.sendRequest(request, callback && callbackWrapper); return null ; }, getResources: function(callback) { function wrapResource(resourceData) { return new Resource(resourceData); } function callbackWrapper(resources) { callback(resources.map(wrapResource)); } extensionServer.sendRequest({ command: commands.GetPageResources }, callback && callbackWrapper); } } function ResourceImpl(resourceData) { this._url = resourceData.url; this._type = resourceData.type; } ResourceImpl.prototype = { get url() { return this._url; }, get type() { return this._type; }, getContent: function(callback) { function callbackWrapper(response) { callback(response.content, response.encoding); } extensionServer.sendRequest({ command: commands.GetResourceContent, url: this._url }, callback && callbackWrapper); }, setContent: function(content, commit, callback) { extensionServer.sendRequest({ command: commands.SetResourceContent, url: this._url, content: content, commit: commit }, callback); } } var keyboardEventRequestQueue = []; var forwardTimer = null ; function forwardKeyboardEvent(event) { const Esc = "U+001B"; if (!event.ctrlKey && !event.altKey && !event.metaKey && !/^F\d+$/.test(event.keyIdentifier) && event.keyIdentifier !== Esc) return; var requestPayload = { eventType: event.type, ctrlKey: event.ctrlKey, altKey: event.altKey, metaKey: event.metaKey, keyIdentifier: event.keyIdentifier, location: event.location, keyCode: event.keyCode }; keyboardEventRequestQueue.push(requestPayload); if (!forwardTimer) forwardTimer = setTimeout(forwardEventQueue, 0); } function forwardEventQueue() { forwardTimer = null ; var request = { command: commands.ForwardKeyboardEvent, entries: keyboardEventRequestQueue }; extensionServer.sendRequest(request); keyboardEventRequestQueue = []; } document.addEventListener("keydown", forwardKeyboardEvent, false); document.addEventListener("keypress", forwardKeyboardEvent, false); function ExtensionServerClient() { this._callbacks = {}; this._handlers = {}; this._lastRequestId = 0; this._lastObjectId = 0; this.registerHandler("callback", this._onCallback.bind(this)); var channel = new MessageChannel(); this._port = channel.port1; this._port.addEventListener("message", this._onMessage.bind(this), false); this._port.start(); window.parent.postMessage("registerExtension", [channel.port2], "*"); } ExtensionServerClient.prototype = { sendRequest: function(message, callback) { if (typeof callback === "function") message.requestId = this._registerCallback(callback); this._port.postMessage(message); }, hasHandler: function(command) { return !!this._handlers[command]; }, registerHandler: function(command, handler) { this._handlers[command] = handler; }, unregisterHandler: function(command) { delete this._handlers[command]; }, nextObjectId: function() { return injectedScriptId.toString() + "_" + ++this._lastObjectId; }, _registerCallback: function(callback) { var id = ++this._lastRequestId; this._callbacks[id] = callback; return id; }, _onCallback: function(request) { if (request.requestId in this._callbacks) { var callback = this._callbacks[request.requestId]; delete this._callbacks[request.requestId]; callback(request.result); } }, _onMessage: function(event) { var request = event.data; var handler = this._handlers[request.command]; if (handler) handler.call(this, request); } } function populateInterfaceClass(interfaze, implementation) { for (var member in implementation) { if (member.charAt(0) === "_") continue;var descriptor = null ; for (var owner = implementation; owner && !descriptor; owner = owner.__proto__) descriptor = Object.getOwnPropertyDescriptor(owner, member); if (!descriptor) continue;if (typeof descriptor.value === "function") interfaze[member] = descriptor.value.bind(implementation); else if (typeof descriptor.get === "function") interfaze.__defineGetter__(member, descriptor.get.bind(implementation)); else Object.defineProperty(interfaze, member, descriptor); } } if (!extensionServer) extensionServer = new ExtensionServerClient(); return new InspectorExtensionAPI();}function platformExtensionAPI(coreAPI) { function getTabId() { return tabId; } chrome = window.chrome || {}; var devtools_descriptor = Object.getOwnPropertyDescriptor(chrome, "devtools"); if (!devtools_descriptor || devtools_descriptor.get) Object.defineProperty(chrome, "devtools", { value: {}, enumerable: true }); chrome.devtools.inspectedWindow = {}; chrome.devtools.inspectedWindow.__defineGetter__("tabId", getTabId); chrome.devtools.inspectedWindow.__proto__ = coreAPI.inspectedWindow; chrome.devtools.network = coreAPI.network; chrome.devtools.panels = coreAPI.panels; if (extensionInfo.exposeExperimentalAPIs !== false) { chrome.experimental = chrome.experimental || {}; chrome.experimental.devtools = chrome.experimental.devtools || {}; var properties = Object.getOwnPropertyNames(coreAPI); for (var i = 0; i < properties.length; ++i) { var descriptor = Object.getOwnPropertyDescriptor(coreAPI, properties[i]); Object.defineProperty(chrome.experimental.devtools, properties[i], descriptor); } chrome.experimental.devtools.inspectedWindow = chrome.devtools.inspectedWindow; } if (extensionInfo.exposeWebInspectorNamespace) window.webInspector = coreAPI;}function buildPlatformExtensionAPI(extensionInfo, inspectedTabId) { return "var extensionInfo = " + JSON.stringify(extensionInfo) + ";" + "var tabId = " + inspectedTabId + ";" + platformExtensionAPI.toString();}function buildExtensionAPIInjectedScript(extensionInfo, inspectedTabId) { return "(function(injectedScriptId){ " + "var extensionServer;" + defineCommonExtensionSymbols.toString() + ";" + injectedExtensionAPI.toString() + ";" + buildPlatformExtensionAPI(extensionInfo, inspectedTabId) + ";" + "platformExtensionAPI(injectedExtensionAPI(injectedScriptId));" + "return {};" + "})";};WebInspector.ExtensionAuditCategory = function(extensionOrigin, id, displayName, ruleCount) { this.extensionOrigin = extensionOrigin; this.id = id; this.displayName = displayName; this.ruleCount = ruleCount;}WebInspector.ExtensionAuditCategoryResults = function() {}WebInspector.ExtensionAuditCategoryResults.prototype = { id: function() {}, addResult: function(displayName, description, severity, details) {}, updateProgress: function(progress) {}, done: function() {}};if (!window.InspectorExtensionRegistry) { WebInspector.InspectorExtensionRegistryStub = function() {} WebInspector.InspectorExtensionRegistryStub.prototype = { getExtensionsAsync: function() {} } var InspectorExtensionRegistry = new WebInspector.InspectorExtensionRegistryStub();};WebInspector.ExtensionServer = function() { this._clientObjects = {}; this._handlers = {}; this._subscribers = {}; this._subscriptionStartHandlers = {}; this._subscriptionStopHandlers = {}; this._extraHeaders = {}; this._requests = {}; this._lastRequestId = 0; this._registeredExtensions = {}; this._status = new WebInspector.ExtensionStatus(); this._sidebarPanes = []; this._auditCategories = []; var commands = WebInspector.extensionAPI.Commands; this._registerHandler(commands.AddAuditCategory, this._onAddAuditCategory.bind(this)); this._registerHandler(commands.AddAuditResult, this._onAddAuditResult.bind(this)); this._registerHandler(commands.AddRequestHeaders, this._onAddRequestHeaders.bind(this)); this._registerHandler(commands.ApplyStyleSheet, this._onApplyStyleSheet.bind(this)); this._registerHandler(commands.CreatePanel, this._onCreatePanel.bind(this)); this._registerHandler(commands.CreateSidebarPane, this._onCreateSidebarPane.bind(this)); this._registerHandler(commands.CreateToolbarButton, this._onCreateToolbarButton.bind(this)); this._registerHandler(commands.EvaluateOnInspectedPage, this._onEvaluateOnInspectedPage.bind(this)); this._registerHandler(commands.ForwardKeyboardEvent, this._onForwardKeyboardEvent.bind(this)); this._registerHandler(commands.GetHAR, this._onGetHAR.bind(this)); this._registerHandler(commands.GetPageResources, this._onGetPageResources.bind(this)); this._registerHandler(commands.GetRequestContent, this._onGetRequestContent.bind(this)); this._registerHandler(commands.GetResourceContent, this._onGetResourceContent.bind(this)); this._registerHandler(commands.Reload, this._onReload.bind(this)); this._registerHandler(commands.SetOpenResourceHandler, this._onSetOpenResourceHandler.bind(this)); this._registerHandler(commands.SetResourceContent, this._onSetResourceContent.bind(this)); this._registerHandler(commands.SetSidebarHeight, this._onSetSidebarHeight.bind(this)); this._registerHandler(commands.SetSidebarContent, this._onSetSidebarContent.bind(this)); this._registerHandler(commands.SetSidebarPage, this._onSetSidebarPage.bind(this)); this._registerHandler(commands.ShowPanel, this._onShowPanel.bind(this)); this._registerHandler(commands.StopAuditCategoryRun, this._onStopAuditCategoryRun.bind(this)); this._registerHandler(commands.Subscribe, this._onSubscribe.bind(this)); this._registerHandler(commands.OpenResource, this._onOpenResource.bind(this)); this._registerHandler(commands.Unsubscribe, this._onUnsubscribe.bind(this)); this._registerHandler(commands.UpdateButton, this._onUpdateButton.bind(this)); this._registerHandler(commands.UpdateAuditProgress, this._onUpdateAuditProgress.bind(this)); window.addEventListener("message", this._onWindowMessage.bind(this), false); InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.AddExtensions, this._addExtensions, this); InspectorFrontendHost.events.addEventListener(InspectorFrontendHostAPI.Events.SetInspectedTabId, this._setInspectedTabId, this); this._initExtensions();}WebInspector.ExtensionServer.Events = { SidebarPaneAdded: "SidebarPaneAdded", AuditCategoryAdded: "AuditCategoryAdded"}WebInspector.ExtensionServer.prototype = { initializeExtensions: function() { this._initializeCommandIssued = true; if (this._pendingExtensionInfos) { this._pendingExtensionInfos.forEach(this._addExtension, this); delete this._pendingExtensionInfos; } }, hasExtensions: function() { return !!Object.keys(this._registeredExtensions).length; }, notifySearchAction: function(panelId, action, searchString) { this._postNotification(WebInspector.extensionAPI.Events.PanelSearch + panelId, action, searchString); }, notifyViewShown: function(identifier, frameIndex) { this._postNotification(WebInspector.extensionAPI.Events.ViewShown + identifier, frameIndex); }, notifyViewHidden: function(identifier) { this._postNotification(WebInspector.extensionAPI.Events.ViewHidden + identifier); }, notifyButtonClicked: function(identifier) { this._postNotification(WebInspector.extensionAPI.Events.ButtonClicked + identifier); }, _inspectedURLChanged: function(event) { this._requests = {}; var url = event.data; this._postNotification(WebInspector.extensionAPI.Events.InspectedURLChanged, url); }, startAuditRun: function(categoryId, auditResults) { this._clientObjects[auditResults.id()] = auditResults; this._postNotification("audit-started-" + categoryId, auditResults.id()); }, stopAuditRun: function(auditResults) { delete this._clientObjects[auditResults.id()]; }, hasSubscribers: function(type) { return !!this._subscribers[type]; }, _postNotification: function(type, vararg) { var subscribers = this._subscribers[type]; if (!subscribers) return; var message = { command: "notify-" + type, arguments: Array.prototype.slice.call(arguments, 1) }; for (var i = 0; i < subscribers.length; ++i) subscribers[i].postMessage(message); }, _onSubscribe: function(message, port) { var subscribers = this._subscribers[message.type]; if (subscribers) subscribers.push(port); else { this._subscribers[message.type] = [port]; if (this._subscriptionStartHandlers[message.type]) this._subscriptionStartHandlers[message.type](); } }, _onUnsubscribe: function(message, port) { var subscribers = this._subscribers[message.type]; if (!subscribers) return; subscribers.remove(port); if (!subscribers.length) { delete this._subscribers[message.type]; if (this._subscriptionStopHandlers[message.type]) this._subscriptionStopHandlers[message.type](); } }, _onAddRequestHeaders: function(message) { var id = message.extensionId; if (typeof id !== "string") return this._status.E_BADARGTYPE("extensionId", typeof id, "string"); var extensionHeaders = this._extraHeaders[id]; if (!extensionHeaders) { extensionHeaders = {}; this._extraHeaders[id] = extensionHeaders; } for (var name in message.headers) extensionHeaders[name] = message.headers[name]; var allHeaders = ({}); for (var extension in this._extraHeaders) { var headers = this._extraHeaders[extension]; for (name in headers) { if (typeof headers[name] === "string") allHeaders[name] = headers[name]; } } WebInspector.multitargetNetworkManager.setExtraHTTPHeaders(allHeaders); }, _onApplyStyleSheet: function(message) { if (!Runtime.experiments.isEnabled("applyCustomStylesheet")) return; var styleSheet = createElement("style"); styleSheet.textContent = message.styleSheet; document.head.appendChild(styleSheet); }, _onCreatePanel: function(message, port) { var id = message.id; if (id in this._clientObjects || WebInspector.inspectorView.hasPanel(id)) return this._status.E_EXISTS(id); var page = this._expandResourcePath(port._extensionOrigin, message.page); var panelDescriptor = new WebInspector.ExtensionServerPanelDescriptor(id,message.title,new WebInspector.ExtensionPanel(this,id,page)); this._clientObjects[id] = panelDescriptor; WebInspector.inspectorView.addPanel(panelDescriptor); return this._status.OK(); }, _onShowPanel: function(message) { WebInspector.inspectorView.showPanel(message.id); }, _onCreateToolbarButton: function(message, port) { var panelDescriptor = this._clientObjects[message.panel]; if (!panelDescriptor || !(panelDescriptor instanceof WebInspector.ExtensionServerPanelDescriptor)) return this._status.E_NOTFOUND(message.panel); var button = new WebInspector.ExtensionButton(this,message.id,this._expandResourcePath(port._extensionOrigin, message.icon),message.tooltip,message.disabled); this._clientObjects[message.id] = button; panelDescriptor.panel().then(appendButton); function appendButton(panel) { (panel).addToolbarItem(button.toolbarButton()); } return this._status.OK(); }, _onUpdateButton: function(message, port) { var button = this._clientObjects[message.id]; if (!button || !(button instanceof WebInspector.ExtensionButton)) return this._status.E_NOTFOUND(message.id); button.update(this._expandResourcePath(port._extensionOrigin, message.icon), message.tooltip, message.disabled); return this._status.OK(); }, _onCreateSidebarPane: function(message) { if (message.panel !== "elements" && message.panel !== "sources") return this._status.E_NOTFOUND(message.panel); var id = message.id; var sidebar = new WebInspector.ExtensionSidebarPane(this,message.panel,message.title,id); this._sidebarPanes.push(sidebar); this._clientObjects[id] = sidebar; this.dispatchEventToListeners(WebInspector.ExtensionServer.Events.SidebarPaneAdded, sidebar); return this._status.OK(); }, sidebarPanes: function() { return this._sidebarPanes; }, _onSetSidebarHeight: function(message) { var sidebar = this._clientObjects[message.id]; if (!sidebar) return this._status.E_NOTFOUND(message.id); sidebar.setHeight(message.height); return this._status.OK(); }, _onSetSidebarContent: function(message, port) { var sidebar = this._clientObjects[message.id]; if (!sidebar) return this._status.E_NOTFOUND(message.id); function callback(error) { var result = error ? this._status.E_FAILED(error) : this._status.OK(); this._dispatchCallback(message.requestId, port, result); } if (message.evaluateOnPage) return sidebar.setExpression(message.expression, message.rootTitle, message.evaluateOptions, port._extensionOrigin, callback.bind(this)); sidebar.setObject(message.expression, message.rootTitle, callback.bind(this)); }, _onSetSidebarPage: function(message, port) { var sidebar = this._clientObjects[message.id]; if (!sidebar) return this._status.E_NOTFOUND(message.id); sidebar.setPage(this._expandResourcePath(port._extensionOrigin, message.page)); }, _onOpenResource: function(message) { var uiSourceCode = WebInspector.networkMapping.uiSourceCodeForURLForAnyTarget(message.url); if (uiSourceCode) { WebInspector.Revealer.reveal(uiSourceCode.uiLocation(message.lineNumber, 0)); return this._status.OK(); } var resource = WebInspector.resourceForURL(message.url); if (resource) { WebInspector.Revealer.reveal(resource, message.lineNumber); return this._status.OK(); } var request = WebInspector.NetworkLog.requestForURL(message.url); if (request) { WebInspector.Revealer.reveal(request); return this._status.OK(); } return this._status.E_NOTFOUND(message.url); }, _onSetOpenResourceHandler: function(message, port) { var name = this._registeredExtensions[port._extensionOrigin].name || ("Extension " + port._extensionOrigin); if (message.handlerPresent) WebInspector.openAnchorLocationRegistry.registerHandler(name, this._handleOpenURL.bind(this, port)); else WebInspector.openAnchorLocationRegistry.unregisterHandler(name); }, _handleOpenURL: function(port, details) { var url = (details.url); var contentProvider = WebInspector.workspace.uiSourceCodeForOriginURL(url) || WebInspector.resourceForURL(url); if (!contentProvider) return false; var lineNumber = details.lineNumber; if (typeof lineNumber === "number") lineNumber += 1; port.postMessage({ command: "open-resource", resource: this._makeResource(contentProvider), lineNumber: lineNumber }); return true; }, _onReload: function(message) { var options = (message.options || {}); WebInspector.multitargetNetworkManager.setUserAgentOverride(typeof options.userAgent === "string" ? options.userAgent : ""); var injectedScript; if (options.injectedScript) injectedScript = "(function(){" + options.injectedScript + "})()"; var target = WebInspector.targetManager.mainTarget(); target.resourceTreeModel.reloadPage(!!options.ignoreCache, injectedScript); return this._status.OK(); }, _onEvaluateOnInspectedPage: function(message, port) { function callback(error, remoteObject, wasThrown) { var result; if (error || !remoteObject) result = this._status.E_PROTOCOLERROR(error.toString()); else if (wasThrown) result = { isException: true, value: remoteObject.description }; else result = { value: remoteObject.value }; this._dispatchCallback(message.requestId, port, result); } return this.evaluate(message.expression, true, true, message.evaluateOptions, port._extensionOrigin, callback.bind(this)); }, _onGetHAR: function() { var requests = WebInspector.NetworkLog.requests(); var harLog = (new WebInspector.HARLog(requests)).build(); for (var i = 0; i < harLog.entries.length; ++i) harLog.entries[i]._requestId = this._requestId(requests[i]); return harLog; }, _makeResource: function(contentProvider) { return { url: contentProvider.contentURL(), type: contentProvider.contentType().name() }; }, _onGetPageResources: function() { var resources = {}; function pushResourceData(contentProvider) { if (!resources[contentProvider.contentURL()]) resources[contentProvider.contentURL()] = this._makeResource(contentProvider); } var uiSourceCodes = WebInspector.workspace.uiSourceCodesForProjectType(WebInspector.projectTypes.Network); uiSourceCodes = uiSourceCodes.concat(WebInspector.workspace.uiSourceCodesForProjectType(WebInspector.projectTypes.ContentScripts)); uiSourceCodes.forEach(pushResourceData.bind(this)); for (var target of WebInspector.targetManager.targets()) target.resourceTreeModel.forAllResources(pushResourceData.bind(this)); return Object.values(resources); }, _getResourceContent: function(contentProvider, message, port) { function onContentAvailable(content) { var contentEncoded = false; if (contentProvider instanceof WebInspector.Resource) contentEncoded = contentProvider.contentEncoded; if (contentProvider instanceof WebInspector.NetworkRequest) contentEncoded = contentProvider.contentEncoded; var response = { encoding: contentEncoded && content ? "base64" : "", content: content }; this._dispatchCallback(message.requestId, port, response); } contentProvider.requestContent(onContentAvailable.bind(this)); }, _onGetRequestContent: function(message, port) { var request = this._requestById(message.id); if (!request) return this._status.E_NOTFOUND(message.id); this._getResourceContent(request, message, port); }, _onGetResourceContent: function(message, port) { var url = (message.url); var contentProvider = WebInspector.workspace.uiSourceCodeForOriginURL(url) || WebInspector.resourceForURL(url); if (!contentProvider) return this._status.E_NOTFOUND(url); this._getResourceContent(contentProvider, message, port); }, _onSetResourceContent: function(message, port) { function callbackWrapper(error) { var response = error ? this._status.E_FAILED(error) : this._status.OK(); this._dispatchCallback(message.requestId, port, response); } var url = (message.url); var uiSourceCode = WebInspector.workspace.uiSourceCodeForOriginURL(url); if (!uiSourceCode) { var resource = WebInspector.ResourceTreeModel.resourceForURL(url); if (!resource) return this._status.E_NOTFOUND(url); return this._status.E_NOTSUPPORTED("Resource is not editable"); } uiSourceCode.setWorkingCopy(message.content); if (message.commit) uiSourceCode.commitWorkingCopy(); callbackWrapper.call(this, null ); }, _requestId: function(request) { if (!request._extensionRequestId) { request._extensionRequestId = ++this._lastRequestId; this._requests[request._extensionRequestId] = request; } return request._extensionRequestId; }, _requestById: function(id) { return this._requests[id]; }, _onAddAuditCategory: function(message, port) { var category = new WebInspector.ExtensionAuditCategory(port._extensionOrigin,message.id,message.displayName,message.resultCount); this._clientObjects[message.id] = category; this._auditCategories.push(category); this.dispatchEventToListeners(WebInspector.ExtensionServer.Events.AuditCategoryAdded, category); }, auditCategories: function() { return this._auditCategories; }, _onAddAuditResult: function(message) { var auditResult = (this._clientObjects[message.resultId]); if (!auditResult) return this._status.E_NOTFOUND(message.resultId); try { auditResult.addResult(message.displayName, message.description, message.severity, message.details); } catch (e) { return e; } return this._status.OK(); }, _onUpdateAuditProgress: function(message) { var auditResult = (this._clientObjects[message.resultId]); if (!auditResult) return this._status.E_NOTFOUND(message.resultId); auditResult.updateProgress(Math.min(Math.max(0, message.progress), 1)); }, _onStopAuditCategoryRun: function(message) { var auditRun = (this._clientObjects[message.resultId]); if (!auditRun) return this._status.E_NOTFOUND(message.resultId); auditRun.done(); }, _onForwardKeyboardEvent: function(message) { const Esc = "U+001B"; message.entries.forEach(handleEventEntry); function handleEventEntry(entry) { if (!entry.ctrlKey && !entry.altKey && !entry.metaKey && !/^F\d+$/.test(entry.keyIdentifier) && entry.keyIdentifier !== Esc) return; var event = new window.KeyboardEvent(entry.eventType,{ keyIdentifier: entry.keyIdentifier, location: entry.location, ctrlKey: entry.ctrlKey, altKey: entry.altKey, shiftKey: entry.shiftKey, metaKey: entry.metaKey }); event.__keyCode = keyCodeForEntry(entry); document.dispatchEvent(event); } function keyCodeForEntry(entry) { var keyCode = entry.keyCode; if (!keyCode) { var match = entry.keyIdentifier.match(/^U\+([\dA-Fa-f]+)$/); if (match) keyCode = parseInt(match[1], 16); } return keyCode || 0; } }, _dispatchCallback: function(requestId, port, result) { if (requestId) port.postMessage({ command: "callback", requestId: requestId, result: result }); }, _initExtensions: function() { this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ResourceAdded, WebInspector.workspace, WebInspector.Workspace.Events.UISourceCodeAdded, this._notifyResourceAdded); this._registerAutosubscriptionTargetManagerHandler(WebInspector.extensionAPI.Events.NetworkRequestFinished, WebInspector.NetworkManager, WebInspector.NetworkManager.EventTypes.RequestFinished, this._notifyRequestFinished); function onElementsSubscriptionStarted() { WebInspector.notifications.addEventListener(WebInspector.NotificationService.Events.SelectedNodeChanged, this._notifyElementsSelectionChanged, this); } function onElementsSubscriptionStopped() { WebInspector.notifications.removeEventListener(WebInspector.NotificationService.Events.SelectedNodeChanged, this._notifyElementsSelectionChanged, this); } this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.PanelObjectSelected + "elements", onElementsSubscriptionStarted.bind(this), onElementsSubscriptionStopped.bind(this)); this._registerResourceContentCommittedHandler(this._notifyUISourceCodeContentCommitted); WebInspector.targetManager.addEventListener(WebInspector.TargetManager.Events.InspectedURLChanged, this._inspectedURLChanged, this); InspectorExtensionRegistry.getExtensionsAsync(); }, _notifyResourceAdded: function(event) { var uiSourceCode = (event.data); this._postNotification(WebInspector.extensionAPI.Events.ResourceAdded, this._makeResource(uiSourceCode)); }, _notifyUISourceCodeContentCommitted: function(event) { var uiSourceCode = (event.data.uiSourceCode); var content = (event.data.content); this._postNotification(WebInspector.extensionAPI.Events.ResourceContentCommitted, this._makeResource(uiSourceCode), content); }, _notifyRequestFinished: function(event) { var request = (event.data); this._postNotification(WebInspector.extensionAPI.Events.NetworkRequestFinished, this._requestId(request), (new WebInspector.HAREntry(request)).build()); }, _notifyElementsSelectionChanged: function() { this._postNotification(WebInspector.extensionAPI.Events.PanelObjectSelected + "elements"); }, _addExtensions: function(event) { if (WebInspector.extensionServer._overridePlatformExtensionAPIForTest) window.buildPlatformExtensionAPI = WebInspector.extensionServer._overridePlatformExtensionAPIForTest; var extensionInfos = (event.data); if (this._initializeCommandIssued) extensionInfos.forEach(this._addExtension, this); else this._pendingExtensionInfos = extensionInfos; }, _setInspectedTabId: function(event) { this._inspectedTabId = (event.data); }, _addExtension: function(extensionInfo) { const urlOriginRegExp = new RegExp("([^:]+:\/\/[^/]*)\/"); var startPage = extensionInfo.startPage; var name = extensionInfo.name; try { var originMatch = urlOriginRegExp.exec(startPage); if (!originMatch) { console.error("Skipping extension with invalid URL: " + startPage); return false; } var extensionOrigin = originMatch[1]; if (!this._registeredExtensions[extensionOrigin]) { InspectorFrontendHost.setInjectedScriptForOrigin(extensionOrigin, buildExtensionAPIInjectedScript(extensionInfo, this._inspectedTabId)); this._registeredExtensions[extensionOrigin] = { name: name }; } var iframe = createElement("iframe"); iframe.src = startPage; iframe.style.display = "none"; document.body.appendChild(iframe); } catch (e) { console.error("Failed to initialize extension " + startPage + ":" + e); return false; } return true; }, _registerExtension: function(origin, port) { if (!this._registeredExtensions.hasOwnProperty(origin)) { if (origin !== window.location.origin) console.error("Ignoring unauthorized client request from " + origin); return; } port._extensionOrigin = origin; port.addEventListener("message", this._onmessage.bind(this), false); port.start(); }, _onWindowMessage: function(event) { if (event.data === "registerExtension") this._registerExtension(event.origin, event.ports[0]); }, _onmessage: function(event) { var message = event.data; var result; if (message.command in this._handlers) result = this._handlers[message.command](message, event.target); else result = this._status.E_NOTSUPPORTED(message.command); if (result && message.requestId) this._dispatchCallback(message.requestId, event.target, result); }, _registerHandler: function(command, callback) { console.assert(command); this._handlers[command] = callback; }, _registerSubscriptionHandler: function(eventTopic, onSubscribeFirst, onUnsubscribeLast) { this._subscriptionStartHandlers[eventTopic] = onSubscribeFirst; this._subscriptionStopHandlers[eventTopic] = onUnsubscribeLast; }, _registerAutosubscriptionHandler: function(eventTopic, eventTarget, frontendEventType, handler) { this._registerSubscriptionHandler(eventTopic, eventTarget.addEventListener.bind(eventTarget, frontendEventType, handler, this), eventTarget.removeEventListener.bind(eventTarget, frontendEventType, handler, this)); }, _registerAutosubscriptionTargetManagerHandler: function(eventTopic, modelClass, frontendEventType, handler) { this._registerSubscriptionHandler(eventTopic, WebInspector.targetManager.addModelListener.bind(WebInspector.targetManager, modelClass, frontendEventType, handler, this), WebInspector.targetManager.removeModelListener.bind(WebInspector.targetManager, modelClass, frontendEventType, handler, this)); }, _registerResourceContentCommittedHandler: function(handler) { function addFirstEventListener() { WebInspector.workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeContentCommitted, handler, this); WebInspector.workspace.setHasResourceContentTrackingExtensions(true); } function removeLastEventListener() { WebInspector.workspace.setHasResourceContentTrackingExtensions(false); WebInspector.workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeContentCommitted, handler, this); } this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.ResourceContentCommitted, addFirstEventListener.bind(this), removeLastEventListener.bind(this)); }, _expandResourcePath: function(extensionPath, resourcePath) { if (!resourcePath) return; return extensionPath + this._normalizePath(resourcePath); }, _normalizePath: function(path) { var source = path.split("/"); var result = []; for (var i = 0; i < source.length; ++i) { if (source[i] === ".") continue;if (source[i] === "") continue;if (source[i] === "..") result.pop(); else result.push(source[i]); } return "/" + result.join("/"); }, evaluate: function(expression, exposeCommandLineAPI, returnByValue, options, securityOrigin, callback) { var contextId; function resolveURLToFrame(url) { var found; function hasMatchingURL(frame) { found = (frame.url === url) ? frame : null ; return found; } WebInspector.ResourceTreeModel.frames().some(hasMatchingURL); return found; } if (typeof options === "object") { var frame = options.frameURL ? resolveURLToFrame(options.frameURL) : WebInspector.targetManager.mainTarget().resourceTreeModel.mainFrame; if (!frame) { if (options.frameURL) console.warn("evaluate: there is no frame with URL " + options.frameURL); else console.warn("evaluate: the main frame is not yet available"); return this._status.E_NOTFOUND(options.frameURL || "<top>"); } var contextSecurityOrigin; if (options.useContentScriptContext) contextSecurityOrigin = securityOrigin; else if (options.scriptExecutionContext) contextSecurityOrigin = options.scriptExecutionContext; var context; var executionContexts = frame.target().runtimeModel.executionContexts(); if (contextSecurityOrigin) { for (var i = 0; i < executionContexts.length; ++i) { var executionContext = executionContexts[i]; if (executionContext.frameId === frame.id && executionContext.origin === contextSecurityOrigin && !executionContext.isMainWorldContext) context = executionContext; } if (!context) { console.warn("The JavaScript context " + contextSecurityOrigin + " was not found in the frame " + frame.url) return this._status.E_NOTFOUND(contextSecurityOrigin) } } else { for (var i = 0; i < executionContexts.length; ++i) { var executionContext = executionContexts[i]; if (executionContext.frameId === frame.id && executionContext.isMainWorldContext) context = executionContext; } if (!context) return this._status.E_FAILED(frame.url + " has no execution context"); } contextId = context.id; } var target = target ? target : WebInspector.targetManager.mainTarget(); if (!target) return; target.runtimeAgent().evaluate(expression, "extension", exposeCommandLineAPI, true, contextId, returnByValue, false, onEvalute); function onEvalute(error, result, wasThrown) { if (error) { callback(error, null , wasThrown); return; } callback(error, target.runtimeModel.createRemoteObject(result), wasThrown); } }, __proto__: WebInspector.Object.prototype}WebInspector.ExtensionServerPanelDescriptor = function(name, title, panel) { this._name = name; this._title = title; this._panel = panel;}WebInspector.ExtensionServerPanelDescriptor.prototype = { name: function() { return this._name; }, title: function() { return this._title; }, panel: function() { return Promise.resolve(this._panel); }}WebInspector.ExtensionStatus = function() { function makeStatus(code, description) { var details = Array.prototype.slice.call(arguments, 2); var status = { code: code, description: description, details: details }; if (code !== "OK") { status.isError = true; console.log("Extension server error: " + String.vsprintf(description, details)); } return status; } this.OK = makeStatus.bind(null , "OK", "OK"); this.E_EXISTS = makeStatus.bind(null , "E_EXISTS", "Object already exists: %s"); this.E_BADARG = makeStatus.bind(null , "E_BADARG", "Invalid argument %s: %s"); this.E_BADARGTYPE = makeStatus.bind(null , "E_BADARGTYPE", "Invalid type for argument %s: got %s, expected %s"); this.E_NOTFOUND = makeStatus.bind(null , "E_NOTFOUND", "Object not found: %s"); this.E_NOTSUPPORTED = makeStatus.bind(null , "E_NOTSUPPORTED", "Object does not support requested operation: %s"); this.E_PROTOCOLERROR = makeStatus.bind(null , "E_PROTOCOLERROR", "Inspector protocol error: %s"); this.E_FAILED = makeStatus.bind(null , "E_FAILED", "Operation failed: %s");}WebInspector.ExtensionStatus.Record;WebInspector.extensionAPI = {};defineCommonExtensionSymbols(WebInspector.extensionAPI);;WebInspector.ExtensionPanel = function(server, id, pageURL) { WebInspector.Panel.call(this, id); this._server = server; this.setHideOnDetach(); this._panelToolbar = new WebInspector.Toolbar(this.element); this._panelToolbar.element.classList.add("hidden"); this._searchableView = new WebInspector.SearchableView(this); this._searchableView.show(this.element); var extensionView = new WebInspector.ExtensionView(server,id,pageURL,"extension"); extensionView.show(this._searchableView.element); this.setDefaultFocusedElement(extensionView.defaultFocusedElement());}WebInspector.ExtensionPanel.prototype = { defaultFocusedElement: function() { return WebInspector.Widget.prototype.defaultFocusedElement.call(this); }, addToolbarItem: function(item) { this._panelToolbar.element.classList.remove("hidden"); this._panelToolbar.appendToolbarItem(item); }, searchCanceled: function() { this._server.notifySearchAction(this.name, WebInspector.extensionAPI.panels.SearchAction.CancelSearch); this._searchableView.updateSearchMatchesCount(0); }, searchableView: function() { return this._searchableView; }, performSearch: function(searchConfig, shouldJump, jumpBackwards) { var query = searchConfig.query; this._server.notifySearchAction(this.name, WebInspector.extensionAPI.panels.SearchAction.PerformSearch, query); }, jumpToNextSearchResult: function() { this._server.notifySearchAction(this.name, WebInspector.extensionAPI.panels.SearchAction.NextSearchResult); }, jumpToPreviousSearchResult: function() { this._server.notifySearchAction(this.name, WebInspector.extensionAPI.panels.SearchAction.PreviousSearchResult); }, supportsCaseSensitiveSearch: function() { return false; }, supportsRegexSearch: function() { return false; }, __proto__: WebInspector.Panel.prototype}WebInspector.ExtensionButton = function(server, id, iconURL, tooltip, disabled) { this._id = id; this._toolbarButton = new WebInspector.ToolbarButton("","extension"); this._toolbarButton.addEventListener("click", server.notifyButtonClicked.bind(server, this._id)); this.update(iconURL, tooltip, disabled);}WebInspector.ExtensionButton.prototype = { update: function(iconURL, tooltip, disabled) { if (typeof iconURL === "string") this._toolbarButton.setBackgroundImage(iconURL); if (typeof tooltip === "string") this._toolbarButton.setTitle(tooltip); if (typeof disabled === "boolean") this._toolbarButton.setEnabled(!disabled); }, toolbarButton: function() { return this._toolbarButton; }}WebInspector.ExtensionSidebarPane = function(server, panelName, title, id) { WebInspector.SidebarPane.call(this, title); this.setHideOnDetach(); this._panelName = panelName; this._server = server; this._id = id;}WebInspector.ExtensionSidebarPane.prototype = { id: function() { return this._id; }, panelName: function() { return this._panelName; }, setObject: function(object, title, callback) { this._createObjectPropertiesView(); this._setObject(WebInspector.RemoteObject.fromLocalObject(object), title, callback); }, setExpression: function(expression, title, evaluateOptions, securityOrigin, callback) { this._createObjectPropertiesView(); this._server.evaluate(expression, true, false, evaluateOptions, securityOrigin, this._onEvaluate.bind(this, title, callback)); }, setPage: function(url) { if (this._objectPropertiesView) { this._objectPropertiesView.detach(); delete this._objectPropertiesView; } if (this._extensionView) this._extensionView.detach(true); this._extensionView = new WebInspector.ExtensionView(this._server,this._id,url,"extension fill"); this._extensionView.show(this.element); if (!this.element.style.height) this.setHeight("150px"); }, setHeight: function(height) { this.element.style.height = height; }, _onEvaluate: function(title, callback, error, result, wasThrown) { if (error) callback(error.toString()); else this._setObject((result), title, callback); }, _createObjectPropertiesView: function() { if (this._objectPropertiesView) return; if (this._extensionView) { this._extensionView.detach(true); delete this._extensionView; } this._objectPropertiesView = new WebInspector.ExtensionNotifierView(this._server,this._id); this._objectPropertiesView.show(this.element); }, _setObject: function(object, title, callback) { if (!this._objectPropertiesView) { callback("operation cancelled"); return; } this._objectPropertiesView.element.removeChildren(); var section = new WebInspector.ObjectPropertiesSection(object,title); if (!title) section.titleLessMode(); section.expand(); section.editable = false; this._objectPropertiesView.element.appendChild(section.element); callback(); }, __proto__: WebInspector.SidebarPane.prototype};WebInspector.ExtensionView = function(server, id, src, className) { WebInspector.Widget.call(this); this.element.className = "vbox flex-auto"; this._server = server; this._id = id; this._iframe = createElement("iframe"); this._iframe.addEventListener("load", this._onLoad.bind(this), false); this._iframe.src = src; this._iframe.className = className; this.setDefaultFocusedElement(this._iframe); this.element.appendChild(this._iframe);}WebInspector.ExtensionView.prototype = { wasShown: function() { if (typeof this._frameIndex === "number") this._server.notifyViewShown(this._id, this._frameIndex); }, willHide: function() { if (typeof this._frameIndex === "number") this._server.notifyViewHidden(this._id); }, _onLoad: function() { var frames = (window.frames); this._frameIndex = Array.prototype.indexOf.call(frames, this._iframe.contentWindow); if (this.isShowing()) this._server.notifyViewShown(this._id, this._frameIndex); }, __proto__: WebInspector.Widget.prototype}WebInspector.ExtensionNotifierView = function(server, id) { WebInspector.VBox.call(this); this._server = server; this._id = id;}WebInspector.ExtensionNotifierView.prototype = { wasShown: function() { this._server.notifyViewShown(this._id); }, willHide: function() { this._server.notifyViewHidden(this._id); }, __proto__: WebInspector.VBox.prototype};WebInspector.OverridesSupport = function() { 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.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.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.screenOrientationOverride = WebInspector.settings.createSetting("screenOrientationOverride", ""); this.settings.overrideCSSMedia = WebInspector.settings.createSetting("overrideCSSMedia", false); this.settings.emulatedCSSMedia = WebInspector.settings.createSetting("emulatedCSSMedia", "print"); this.settings.javaScriptDisabled = WebInspector.moduleSetting("javaScriptDisabled");}WebInspector.OverridesSupport.Events = { OverridesWarningUpdated: "OverridesWarningUpdated", EmulationStateChanged: "EmulationStateChanged"}WebInspector.OverridesSupport.MaxDeviceSize = 9999;WebInspector.OverridesSupport.PageResizer = function() {};WebInspector.OverridesSupport.PageResizer.Events = { AvailableSizeChanged: "AvailableSizeChanged", ResizeRequested: "ResizeRequested", FixedScaleRequested: "FixedScaleRequested", InsetsChanged: "InsetsChanged"};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 && !longitudeString) 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.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.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._touchEventsScriptIdSymbol = Symbol("OverridesSupport.touchEventsScriptIdSymbol");WebInspector.OverridesSupport.prototype = { canEmulate: function() { return !!this._target && this._targetCanEmulate; }, 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.emulationAgent().resetScrollAndPageScaleFactor(); } }, init: function(target, callback) { if (target.isPage()) target.emulationAgent().canEmulate(canEmulateCallback.bind(this)); else canEmulateCallback.call(this, null , false); function canEmulateCallback(error, canEmulate) { this._target = target; this._targetCanEmulate = !error && canEmulate; this._initialized = true; if (this.canEmulate()) { target.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._onMainFrameNavigated, this); var domModel = WebInspector.DOMModel.fromTarget(this._target); if (domModel) domModel.addEventListener(WebInspector.DOMModel.Events.InspectModeWillBeToggled, this._inspectModeWillBeToggled, this); this._applyInitialOverrides(); } this.dispatchEventToListeners(WebInspector.OverridesSupport.Events.EmulationStateChanged); callback(); } }, setPageResizer: function(pageResizer, availableSize, insets) { 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.removeEventListener(WebInspector.OverridesSupport.PageResizer.Events.InsetsChanged, this._onPageResizerInsetsChanged, this); } this._pageResizer = pageResizer; this._pageResizerAvailableSize = availableSize; this._pageResizerInsets = insets; 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); this._pageResizer.addEventListener(WebInspector.OverridesSupport.PageResizer.Events.InsetsChanged, this._onPageResizerInsetsChanged, this); } 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.emulationAgent().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.screenOrientationOverride.set(""); this.settings.overrideGeolocation.set(false); this.settings.overrideCSSMedia.set(false); 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; }, _inspectModeWillBeToggled: function(event) { var inspectModeEnabled = (event.data); this._touchEmulationSuspended = inspectModeEnabled; this._emulateTouchEventsChanged(); }, _applyInitialOverrides: function() { 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._screenOrientationChanged, this); this.settings.screenOrientationOverride.addChangeListener(this._screenOrientationChanged, 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.javaScriptDisabled.addChangeListener(this._javaScriptDisabledChanged, this); this._javaScriptDisabledChanged(); this.settings._emulationEnabled.addChangeListener(this._showRulersChanged, this); WebInspector.moduleSetting("showMetricsRulers").addChangeListener(this._showRulersChanged, this); this._showRulersChanged(); if (this.emulationEnabled()) { if (this.settings.overrideDeviceOrientation.get()) this._deviceOrientationChanged(); if (this.settings.screenOrientationOverride.get()) this._screenOrientationChanged(); 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.emulationAgent().resetScrollAndPageScaleFactor(); this._userAgentChanged(); } }, _userAgentChanged: function() { if (this._userAgentChangedListenerMuted) return; var userAgent = this.emulationEnabled() ? this.settings.userAgent.get() : ""; WebInspector.multitargetNetworkManager.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.size); this._pageResizerInsets = (event.data.insets); this._deviceMetricsChanged(); }, _onPageResizerInsetsChanged: function(event) { this._pageResizerInsets = (event.data); }, _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); this._deviceMetricsChanged(); }, _deviceMetricsChanged: function() { if (!this._initialized) return; 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 screenWidth = dipWidth; var screenHeight = dipHeight; var positionX = 0; var positionY = 0; var scale = 1; if (this._pageResizer) { var available = this._pageResizerAvailableSize; var insets = this._pageResizerInsets; if (this.settings.deviceFitWindow.get()) { if (this._fixedDeviceScale) { scale = this._deviceScale; } else { scale = 1; while (available.width < (dipWidth + insets.left + insets.right) * scale || available.height < (dipHeight + insets.top + insets.bottom) * scale) scale *= 0.8; } } this._pageResizer.update(Math.min(dipWidth * scale, available.width - insets.left * scale), Math.min(dipHeight * scale, available.height - insets.top * scale), 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); screenWidth = dipWidth + insets.left + insets.right; screenHeight = dipHeight + insets.top + insets.bottom; positionX = insets.left; positionY = insets.top; } this._deviceScale = scale; this._deviceMetricsThrottler.schedule(setDeviceMetricsOverride.bind(this)); function setDeviceMetricsOverride(finishCallback) { this._target.emulationAgent().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, screenWidth, screenHeight, positionX, positionY, apiCallback.bind(this, finishCallback)); } function clearDeviceMetricsOverride(finishCallback) { this._target.emulationAgent().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()) { this._target.emulationAgent().clearGeolocationOverride(); return; } var geolocation = WebInspector.OverridesSupport.GeolocationPosition.parseSetting(this.settings.geolocationOverride.get()); if (geolocation.error) this._target.emulationAgent().setGeolocationOverride(); else this._target.emulationAgent().setGeolocationOverride(geolocation.latitude, geolocation.longitude, 150); }, _deviceOrientationChanged: function() { if (!this.emulationEnabled() || !this.settings.overrideDeviceOrientation.get()) { this._target.deviceOrientationAgent().clearDeviceOrientationOverride(); return; } var deviceOrientation = WebInspector.OverridesSupport.DeviceOrientation.parseSetting(this.settings.deviceOrientationOverride.get()); this._target.deviceOrientationAgent().setDeviceOrientationOverride(deviceOrientation.alpha, deviceOrientation.beta, deviceOrientation.gamma); }, _screenOrientationChanged: function() { if (!this.emulationEnabled() || !this.settings.screenOrientationOverride.get()) { this._target.screenOrientationAgent().clearScreenOrientationOverride(); return; } var screenOrientation = this.settings.screenOrientationOverride.get(); this._target.screenOrientationAgent().setScreenOrientationOverride(screenOrientation === "landscapePrimary" ? 90 : 0, screenOrientation); }, _emulateTouchEventsChanged: function() { var emulationEnabled = this.emulationEnabled() && this.settings.emulateTouch.get() && !this._touchEmulationSuspended; var configuration = this.settings.emulateMobile.get() ? "mobile" : "desktop"; var target = this._target; 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 }); } } } var symbol = WebInspector.OverridesSupport._touchEventsScriptIdSymbol; if (emulationEnabled && target[symbol] !== -1) { target[symbol] = -1; target.pageAgent().addScriptToEvaluateOnLoad("(" + injectedFunction.toString() + ")()", scriptAddedCallback); } else { if (typeof target[symbol] !== "undefined") { target.pageAgent().removeScriptToEvaluateOnLoad(target[symbol]); delete target[symbol]; } } function scriptAddedCallback(error, scriptId) { if (error) delete target[symbol]; else target[symbol] = scriptId; } target.emulationAgent().setTouchEmulationEnabled(emulationEnabled, configuration); }, _cssMediaChanged: function() { var enabled = this.emulationEnabled() && this.settings.overrideCSSMedia.get(); this._target.emulationAgent().setEmulatedMedia(enabled ? this.settings.emulatedCSSMedia.get() : ""); var cssModel = WebInspector.CSSStyleModel.fromTarget(this._target); if (cssModel) cssModel.mediaQueryResultChanged(); }, _javaScriptDisabledChanged: function() { this._target.emulationAgent().setScriptExecutionDisabled(this.settings.javaScriptDisabled.get()); }, _pageResizerActive: function() { return this._pageResizer && this.emulationEnabled(); }, _showRulersChanged: function() { var showRulersValue = WebInspector.moduleSetting("showMetricsRulers").get(); for (var target of WebInspector.targetManager.targets(WebInspector.Target.Type.Page)) { target.pageAgent().setShowViewportSizeOnResize(!this._pageResizerActive(), showRulersValue); var domModel = WebInspector.DOMModel.fromTarget(target); if (domModel) domModel.setHighlightSettings(showRulersValue && !this._pageResizerActive(), showRulersValue); } }, _onMainFrameNavigated: function() { 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 this._deviceMetricsWarningMessage || this._userAgentWarningMessage || ""; }, clearWarningMessage: function() { this._deviceMetricsWarningMessage = ""; this._userAgentWarningMessage = ""; this._dispatchWarningChanged(); }, 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); }, __proto__: WebInspector.Object.prototype}WebInspector.overridesSupport;;WebInspector.EmulatedDevice = function() { this.title = ""; this.type = WebInspector.EmulatedDevice.Type.Unknown; this.vertical = { width: 0, height: 0, outlineInsets: null , outlineImages: null }; this.horizontal = { width: 0, height: 0, outlineInsets: null , outlineImages: null }; this.deviceScaleFactor = 1; this.capabilities = [WebInspector.EmulatedDevice.Capability.Touch, WebInspector.EmulatedDevice.Capability.Mobile]; this.userAgent = ""; this.modes = []; this._show = WebInspector.EmulatedDevice._Show.Default; this._showByDefault = true; this._extension = null ;}WebInspector.EmulatedDevice.Mode;WebInspector.EmulatedDevice.Orientation;WebInspector.EmulatedDevice.Horizontal = "horizontal";WebInspector.EmulatedDevice.Vertical = "vertical";WebInspector.EmulatedDevice.Type = { Phone: "phone", Tablet: "tablet", Notebook: "notebook", Desktop: "desktop", Unknown: "unknown"}WebInspector.EmulatedDevice.Capability = { Touch: "touch", Mobile: "mobile"}WebInspector.EmulatedDevice._Show = { Always: "Always", Default: "Default", Never: "Never"}WebInspector.EmulatedDevice.fromJSONV1 = function(json) { try { function parseValue(object, key, type, defaultValue) { if (typeof object !== "object" || object === null || !object.hasOwnProperty(key)) { if (typeof defaultValue !== "undefined") return defaultValue; throw new Error("Emulated device is missing required property '" + key + "'"); } var value = object[key]; if (typeof value !== type || value === null ) throw new Error("Emulated device property '" + key + "' has wrong type '" + typeof value + "'"); return value; } function parseIntValue(object, key) { var value = (parseValue(object, key, "number")); if (value !== Math.abs(value)) throw new Error("Emulated device value '" + key + "' must be integer"); return value; } function parseInsets(json) { return new Insets(parseIntValue(json, "left"),parseIntValue(json, "top"),parseIntValue(json, "right"),parseIntValue(json, "bottom")); } function parseImages(json) { if (!Array.isArray(json)) throw new Error("Emulated device images is not an array"); var result = new WebInspector.EmulatedDevice.Images(); for (var i = 0; i < json.length; ++i) { var src = (parseValue(json[i], "src", "string")); var scale = (parseValue(json[i], "scale", "number")); if (scale <= 0) throw new Error("Emulated device property image scale must be positive"); result.addSource(src, scale); } return result; } function parseOrientation(json) { var result = {}; result.width = parseIntValue(json, "width"); if (result.width < 0 || result.width > WebInspector.OverridesSupport.MaxDeviceSize) throw new Error("Emulated device has wrong width: " + result.width); result.height = parseIntValue(json, "height"); if (result.height < 0 || result.height > WebInspector.OverridesSupport.MaxDeviceSize) throw new Error("Emulated device has wrong height: " + result.height); var outlineInsets = parseValue(json["outline"], "insets", "object", null ); if (outlineInsets) { result.outlineInsets = parseInsets(outlineInsets); if (result.outlineInsets.left < 0 || result.outlineInsets.top < 0) throw new Error("Emulated device has wrong outline insets"); result.outlineImages = parseImages(parseValue(json["outline"], "images", "object")); } return ( result) ; } var result = new WebInspector.EmulatedDevice(); result.title = (parseValue(json, "title", "string")); result.type = (parseValue(json, "type", "string")); result.userAgent = (parseValue(json, "user-agent", "string")); var capabilities = parseValue(json, "capabilities", "object", []); if (!Array.isArray(capabilities)) throw new Error("Emulated device capabilities must be an array"); result.capabilities = []; for (var i = 0; i < capabilities.length; ++i) { if (typeof capabilities[i] !== "string") throw new Error("Emulated device capability must be a string"); result.capabilities.push(capabilities[i]); } result.deviceScaleFactor = (parseValue(json["screen"], "device-pixel-ratio", "number")); if (result.deviceScaleFactor < 0 || result.deviceScaleFactor > 100) throw new Error("Emulated device has wrong deviceScaleFactor: " + result.deviceScaleFactor); result.vertical = parseOrientation(parseValue(json["screen"], "vertical", "object")); result.horizontal = parseOrientation(parseValue(json["screen"], "horizontal", "object")); var modes = parseValue(json, "modes", "object", []); if (!Array.isArray(modes)) throw new Error("Emulated device modes must be an array"); result.modes = []; for (var i = 0; i < modes.length; ++i) { var mode = {}; mode.title = (parseValue(modes[i], "title", "string")); mode.orientation = (parseValue(modes[i], "orientation", "string")); if (mode.orientation !== WebInspector.EmulatedDevice.Vertical && mode.orientation !== WebInspector.EmulatedDevice.Horizontal) throw new Error("Emulated device mode has wrong orientation '" + mode.orientation + "'"); var orientation = result.orientationByName(mode.orientation); mode.insets = parseInsets(parseValue(modes[i], "insets", "object")); if (mode.insets.top < 0 || mode.insets.left < 0 || mode.insets.right < 0 || mode.insets.bottom < 0 || mode.insets.top + mode.insets.bottom > orientation.height || mode.insets.left + mode.insets.right > orientation.width) { throw new Error("Emulated device mode '" + mode.title + "'has wrong mode insets"); } if (modes[i].hasOwnProperty("images")) mode.images = parseImages(parseValue(modes[i], "images", "object")); result.modes.push(mode); } result._showByDefault = (parseValue(json, "show-by-default", "boolean", true)); result._show = (parseValue(json, "show", "string", WebInspector.EmulatedDevice._Show.Default)); return result; } catch (e) { WebInspector.console.error("Failed to update emulated device list. " + String(e)); return null ; }}WebInspector.EmulatedDevice.fromOverridesDevice = function(device, title, type) { var result = new WebInspector.EmulatedDevice(); result.title = title; result.type = type || WebInspector.EmulatedDevice.Type.Unknown; result.vertical.width = device.width; result.vertical.height = device.height; result.horizontal.width = device.height; result.horizontal.height = device.width; result.deviceScaleFactor = device.deviceScaleFactor; result.userAgent = device.userAgent; result.capabilities = []; if (device.touch) result.capabilities.push(WebInspector.EmulatedDevice.Capability.Touch); if (device.mobile) result.capabilities.push(WebInspector.EmulatedDevice.Capability.Mobile); return result;}WebInspector.EmulatedDevice.compareByTitle = function(device1, device2) { return device1.title < device2.title ? -1 : (device1.title > device2.title ? 1 : 0);}WebInspector.EmulatedDevice.prototype = { extension: function() { return this._extension; }, setExtension: function(extension) { this._extension = extension; }, modesForOrientation: function(orientation) { var result = []; for (var index = 0; index < this.modes.length; index++) { if (this.modes[index].orientation === orientation) result.push(this.modes[index]); } return result; }, _toJSON: function() { var json = {}; json["title"] = this.title; json["type"] = this.type; json["user-agent"] = this.userAgent; json["capabilities"] = this.capabilities; json["screen"] = {}; json["screen"]["device-pixel-ratio"] = this.deviceScaleFactor; json["screen"]["vertical"] = this._orientationToJSON(this.vertical); json["screen"]["horizontal"] = this._orientationToJSON(this.horizontal); json["modes"] = []; for (var i = 0; i < this.modes.length; ++i) { var mode = {}; mode["title"] = this.modes[i].title; mode["orientation"] = this.modes[i].orientation; mode["insets"] = {}; mode["insets"]["left"] = this.modes[i].insets.left; mode["insets"]["top"] = this.modes[i].insets.top; mode["insets"]["right"] = this.modes[i].insets.right; mode["insets"]["bottom"] = this.modes[i].insets.bottom; if (this.modes[i].images) mode["images"] = this.modes[i].images._toJSON(); json["modes"].push(mode); } json["show-by-default"] = this._showByDefault; json["show"] = this._show; return json; }, _orientationToJSON: function(orientation) { var json = {}; json["width"] = orientation.width; json["height"] = orientation.height; if (orientation.outlineInsets) { json["outline"] = {}; json["outline"]["insets"] = {}; json["outline"]["insets"]["left"] = orientation.outlineInsets.left; json["outline"]["insets"]["top"] = orientation.outlineInsets.top; json["outline"]["insets"]["right"] = orientation.outlineInsets.right; json["outline"]["insets"]["bottom"] = orientation.outlineInsets.bottom; json["outline"]["images"] = orientation.outlineImages._toJSON(); } return json; }, modeToOverridesDevice: function(mode) { var result = {}; var orientation = this.orientationByName(mode.orientation); result.width = orientation.width - mode.insets.left - mode.insets.right; result.height = orientation.height - mode.insets.top - mode.insets.bottom; result.deviceScaleFactor = this.deviceScaleFactor; result.userAgent = this.userAgent; result.touch = this.touch(); result.mobile = this.mobile(); return result; }, orientationByName: function(name) { return name === WebInspector.EmulatedDevice.Vertical ? this.vertical : this.horizontal; }, show: function() { if (this._show === WebInspector.EmulatedDevice._Show.Default) return this._showByDefault; return this._show === WebInspector.EmulatedDevice._Show.Always; }, setShow: function(show) { this._show = show ? WebInspector.EmulatedDevice._Show.Always : WebInspector.EmulatedDevice._Show.Never; }, copyShowFrom: function(other) { this._show = other._show; }, touch: function() { return this.capabilities.indexOf(WebInspector.EmulatedDevice.Capability.Touch) !== -1; }, mobile: function() { return this.capabilities.indexOf(WebInspector.EmulatedDevice.Capability.Mobile) !== -1; }}WebInspector.EmulatedDevice.Images = function() { WebInspector.Object.call(this); this._sources = []; this._scales = [];}WebInspector.EmulatedDevice.Images.prototype = { _toJSON: function() { var result = []; for (var i = 0; i < this._sources.length; ++i) result.push({ src: this._sources[i], scale: this._scales[i] }); return result; }, addSource: function(src, scale) { this._sources.push(src); this._scales.push(scale); }, __proto__: WebInspector.Object.prototype}WebInspector.EmulatedDevicesList = function() { WebInspector.Object.call(this); WebInspector.settings.createSetting("standardEmulatedDeviceList", []).remove(); this._standardSetting = WebInspector.settings.createSetting("standardEmulatedDeviceList", []); this._standard = this._listFromJSONV1(this._standardSetting.get()); this._updateStandardDevices(); this._customSetting = WebInspector.settings.createSetting("customEmulatedDeviceList", []); this._custom = this._listFromJSONV1(this._customSetting.get());}WebInspector.EmulatedDevicesList.Events = { CustomDevicesUpdated: "CustomDevicesUpdated", StandardDevicesUpdated: "StandardDevicesUpdated"}WebInspector.EmulatedDevicesList.prototype = { _updateStandardDevices: function() { var devices = []; var extensions = self.runtime.extensions("emulated-device"); for (var i = 0; i < extensions.length; ++i) { var device = WebInspector.EmulatedDevice.fromJSONV1(extensions[i].descriptor()["device"]); device.setExtension(extensions[i]); devices.push(device); } this._copyShowValues(this._standard, devices); this._standard = devices; this.saveStandardDevices(); }, _listFromJSONV1: function(jsonArray) { var result = []; if (!Array.isArray(jsonArray)) return result; for (var i = 0; i < jsonArray.length; ++i) { var device = WebInspector.EmulatedDevice.fromJSONV1(jsonArray[i]); if (device) { result.push(device); if (!device.modes.length) { device.modes.push({ title: "", orientation: WebInspector.EmulatedDevice.Horizontal, insets: new Insets(0,0,0,0), images: null }); device.modes.push({ title: "", orientation: WebInspector.EmulatedDevice.Vertical, insets: new Insets(0,0,0,0), images: null }); } } } return result; }, standard: function() { return this._standard; }, custom: function() { return this._custom; }, addCustomDevice: function(device) { this._custom.push(device); this.saveCustomDevices(); }, removeCustomDevice: function(device) { this._custom.remove(device); this.saveCustomDevices(); }, saveCustomDevices: function() { var json = this._custom.map(function(device) { return device._toJSON(); } ); this._customSetting.set(json); this.dispatchEventToListeners(WebInspector.EmulatedDevicesList.Events.CustomDevicesUpdated); }, saveStandardDevices: function() { var json = this._standard.map(function(device) { return device._toJSON(); } ); this._standardSetting.set(json); this.dispatchEventToListeners(WebInspector.EmulatedDevicesList.Events.StandardDevicesUpdated); }, _copyShowValues: function(from, to) { var deviceById = new Map(); for (var i = 0; i < from.length; ++i) deviceById.set(from[i].title, from[i]); for (var i = 0; i < to.length; ++i) { var title = to[i].title; if (deviceById.has(title)) to[i].copyShowFrom((deviceById.get(title))); } }, __proto__: WebInspector.Object.prototype}WebInspector.emulatedDevicesList;;WebInspector.DevicesSettingsTab = function() { WebInspector.VBox.call(this); this.element.classList.add("settings-tab-container"); this.element.classList.add("devices-settings-tab"); this.registerRequiredCSS("emulation/devicesSettingsTab.css"); var header = this.element.createChild("header"); header.createChild("h3").createTextChild(WebInspector.UIString("Devices")); this.containerElement = this.element.createChild("div", "help-container-wrapper").createChild("div", "settings-tab help-content help-container"); this.containerElement.createChild("div", "devices-title").textContent = WebInspector.UIString("Emulated devices"); this._devicesList = this.containerElement.createChild("div", "devices-list"); this._customListSearator = createElementWithClass("div", "devices-custom-separator"); var buttonsRow = this.containerElement.createChild("div", "devices-button-row"); this._addCustomButton = createTextButton(WebInspector.UIString("Add custom device..."), this._addCustomDevice.bind(this)); buttonsRow.appendChild(this._addCustomButton); this._editDevice = null ; this._editDeviceListItem = null ; this._createEditDeviceElement(); this._muteUpdate = false; WebInspector.emulatedDevicesList.addEventListener(WebInspector.EmulatedDevicesList.Events.CustomDevicesUpdated, this._devicesUpdated, this); WebInspector.emulatedDevicesList.addEventListener(WebInspector.EmulatedDevicesList.Events.StandardDevicesUpdated, this._devicesUpdated, this);}WebInspector.DevicesSettingsTab.prototype = { wasShown: function() { WebInspector.VBox.prototype.wasShown.call(this); this._devicesUpdated(); this._stopEditing(); }, _devicesUpdated: function() { if (this._muteUpdate) return; this._devicesList.removeChildren(); var devices = WebInspector.emulatedDevicesList.custom().slice(); devices.sort(WebInspector.EmulatedDevice.compareByTitle); for (var i = 0; i < devices.length; ++i) this._devicesList.appendChild(this._createDeviceListItem(devices[i], true)); this._devicesList.appendChild(this._customListSearator); this._updateSeparatorVisibility(); devices = WebInspector.emulatedDevicesList.standard().slice(); devices.sort(WebInspector.EmulatedDevice.compareByTitle); for (var i = 0; i < devices.length; ++i) this._devicesList.appendChild(this._createDeviceListItem(devices[i], false)); }, _updateSeparatorVisibility: function() { this._customListSearator.classList.toggle("hidden", this._devicesList.firstChild === this._customListSearator); }, _muteAndSaveDeviceList: function(custom) { this._muteUpdate = true; if (custom) WebInspector.emulatedDevicesList.saveCustomDevices(); else WebInspector.emulatedDevicesList.saveStandardDevices(); this._muteUpdate = false; }, _createDeviceListItem: function(device, custom) { var item = createElementWithClass("div", "devices-list-item"); var checkbox = item.createChild("input", "devices-list-checkbox"); checkbox.type = "checkbox"; checkbox.checked = device.show(); item.createChild("div", "devices-list-title").textContent = device.title; item.addEventListener("click", onItemClicked.bind(this), false); item.classList.toggle("device-list-item-show", device.show()); if (custom) { var editButton = item.createChild("div", "devices-list-edit"); editButton.title = WebInspector.UIString("Edit"); editButton.addEventListener("click", onEditClicked.bind(this), false); var removeButton = item.createChild("div", "devices-list-remove"); removeButton.title = WebInspector.UIString("Remove"); removeButton.addEventListener("click", onRemoveClicked, false); } function onItemClicked(event) { var show = !checkbox.checked; device.setShow(show); this._muteAndSaveDeviceList(custom); checkbox.checked = show; item.classList.toggle("device-list-item-show", show); event.consume(); } function onEditClicked(event) { event.consume(); this._startEditing(device, item); } function onRemoveClicked(event) { WebInspector.emulatedDevicesList.removeCustomDevice(device); event.consume(); } return item; }, _addCustomDevice: function() { this._startEditing(new WebInspector.EmulatedDevice(), null ); }, _createEditDeviceElement: function() { this._editDeviceElement = createElementWithClass("div", "devices-edit-container"); this._editDeviceElement.addEventListener("keydown", onKeyDown.bind(null , isEscKey, this._stopEditing.bind(this)), false); this._editDeviceElement.addEventListener("keydown", onKeyDown.bind(null , isEnterKey, this._editDeviceCommitClicked.bind(this)), false); this._editDeviceCheckbox = this._editDeviceElement.createChild("input", "devices-edit-checkbox"); this._editDeviceCheckbox.type = "checkbox"; var fields = this._editDeviceElement.createChild("div", "devices-edit-fields"); this._editDeviceTitle = this._createInput(WebInspector.UIString("Device name")); fields.appendChild(this._editDeviceTitle); var screen = fields.createChild("div", "hbox"); this._editDeviceWidth = this._createInput(WebInspector.UIString("Width"), "120px"); screen.appendChild(this._editDeviceWidth); this._editDeviceHeight = this._createInput(WebInspector.UIString("Height"), "120px"); screen.appendChild(this._editDeviceHeight); this._editDeviceScale = this._createInput(WebInspector.UIString("Device pixel ratio")); screen.appendChild(this._editDeviceScale); this._editDeviceUserAgent = this._createInput(WebInspector.UIString("User agent string")); fields.appendChild(this._editDeviceUserAgent); var buttonsRow = fields.createChild("div", "devices-edit-buttons"); this._editDeviceCommitButton = createTextButton("", this._editDeviceCommitClicked.bind(this)); buttonsRow.appendChild(this._editDeviceCommitButton); this._editDeviceCancelButton = createTextButton(WebInspector.UIString("Cancel"), this._stopEditing.bind(this)); this._editDeviceCancelButton.addEventListener("keydown", onKeyDown.bind(null , isEnterKey, this._stopEditing.bind(this)), false); buttonsRow.appendChild(this._editDeviceCancelButton); function onKeyDown(predicate, callback, event) { if (predicate(event)) { event.consume(true); callback(); } } }, _createInput: function(title, width) { var input = createElement("input"); input.type = "text"; if (width) input.style.width = width; input.placeholder = title; input.addEventListener("input", this._validateInputs.bind(this), false); return input; }, _validateInputs: function() { var trimmedTitle = this._editDeviceTitle.value.trim(); var titleValid = trimmedTitle.length > 0 && trimmedTitle.length < 50; this._editDeviceTitle.classList.toggle("error-input", !titleValid); var widthValid = !WebInspector.OverridesSupport.deviceSizeValidator(this._editDeviceWidth.value); this._editDeviceWidth.classList.toggle("error-input", !widthValid); var heightValid = !WebInspector.OverridesSupport.deviceSizeValidator(this._editDeviceHeight.value); this._editDeviceHeight.classList.toggle("error-input", !heightValid); var scaleValid = !WebInspector.OverridesSupport.deviceScaleFactorValidator(this._editDeviceScale.value); this._editDeviceScale.classList.toggle("error-input", !scaleValid); var allValid = titleValid && widthValid && heightValid && scaleValid; this._editDeviceCommitButton.disabled = !allValid; }, _toNumericInputValue: function(value) { return value ? String(value) : ""; }, _startEditing: function(device, listItem) { this._stopEditing(); this._addCustomButton.disabled = true; this._devicesList.classList.add("devices-list-editing"); this._editDevice = device; this._editDeviceListItem = listItem; if (listItem) listItem.classList.add("hidden"); this._editDeviceCommitButton.textContent = listItem ? WebInspector.UIString("Save") : WebInspector.UIString("Add device"); this._editDeviceCheckbox.checked = device.show(); this._editDeviceTitle.value = device.title; this._editDeviceWidth.value = listItem ? this._toNumericInputValue(device.vertical.width) : ""; this._editDeviceHeight.value = listItem ? this._toNumericInputValue(device.vertical.height) : ""; this._editDeviceScale.value = listItem ? this._toNumericInputValue(device.deviceScaleFactor) : ""; this._editDeviceUserAgent.value = device.userAgent; this._validateInputs(); if (listItem && listItem.nextElementSibling) this._devicesList.insertBefore(this._editDeviceElement, listItem.nextElementSibling); else this._devicesList.insertBefore(this._editDeviceElement, this._customListSearator); this._editDeviceCommitButton.scrollIntoView(); this._editDeviceTitle.focus(); }, _editDeviceCommitClicked: function() { if (this._editDeviceCommitButton.disabled) return; this._editDevice.setShow(this._editDeviceCheckbox.checked); this._editDevice.title = this._editDeviceTitle.value; this._editDevice.vertical.width = this._editDeviceWidth.value ? parseInt(this._editDeviceWidth.value, 10) : 0; this._editDevice.vertical.height = this._editDeviceHeight.value ? parseInt(this._editDeviceHeight.value, 10) : 0; this._editDevice.horizontal.width = this._editDevice.vertical.height; this._editDevice.horizontal.height = this._editDevice.vertical.width; this._editDevice.deviceScaleFactor = this._editDeviceScale.value ? parseFloat(this._editDeviceScale.value) : 0; this._editDevice.userAgent = this._editDeviceUserAgent.value; this._editDevice.modes.push({ title: "", orientation: WebInspector.EmulatedDevice.Horizontal, insets: new Insets(0,0,0,0), images: null }); this._editDevice.modes.push({ title: "", orientation: WebInspector.EmulatedDevice.Vertical, insets: new Insets(0,0,0,0), images: null }); this._stopEditing(); if (this._editDeviceListItem) WebInspector.emulatedDevicesList.saveCustomDevices(); else WebInspector.emulatedDevicesList.addCustomDevice(this._editDevice); this._editDevice = null ; this._editDeviceListItem = null ; }, _stopEditing: function() { this._devicesList.classList.remove("devices-list-editing"); if (this._editDeviceListItem) this._editDeviceListItem.classList.remove("hidden"); if (this._editDeviceElement.parentElement) this._devicesList.removeChild(this._editDeviceElement); this._addCustomButton.disabled = false; this._addCustomButton.focus(); }, __proto__: WebInspector.VBox.prototype};WebInspector.DeviceModeButtonProvider = function() { var button = new WebInspector.ToolbarButton(WebInspector.UIString("Toggle device mode"),"emulation-toolbar-item"); button.addEventListener("click", toggleEmulationEnabled); WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.EmulationStateChanged, emulationEnabledChanged); WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.OverridesWarningUpdated, updateWarning); emulationEnabledChanged(); updateWarning(); function toggleEmulationEnabled() { WebInspector.overridesSupport.setEmulationEnabled(!button.toggled()); } function emulationEnabledChanged() { button.setToggled(WebInspector.overridesSupport.emulationEnabled()); } function updateWarning() { var message = WebInspector.overridesSupport.warningMessage(); button.setTitle(message || WebInspector.UIString("Toggle device mode")); button.element.classList.toggle("warning", !!message); } this._button = button;}WebInspector.DeviceModeButtonProvider.prototype = { item: function() { return this._button; }}WebInspector.ToggleDeviceModeActionDelegate = function() {}WebInspector.ToggleDeviceModeActionDelegate.prototype = { handleAction: function(context, actionId) { WebInspector.overridesSupport.setEmulationEnabled(!WebInspector.overridesSupport.emulationEnabled()); }};WebInspector.OverridesUI = {}WebInspector.DeviceSelect = function(rotateButton, callback) { this._callback = callback; this._rotateButton = rotateButton; this.element = createElement("p"); this._deviceSelectElement = this.element.createChild("select", "device-select"); this._deviceSelectElement.addEventListener("change", this._deviceSelected.bind(this), false); var container = this.element.createChild("div", "mode-container"); container.appendChild(this._rotateButton); this._rotateButton.addEventListener("click", this._rotateButtonClicked.bind(this), false); this._rotateButton.title = WebInspector.UIString("Change orientation"); var modeSelectContainer = container.createChild("span", "mode-select"); this._modeSelectElement = modeSelectContainer.createChild("select"); this._modeSelectElement.addEventListener("change", this._modeSelected.bind(this), false); this._modeLabelElement = modeSelectContainer.createChild("label"); this._modeLabelElement.addEventListener("click", this._rotateButtonClicked.bind(this), false); this._modeLabelElement.title = WebInspector.UIString("Change orientation"); this._emulatedSettingChangedMuted = false; this._lastOrientation = null ; WebInspector.overridesSupport.settings.emulateResolution.addChangeListener(this._emulatedSettingChanged, this); WebInspector.overridesSupport.settings.deviceWidth.addChangeListener(this._emulatedSettingChanged, this); WebInspector.overridesSupport.settings.deviceHeight.addChangeListener(this._emulatedSettingChanged, this); WebInspector.overridesSupport.settings.deviceScaleFactor.addChangeListener(this._emulatedSettingChanged, this); WebInspector.overridesSupport.settings.emulateMobile.addChangeListener(this._emulatedSettingChanged, this); WebInspector.overridesSupport.settings.emulateTouch.addChangeListener(this._emulatedSettingChanged, this); WebInspector.overridesSupport.settings.userAgent.addChangeListener(this._emulatedSettingChanged, this); WebInspector.emulatedDevicesList.addEventListener(WebInspector.EmulatedDevicesList.Events.CustomDevicesUpdated, this._deviceListChanged, this); WebInspector.emulatedDevicesList.addEventListener(WebInspector.EmulatedDevicesList.Events.StandardDevicesUpdated, this._deviceListChanged, this); this._deviceListChanged();}WebInspector.DeviceSelect.prototype = { _deviceListChanged: function() { this._deviceSelectElement.removeChildren(); var selectDeviceOption = new Option(WebInspector.UIString("<Select model>"),WebInspector.UIString("<Select model>")); selectDeviceOption.device = null ; selectDeviceOption.lastSelectedIndex = 0; selectDeviceOption.disabled = true; this._deviceSelectElement.appendChild(selectDeviceOption); this._addDeviceGroup(WebInspector.UIString("Custom"), WebInspector.emulatedDevicesList.custom()); this._addDeviceGroup(WebInspector.UIString("Devices"), WebInspector.emulatedDevicesList.standard()); this._emulatedSettingChanged(); }, _addDeviceGroup: function(name, devices) { devices = devices.filter(function(d) { return d.show(); } ); if (!devices.length) return; devices.sort(WebInspector.EmulatedDevice.compareByTitle); var groupElement = this._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.lastSelectedIndex = 0; groupElement.appendChild(option); } }, _emulatedSettingChanged: function() { if (this._emulatedSettingChangedMuted) return; for (var i = 1; i < this._deviceSelectElement.options.length; ++i) { var option = this._deviceSelectElement.options[i]; var device = (option.device); for (var j = 0; j < device.modes.length; j++) { if (WebInspector.overridesSupport.isEmulatingDevice(device.modeToOverridesDevice(device.modes[j]))) { this._select(device, device.modes[j]); return; } } } this._select(null , null ); }, _select: function(device, mode) { for (var i = 0; i < this._deviceSelectElement.options.length; i++) { if (this._deviceSelectElement.options[i].device === device) this._deviceSelectElement.selectedIndex = i; } this._updateModeSelect(); for (var i = 0; i < this._modeSelectElement.options.length; i++) { if (this._modeSelectElement.options[i].mode === mode) this._modeSelectElement.selectedIndex = i; } this._updateModeControls(); this._saveLastSelectedIndex(); if (this._callback) { var option = this._modeSelectElement.options[this._modeSelectElement.selectedIndex]; this._callback(option.device, option.mode); } }, _deviceSelected: function() { this._updateModeSelect(); this._modeSelected(); }, _updateModeSelect: function() { this._modeSelectElement.removeChildren(); var option = this._deviceSelectElement.options[this._deviceSelectElement.selectedIndex]; var device = (option.device); if (this._deviceSelectElement.selectedIndex === 0) { this._addMode(device, null , ""); } else if (device.modes.length === 1) { this._addMode(device, device.modes[0], WebInspector.UIString("Default")); } else { this._addOrientation(device, WebInspector.EmulatedDevice.Vertical, WebInspector.UIString("Portrait")); this._addOrientation(device, WebInspector.EmulatedDevice.Horizontal, WebInspector.UIString("Landscape")); } this._updateRotateModes(); var index = option.lastSelectedIndex; var modeOption = this._modeSelectElement.options[index]; if (modeOption.rotateIndex != -1) { var rotateOption = this._modeSelectElement.options[modeOption.rotateIndex]; if (rotateOption.mode && rotateOption.mode.orientation === this._lastOrientation) index = modeOption.rotateIndex; } this._modeSelectElement.selectedIndex = index; this._updateModeControls(); }, _addOrientation: function(device, orientation, title) { var modes = device.modesForOrientation(orientation); if (!modes.length) return; if (modes.length === 1) { this._addMode(device, modes[0], title); } else { for (var index = 0; index < modes.length; index++) this._addMode(device, modes[index], title + " \u2013 " + modes[index].title); } }, _addMode: function(device, mode, title) { var option = new Option(title,title); option.mode = mode; option.device = device; this._modeSelectElement.appendChild(option); }, _updateRotateModes: function() { for (var i = 0; i < this._modeSelectElement.options.length; i++) { var modeI = this._modeSelectElement.options[i].mode; this._modeSelectElement.options[i].rotateIndex = -1; for (var j = 0; j < this._modeSelectElement.options.length; j++) { var modeJ = this._modeSelectElement.options[j].mode; if (modeI && modeJ && modeI.orientation !== modeJ.orientation && modeI.title === modeJ.title) this._modeSelectElement.options[i].rotateIndex = j; } } }, _updateModeControls: function() { this._modeLabelElement.textContent = this._modeSelectElement.options[this._modeSelectElement.selectedIndex].label; if (this._modeSelectElement.options.length <= 1) { this._modeSelectElement.classList.toggle("hidden", true); this._modeLabelElement.classList.toggle("hidden", true); } else { var showLabel = this._modeSelectElement.options.length === 2 && this._modeSelectElement.options[0].rotateIndex === 1; this._modeSelectElement.classList.toggle("hidden", showLabel); this._modeLabelElement.classList.toggle("hidden", !showLabel); } this._rotateButton.classList.toggle("hidden", this._modeSelectElement.options[this._modeSelectElement.selectedIndex].rotateIndex === -1); }, _modeSelected: function() { this._saveLastSelectedIndex(); this._updateModeControls(); var option = this._modeSelectElement.options[this._modeSelectElement.selectedIndex]; if (this._callback) this._callback(option.device, option.mode); this._emulatedSettingChangedMuted = true; WebInspector.overridesSupport.emulateDevice(option.device.modeToOverridesDevice(option.mode)); this._emulatedSettingChangedMuted = false; }, _saveLastSelectedIndex: function() { this._deviceSelectElement.options[this._deviceSelectElement.selectedIndex].lastSelectedIndex = this._modeSelectElement.selectedIndex; var option = this._modeSelectElement.options[this._modeSelectElement.selectedIndex]; if (option.mode && option.rotateIndex != -1) this._lastOrientation = option.mode.orientation; }, _rotateButtonClicked: function() { this._modeSelectElement.selectedIndex = this._modeSelectElement.options[this._modeSelectElement.selectedIndex].rotateIndex; this._modeSelected(); }}WebInspector.OverridesUI.createUserAgentSelectAndInput = function() { 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 = 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 = 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._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: "Chrome \u2014 iPad", value: "Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) CriOS/30.0.1599.12 Mobile/11A465 Safari/8536.25"}, { title: "Chrome \u2014 iPhone", value: "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) CriOS/30.0.1599.12 Mobile/11A501 Safari/8536.25"}, { 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: "Googlebot", value: "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}, { title: "Googlebot Smartphone", 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 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}, { 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 8", value: "Mozilla/5.0 (iPad; CPU OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4"}, { 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 8", value: "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4"}, { 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.InspectedPagePlaceholder = function() { WebInspector.Widget.call(this); this.element.classList.add("inspected-page-placeholder"); 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 widget = this; while (widget.parentWidget()) { var parent = widget.parentWidget(); if (parent instanceof WebInspector.SplitWidget) { var side = parent.sidebarSide(); if (adjacent[side] && !parent.hasCustomResizer() && parent.isResizable()) margins[side] = WebInspector.InspectedPagePlaceholder.MarginValue; adjacent[side] = false; } widget = 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) this.element.window().cancelAnimationFrame(this._updateId); this._updateId = this.element.window().requestAnimationFrame(this.update.bind(this)); }, 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 = this.element.ownerDocument.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.Widget.prototype};;WebInspector.MediaQueryInspector = function() { WebInspector.Widget.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._mediaThrottler = new WebInspector.Throttler(0); this._offset = 0; this._scale = 1; this._lastReportedCount = 0; 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", CountUpdated: "CountUpdated"}WebInspector.MediaQueryInspector.prototype = { targetAdded: function(target) { if (this._cssModel) return; this._cssModel = WebInspector.CSSStyleModel.fromTarget(target); if (!this._cssModel) return; this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this); this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this); this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._scheduleMediaQueriesUpdate, this); this._cssModel.addEventListener(WebInspector.CSSStyleModel.Events.MediaQueryResultChanged, this._scheduleMediaQueriesUpdate, this); }, targetRemoved: function(target) { if (WebInspector.CSSStyleModel.fromTarget(target) !== this._cssModel) return; this._cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetAdded, this._scheduleMediaQueriesUpdate, this); this._cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetRemoved, this._scheduleMediaQueriesUpdate, this); this._cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._scheduleMediaQueriesUpdate, this); this._cssModel.removeEventListener(WebInspector.CSSStyleModel.Events.MediaQueryResultChanged, this._scheduleMediaQueriesUpdate, this); delete this._cssModel; }, setAxisTransform: function(offset, scale) { if (this._offset === offset && Math.abs(this._scale - scale) < 1e-8) return; this._offset = offset; this._scale = scale; this._renderMediaQueries(); }, setEnabled: function(enabled) { this._enabled = enabled; this._scheduleMediaQueriesUpdate(); }, _onMediaQueryClicked: function(event) { var mediaQueryMarker = event.target.enclosingNodeOrSelfWithClass("media-inspector-marker"); if (!mediaQueryMarker) return; function setWidth(width) { WebInspector.overridesSupport.settings.deviceWidth.set(width); WebInspector.overridesSupport.settings.emulateResolution.set(true); } var model = mediaQueryMarker._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) { if (!this._cssModel || !this._cssModel.isEnabled()) return; var mediaQueryMarker = event.target.enclosingNodeOrSelfWithClass("media-inspector-marker"); if (!mediaQueryMarker) return; var locations = mediaQueryMarker._locations; var uiLocations = new Map(); for (var i = 0; i < locations.length; ++i) { var uiLocation = WebInspector.cssWorkspaceBinding.rawLocationToUILocation(locations[i]); if (!uiLocation) continue;var descriptor = String.sprintf("%s:%d:%d", uiLocation.uiSourceCode.uri(), uiLocation.lineNumber + 1, uiLocation.columnNumber + 1); uiLocations.set(descriptor, uiLocation); } var contextMenuItems = uiLocations.keysArray().sort(); var contextMenu = new WebInspector.ContextMenu(event); var subMenuItem = contextMenu.appendSubMenuItem(WebInspector.UIString.capitalize("Reveal in ^source ^code")); for (var i = 0; i < contextMenuItems.length; ++i) { var title = contextMenuItems[i]; subMenuItem.appendItem(title, this._revealSourceLocation.bind(this, (uiLocations.get(title)))); } 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 || !this._cssModel) { finishCallback(); return; } this._cssModel.mediaQueriesPromise().then(this._rebuildMediaQueries.bind(this)).then(finishCallback).catch(finishCallback); }, _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 mediaQuery = cssMedia.mediaList[j]; var queryModel = WebInspector.MediaQueryInspector.MediaQueryUIModel.createFromMediaQuery(cssMedia, mediaQuery); if (queryModel && queryModel.rawLocation()) 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; var markers = []; var lastMarker = null ; for (var i = 0; i < this._cachedQueryModels.length; ++i) { var model = this._cachedQueryModels[i]; if (lastMarker && lastMarker.model.dimensionsEqual(model)) { lastMarker.locations.push(model.rawLocation()); lastMarker.active = lastMarker.active || model.active(); } else { lastMarker = { active: model.active(), model: model, locations: [model.rawLocation()] }; markers.push(lastMarker); } } if (markers.length !== this._lastReportedCount) { this._lastReportedCount = markers.length; this.dispatchEventToListeners(WebInspector.MediaQueryInspector.Events.CountUpdated, markers.length); } if (!this.isShowing()) return; var oldChildrenCount = this.element.children.length; var scrollTop = this.element.scrollTop; this.element.removeChildren(); var container = null ; for (var i = 0; i < markers.length; ++i) { if (!i || markers[i].model.section() !== markers[i - 1].model.section()) container = this.element.createChild("div", "media-inspector-marker-container"); var marker = markers[i]; var bar = this._createElementFromMediaQueryModel(marker.model); bar._model = marker.model; bar._locations = marker.locations; bar.classList.toggle("media-inspector-marker-inactive", !marker.active); container.appendChild(bar); } this.element.scrollTop = scrollTop; this.element.classList.toggle("media-inspector-view-empty", !this.element.children.length); if (this.element.children.length !== oldChildrenCount) this.dispatchEventToListeners(WebInspector.MediaQueryInspector.Events.HeightUpdated); }, _zoomFactor: function() { return WebInspector.zoomManager.zoomFactor() / this._scale; }, wasShown: function() { this._renderMediaQueries(); }, _createElementFromMediaQueryModel: function(model) { var zoomFactor = this._zoomFactor(); var minWidthValue = model.minWidthExpression() ? model.minWidthExpression().computedLength() : 0; const styleClassPerSection = ["media-inspector-marker-max-width", "media-inspector-marker-min-max-width", "media-inspector-marker-min-width"]; var markerElement = createElementWithClass("div", "media-inspector-marker"); var leftPixelValue = minWidthValue ? (minWidthValue - this._offset) / zoomFactor : 0; markerElement.style.left = leftPixelValue + "px"; markerElement.classList.add(styleClassPerSection[model.section()]); 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; else markerElement.style.right = "0"; if (typeof widthPixelValue === "number") markerElement.style.width = widthPixelValue + "px"; if (model.minWidthExpression()) { var labelClass = model.section() === WebInspector.MediaQueryInspector.Section.MinMax ? "media-inspector-label-right" : "media-inspector-label-left"; var labelContainer = markerElement.createChild("div", "media-inspector-marker-label-container media-inspector-marker-label-container-left"); labelContainer.createChild("span", "media-inspector-marker-label " + labelClass).textContent = model.minWidthExpression().value() + model.minWidthExpression().unit(); } if (model.maxWidthExpression()) { var labelClass = model.section() === WebInspector.MediaQueryInspector.Section.MinMax ? "media-inspector-label-left" : "media-inspector-label-right"; var labelContainer = markerElement.createChild("div", "media-inspector-marker-label-container media-inspector-marker-label-container-right"); labelContainer.createChild("span", "media-inspector-marker-label " + labelClass).textContent = model.maxWidthExpression().value() + model.maxWidthExpression().unit(); } markerElement.title = model.mediaText(); return markerElement; }, __proto__: WebInspector.Widget.prototype};WebInspector.MediaQueryInspector.MediaQueryUIModel = function(cssMedia, minWidthExpression, maxWidthExpression, active) { this._cssMedia = cssMedia; this._minWidthExpression = minWidthExpression; this._maxWidthExpression = maxWidthExpression; this._active = active; 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.createFromMediaQuery = function(cssMedia, mediaQuery) { var maxWidthExpression = null ; var maxWidthPixels = Number.MAX_VALUE; var minWidthExpression = null ; var minWidthPixels = Number.MIN_VALUE; var expressions = mediaQuery.expressions(); for (var i = 0; i < expressions.length; ++i) { var expression = expressions[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,mediaQuery.active());}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.rawLocation(); var otherLocation = other.rawLocation(); if (!myLocation && !otherLocation) return this.mediaText().compareTo(other.mediaText()); if (myLocation && !otherLocation) return 1; if (!myLocation && otherLocation) return -1; if (this.active() !== other.active()) return this.active() ? -1 : 1; return myLocation.url.compareTo(otherLocation.url) || myLocation.lineNumber - otherLocation.lineNumber || myLocation.columnNumber - otherLocation.columnNumber; } if (this.section() === WebInspector.MediaQueryInspector.Section.Max) return other.maxWidthExpression().computedLength() - this.maxWidthExpression().computedLength(); if (this.section() === WebInspector.MediaQueryInspector.Section.Min) return this.minWidthExpression().computedLength() - other.minWidthExpression().computedLength(); return this.minWidthExpression().computedLength() - other.minWidthExpression().computedLength() || other.maxWidthExpression().computedLength() - this.maxWidthExpression().computedLength(); }, section: function() { return this._section; }, mediaText: function() { return this._cssMedia.text; }, rawLocation: function() { if (!this._rawLocation) this._rawLocation = this._cssMedia.rawLocation(); return this._rawLocation; }, minWidthExpression: function() { return this._minWidthExpression; }, maxWidthExpression: function() { return this._maxWidthExpression; }, active: function() { return this._active; }};WebInspector.ResponsiveDesignView = function(inspectedPagePlaceholder) { WebInspector.VBox.call(this); this.setMinimumSize(150, 150); this.element.classList.add("responsive-design-view"); this.registerRequiredCSS("emulation/responsiveDesignView.css"); this._showMediaQueryInspectorSetting = WebInspector.settings.createSetting("showMediaQueryInspector", false); this._responsiveDesignContainer = new WebInspector.VBox(); this._uiInitialized = false; this._inspectedPagePlaceholder = inspectedPagePlaceholder; inspectedPagePlaceholder.show(this.element); this._enabled = false; this._viewport = { scrollX: 0, scrollY: 0, contentsWidth: 0, contentsHeight: 0, pageScaleFactor: 1, minimumPageScaleFactor: 1, maximumPageScaleFactor: 1 }; this._drawContentsSize = true; this._deviceInsets = new Insets(0,0,0,0); this._viewportChangedThrottler = new WebInspector.Throttler(0); this._pageScaleFactorThrottler = new WebInspector.Throttler(50); WebInspector.zoomManager.addEventListener(WebInspector.ZoomManager.Events.ZoomChanged, this._onZoomChanged, this); WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.EmulationStateChanged, this._emulationEnabledChanged, this); WebInspector.targetManager.observeTargets(this, WebInspector.Target.Type.Page); this._emulationEnabledChanged();};WebInspector.ResponsiveDesignView.RulerWidth = 26;WebInspector.ResponsiveDesignView.RulerHeight = 22;WebInspector.ResponsiveDesignView.RulerTopHeight = 11;WebInspector.ResponsiveDesignView.RulerBottomHeight = 9;WebInspector.ResponsiveDesignView.prototype = { _ensureUIInitialized: function() { if (this._uiInitialized) return; this._uiInitialized = true; this._createToolbar(); this._canvasContainer = new WebInspector.Widget(); this._canvasContainer.element.classList.add("responsive-design"); this._canvasContainer.show(this._responsiveDesignContainer.element); this._canvas = this._canvasContainer.element.createChild("canvas", "fill responsive-design-canvas"); this._mediaInspectorContainer = this._canvasContainer.element.createChild("div", "responsive-design-media-container"); this._mediaInspector = new WebInspector.MediaQueryInspector(); this._updateMediaQueryInspector(); this._warningInfobar = new WebInspector.Infobar(WebInspector.Infobar.Type.Warning,WebInspector.moduleSetting("disableOverridesWarning")); this._warningInfobar.element.classList.add("responsive-design-warning"); this._warningInfobar.setCloseCallback(WebInspector.overridesSupport.clearWarningMessage.bind(WebInspector.overridesSupport)); this._canvasContainer.element.appendChild(this._warningInfobar.element); this._warningMessage = this._warningInfobar.element.createChild("span"); WebInspector.overridesSupport.addEventListener(WebInspector.OverridesSupport.Events.OverridesWarningUpdated, this._overridesWarningUpdated, this); this._slidersContainer = this._canvasContainer.element.createChild("div", "vbox responsive-design-sliders-container"); var genericDeviceOutline = this._slidersContainer.createChild("div", "responsive-design-generic-outline-container"); genericDeviceOutline.createChild("div", "responsive-design-generic-outline"); var widthSlider = this._slidersContainer.createChild("div", "responsive-design-slider-width"); widthSlider.createChild("div", "responsive-design-thumb-handle"); this._createResizer(widthSlider, true, false); var heightSlider = this._slidersContainer.createChild("div", "responsive-design-slider-height"); heightSlider.createChild("div", "responsive-design-thumb-handle"); this._createResizer(heightSlider, false, true); var cornerSlider = this._slidersContainer.createChild("div", "responsive-design-slider-corner"); this._createResizer(cornerSlider, true, true); this._pageContainer = this._slidersContainer.createChild("div", "vbox flex-auto responsive-design-page-container"); this._pageScaleContainer = this._canvasContainer.element.createChild("div", "hbox responsive-design-page-scale-container"); this._decreasePageScaleButton = this._pageScaleContainer.createChild("button", "responsive-design-page-scale-button responsive-design-page-scale-decrease"); this._decreasePageScaleButton.createChild("div", "glyph"); this._decreasePageScaleButton.tabIndex = -1; this._decreasePageScaleButton.addEventListener("click", this._pageScaleButtonClicked.bind(this, false), false); this._pageScaleLabel = this._pageScaleContainer.createChild("label", "responsive-design-page-scale-label"); this._pageScaleLabel.title = WebInspector.UIString("For a simpler way to change the current page scale, hold down Shift and drag with your mouse."); this._pageScaleLabel.addEventListener("dblclick", this._resetPageScale.bind(this), false); this._increasePageScaleButton = this._pageScaleContainer.createChild("button", "responsive-design-page-scale-button responsive-design-page-scale-increase"); this._increasePageScaleButton.tabIndex = -1; this._increasePageScaleButton.createChild("div", "glyph"); this._increasePageScaleButton.addEventListener("click", this._pageScaleButtonClicked.bind(this, true), false); this._mediaInspector.addEventListener(WebInspector.MediaQueryInspector.Events.CountUpdated, this._updateMediaQueryInspectorButton, this); this._mediaInspector.addEventListener(WebInspector.MediaQueryInspector.Events.HeightUpdated, this.onResize, this); this._overridesWarningUpdated(); }, targetAdded: function(target) { if (this._target) return; this._target = target; target.registerEmulationDispatcher(new WebInspector.EmulationDispatcher(this)); }, targetRemoved: function(target) {}, _invalidateCache: function() { delete this._cachedScale; delete this._cachedCssCanvasWidth; delete this._cachedCssCanvasHeight; delete this._cachedCssHeight; delete this._cachedCssWidth; delete this._cachedDeviceInsets; delete this._cachedZoomFactor; delete this._cachedViewport; delete this._cachedDrawContentsSize; delete this._cachedMediaInspectorHeight; delete this._availableSize; }, _emulationEnabledChanged: function() { var enabled = WebInspector.overridesSupport.emulationEnabled(); if (enabled && !this._enabled) { WebInspector.userMetrics.DeviceModeEnabled.record(); this._invalidateCache(); this._ignoreResize = true; this._ensureUIInitialized(); this._enabled = true; this._mediaInspector.setEnabled(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._mediaInspector.setEnabled(false); 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() { var available = this._availableDipSize(); WebInspector.overridesSupport.setPageResizer(this, available.size, available.insets); }, _availableDipSize: function() { if (typeof this._availableSize === "undefined") { if (!this._enabled) return { size: new Size(1,1), insets: new Insets(0,0,0,0) }; var zoomFactor = WebInspector.zoomManager.zoomFactor(); var rect = this._canvasContainer.element.getBoundingClientRect(); var rulerTotalHeight = this._rulerTotalHeightDIP(); this._availableSize = { size: new Size(Math.max(rect.width * zoomFactor - WebInspector.ResponsiveDesignView.RulerWidth, 1),Math.max(rect.height * zoomFactor - rulerTotalHeight, 1)), insets: this._deviceInsets }; } return this._availableSize; }, _createResizer: function(element, x, y) { var resizer = new WebInspector.ResizerWidget(); resizer.addElement(element); resizer.setCursor(x && y ? "nwse-resize" : (x ? "ew-resize" : "ns-resize")); resizer.addEventListener(WebInspector.ResizerWidget.Events.ResizeStart, this._onResizeStart, this); resizer.addEventListener(WebInspector.ResizerWidget.Events.ResizeUpdate, this._onResizeUpdate.bind(this, x, y)); resizer.addEventListener(WebInspector.ResizerWidget.Events.ResizeEnd, this._onResizeEnd, this); return resizer; }, _onResizeStart: function(event) { this._drawContentsSize = false; var available = this._availableDipSize().size; this._slowPositionStart = null ; this._resizeStart = { x: this._dipWidth || available.width, y: this._dipHeight || available.height }; this.dispatchEventToListeners(WebInspector.OverridesSupport.PageResizer.Events.FixedScaleRequested, true); this._updateUI(); }, _onResizeUpdate: function(x, y, event) { if (event.data.shiftKey !== !!this._slowPositionStart) this._slowPositionStart = event.data.shiftKey ? { x: event.data.currentX, y: event.data.currentY } : null ; var cssOffsetX = event.data.currentX - event.data.startX; var cssOffsetY = event.data.currentY - event.data.startY; if (this._slowPositionStart) { cssOffsetX = (event.data.currentX - this._slowPositionStart.x) / 10 + this._slowPositionStart.x - event.data.startX; cssOffsetY = (event.data.currentY - this._slowPositionStart.y) / 10 + this._slowPositionStart.y - event.data.startY; } var dipOffsetX = Math.round(cssOffsetX * WebInspector.zoomManager.zoomFactor()); var dipOffsetY = Math.round(cssOffsetY * WebInspector.zoomManager.zoomFactor()); var newSizeX = this._resizeStart.x + dipOffsetX; newSizeX = Math.round(newSizeX / (this._scale || 1)); newSizeX = Math.max(Math.min(newSizeX, WebInspector.OverridesSupport.MaxDeviceSize), 1); var newSizeY = this._resizeStart.y + dipOffsetY; newSizeY = Math.round(newSizeY / (this._scale || 1)); newSizeY = Math.max(Math.min(newSizeY, WebInspector.OverridesSupport.MaxDeviceSize), 1); var requested = {}; if (x) requested.width = newSizeX; if (y) requested.height = newSizeY; this.dispatchEventToListeners(WebInspector.OverridesSupport.PageResizer.Events.ResizeRequested, requested); }, _onResizeEnd: function(event) { this._drawContentsSize = true; this.dispatchEventToListeners(WebInspector.OverridesSupport.PageResizer.Events.FixedScaleRequested, false); delete this._resizeStart; this._updateUI(); }, _drawCanvas: function(cssCanvasWidth, cssCanvasHeight, rulerHeight) { 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 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 - rulerHeight; var dipScrollX = this._viewport.scrollX * scale; var dipScrollY = this._viewport.scrollY * scale; context.translate(rulerWidth, rulerHeight); 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); if (minXIndex) { context.beginPath(); context.moveTo(0, -rulerHeight); context.lineTo(0, 0); context.stroke(); } context.translate(-dipScrollX, 0); for (var index = minXIndex; index <= maxXIndex; index++) { var x = index * rulerSubStep; var height = WebInspector.ResponsiveDesignView.RulerHeight * 0.25; if (!(index % (rulerStepCount / 4))) height = WebInspector.ResponsiveDesignView.RulerHeight * 0.5; if (!(index % (rulerStepCount / 2))) height = rulerHeight; if (!(index % rulerStepCount)) { context.save(); context.translate(x, 0); context.fillText(Math.round(x / scale), 2, -rulerHeight + 10); context.restore(); height = rulerHeight; } context.beginPath(); context.moveTo(x, -height); 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 * 0.25; if (!(index % (rulerStepCount / 4))) x = -rulerWidth * 0.5; if (!(index % (rulerStepCount / 2))) x = -rulerWidth * 0.75; if (!(index % rulerStepCount)) { context.save(); context.translate(0, y); context.rotate(-Math.PI / 2); context.fillText(Math.round(y / scale), 2, -rulerWidth + 10); 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); } }, _rulerTotalHeightDIP: function() { var mediaInspectorHeight = this._mediaInspector.isShowing() ? this._mediaInspector.element.offsetHeight : 0; if (!mediaInspectorHeight) return WebInspector.ResponsiveDesignView.RulerHeight; return WebInspector.ResponsiveDesignView.RulerTopHeight + WebInspector.ResponsiveDesignView.RulerBottomHeight + mediaInspectorHeight * WebInspector.zoomManager.zoomFactor(); }, _updateUI: function() { if (!this._enabled || !this.isShowing()) return; var zoomFactor = WebInspector.zoomManager.zoomFactor(); var rect = this._canvas.parentElement.getBoundingClientRect(); var availableDip = this._availableDipSize().size; var cssCanvasWidth = rect.width; var cssCanvasHeight = rect.height; var mediaInspectorHeight = this._mediaInspector.isShowing() ? this._mediaInspector.element.offsetHeight : 0; var rulerTotalHeight = this._rulerTotalHeightDIP(); this._mediaInspector.setAxisTransform(this._viewport.scrollX, this._scale * this._viewport.pageScaleFactor); if (this._cachedZoomFactor !== zoomFactor || this._cachedMediaInspectorHeight !== mediaInspectorHeight) { var cssRulerWidth = WebInspector.ResponsiveDesignView.RulerWidth / zoomFactor + "px"; var cssRulerHeight = (mediaInspectorHeight ? WebInspector.ResponsiveDesignView.RulerTopHeight : WebInspector.ResponsiveDesignView.RulerHeight) / zoomFactor + "px"; var cssCanvasOffset = rulerTotalHeight / zoomFactor + "px"; this._slidersContainer.style.left = cssRulerWidth; this._slidersContainer.style.top = cssCanvasOffset; this._warningInfobar.element.style.height = cssCanvasOffset; this._pageScaleContainer.style.top = cssCanvasOffset; this._mediaInspectorContainer.style.left = cssRulerWidth; this._mediaInspectorContainer.style.marginTop = cssRulerHeight; } var cssWidth = (this._dipWidth ? this._dipWidth : availableDip.width) / zoomFactor; var cssHeight = (this._dipHeight ? this._dipHeight : availableDip.height) / zoomFactor; var deviceInsets = new Insets(this._deviceInsets.left * this._scale / zoomFactor,this._deviceInsets.top * this._scale / zoomFactor,this._deviceInsets.right * this._scale / zoomFactor,this._deviceInsets.bottom * this._scale / zoomFactor); cssWidth += deviceInsets.left + deviceInsets.right; cssHeight += deviceInsets.top + deviceInsets.bottom; if (this._cachedCssWidth !== cssWidth || this._cachedCssHeight !== cssHeight || !deviceInsets.isEqual(this._cachedDeviceInsets)) { this._slidersContainer.style.width = cssWidth + "px"; this._slidersContainer.style.height = cssHeight + "px"; this._pageContainer.style.paddingLeft = deviceInsets.left + "px"; this._pageContainer.style.paddingTop = deviceInsets.top + "px"; this._pageContainer.style.paddingRight = deviceInsets.right + "px"; this._pageContainer.style.paddingBottom = deviceInsets.bottom + "px"; this._inspectedPagePlaceholder.onResize(); } var pageScaleVisible = cssWidth + this._pageScaleContainerWidth + WebInspector.ResponsiveDesignView.RulerWidth / zoomFactor <= rect.width; this._pageScaleContainer.classList.toggle("hidden", !pageScaleVisible); 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 || this._cachedViewport.minimumPageScaleFactor !== this._viewport.minimumPageScaleFactor || this._cachedViewport.maximumPageScaleFactor !== this._viewport.maximumPageScaleFactor; var canvasInvalidated = viewportChanged || this._drawContentsSize !== this._cachedDrawContentsSize || this._cachedScale !== this._scale || this._cachedCssCanvasWidth !== cssCanvasWidth || this._cachedCssCanvasHeight !== cssCanvasHeight || this._cachedZoomFactor !== zoomFactor || this._cachedMediaInspectorHeight !== mediaInspectorHeight; if (canvasInvalidated) this._drawCanvas(cssCanvasWidth, cssCanvasHeight, rulerTotalHeight); if (viewportChanged) { this._pageScaleLabel.textContent = WebInspector.UIString("%.1f", this._viewport.pageScaleFactor); this._decreasePageScaleButton.title = WebInspector.UIString("Scale down (minimum %.1f)", this._viewport.minimumPageScaleFactor); this._decreasePageScaleButton.disabled = this._viewport.pageScaleFactor <= this._viewport.minimumPageScaleFactor; this._increasePageScaleButton.title = WebInspector.UIString("Scale up (maximum %.1f)", this._viewport.maximumPageScaleFactor); this._increasePageScaleButton.disabled = this._viewport.pageScaleFactor >= this._viewport.maximumPageScaleFactor; } this._cachedScale = this._scale; this._cachedCssCanvasWidth = cssCanvasWidth; this._cachedCssCanvasHeight = cssCanvasHeight; this._cachedCssHeight = cssHeight; this._cachedCssWidth = cssWidth; this._cachedDeviceInsets = deviceInsets; this._cachedZoomFactor = zoomFactor; this._cachedViewport = this._viewport; this._cachedDrawContentsSize = this._drawContentsSize; this._cachedMediaInspectorHeight = mediaInspectorHeight; }, onResize: function() { if (!this._enabled || this._ignoreResize) return; var oldSize = this._availableSize; this._pageScaleContainer.classList.remove("hidden"); this._pageScaleContainerWidth = this._pageScaleContainer.offsetWidth; delete this._availableSize; var newSize = this._availableDipSize(); if (!oldSize || !newSize.size.isEqual(oldSize.size) || !newSize.insets.isEqual(oldSize.insets)) 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._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 buttonsToolbar = new WebInspector.Toolbar(this._toolbarElement); buttonsToolbar.makeVertical(); buttonsToolbar.setColor("white"); buttonsToolbar.setToggledColor("rgb(105, 194, 236)"); buttonsToolbar.element.classList.add("responsive-design-section", "responsive-design-section-buttons"); var resetButton = new WebInspector.ToolbarButton(WebInspector.UIString("Reset all overrides."),"clear-toolbar-item"); buttonsToolbar.appendToolbarItem(resetButton); resetButton.addEventListener("click", WebInspector.overridesSupport.reset, WebInspector.overridesSupport); this._toggleMediaInspectorButton = new WebInspector.ToolbarButton(WebInspector.UIString("Media queries not found"),"waterfall-toolbar-item"); this._toggleMediaInspectorButton.setToggled(this._showMediaQueryInspectorSetting.get()); this._toggleMediaInspectorButton.setEnabled(false); this._toggleMediaInspectorButton.addEventListener("click", this._onToggleMediaInspectorButtonClick, this); this._showMediaQueryInspectorSetting.addChangeListener(this._updateMediaQueryInspector, this); buttonsToolbar.appendToolbarItem(this._toggleMediaInspectorButton); }, _createDeviceSection: function() { var deviceSection = this._toolbarElement.createChild("div", "responsive-design-section responsive-design-section-device"); deviceSection.createChild("div", "responsive-design-section-decorator"); 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 deviceSelect = new WebInspector.DeviceSelect(createElementWithClass("button", "responsive-design-icon responsive-design-icon-swap"),this._deviceModeSelected.bind(this)); fieldsetElement.appendChild(deviceSelect.element); deviceSelect.element.classList.add("responsive-design-device-select"); 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, WebInspector.UIString("Emulate screen resolution")); themeCheckbox(emulateResolutionCheckbox); fieldsetElement.appendChild(emulateResolutionCheckbox); fieldsetElement.createChild("label").textContent = WebInspector.UIString("Screen"); 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.createTextChild("\u00D7"); resolutionFieldset.appendChild(WebInspector.SettingsUI.createSettingInputField("", WebInspector.overridesSupport.settings.deviceHeight, true, 4, "3em", WebInspector.OverridesSupport.deviceSizeValidator, true, true, WebInspector.UIString("\u2013"))); 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 = resolutionFieldset2.createChild("div", "responsive-design-icon responsive-design-icon-dpr"); dprButton.title = WebInspector.UIString("Device pixel ratio"); resolutionFieldset2.appendChild(WebInspector.SettingsUI.createSettingInputField("", WebInspector.overridesSupport.settings.deviceScaleFactor, true, 4, "1.9em", WebInspector.OverridesSupport.deviceScaleFactorValidator, true, true, WebInspector.UIString("\u2013"))); detailsElement.createChild("div", "responsive-design-suite-separator"); var fitToWindowElement = detailsElement.createChild("div", ""); fieldsetElement = fitToWindowElement.createChild("fieldset"); var fitCheckbox = WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Zoom to fit"), WebInspector.overridesSupport.settings.deviceFitWindow, true, WebInspector.UIString("Zoom to fit available space")) fieldsetElement.appendChild(fitCheckbox); themeCheckbox(fitCheckbox); function themeCheckbox(checkbox) { checkbox.checkColor = "rgb(255, 156, 0)"; checkbox.backgroundColor = "rgb(102, 102, 102)"; checkbox.borderColor = "rgb(45, 45, 45)"; } }, _createNetworkSection: function() { var networkSection = this._toolbarElement.createChild("div", "responsive-design-section responsive-design-section-network"); networkSection.createChild("div", "responsive-design-section-decorator"); 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"); new WebInspector.NetworkConditionsSelector(fieldsetElement.createChild("select")); 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() { this._showMediaQueryInspectorSetting.set(!this._toggleMediaInspectorButton.toggled()); }, _updateMediaQueryInspector: function() { this._toggleMediaInspectorButton.setToggled(this._showMediaQueryInspectorSetting.get()); if (this._mediaInspector.isShowing() === this._showMediaQueryInspectorSetting.get()) return; if (this._mediaInspector.isShowing()) this._mediaInspector.detach(); else this._mediaInspector.show(this._mediaInspectorContainer); this.onResize(); }, _updateMediaQueryInspectorButton: function(event) { var count = (event.data); this._toggleMediaInspectorButton.setEnabled(!!count); this._toggleMediaInspectorButton.setTitle(!count ? WebInspector.UIString("Media queries not found") : WebInspector.UIString((count === 1 ? "%d media query found" : "%d media queries found"), count)); }, _overridesWarningUpdated: function() { var message = WebInspector.overridesSupport.warningMessage(); this._warningMessage.textContent = message; this._warningInfobar.setVisible(!!message); }, _showEmulationInDrawer: function() { WebInspector.Revealer.reveal(WebInspector.overridesSupport); }, _deviceModeSelected: function(device, mode) { if (device && mode) { var orientation = device.orientationByName(mode.orientation); this._deviceInsets = mode.insets; WebInspector.overridesSupport.settings.screenOrientationOverride.set(mode.orientation == WebInspector.EmulatedDevice.Horizontal ? "landscapePrimary" : "portraitPrimary"); } else { this._deviceInsets = new Insets(0,0,0,0); WebInspector.overridesSupport.settings.screenOrientationOverride.set(""); } this.dispatchEventToListeners(WebInspector.OverridesSupport.PageResizer.Events.InsetsChanged, this._deviceInsets); }, _viewportChanged: function(viewport) { if (viewport) { this._viewport = viewport; this._viewport.minimumPageScaleFactor = Math.max(0.1, this._viewport.minimumPageScaleFactor); this._viewport.minimumPageScaleFactor = Math.min(this._viewport.minimumPageScaleFactor, this._viewport.pageScaleFactor); this._viewport.maximumPageScaleFactor = Math.min(10, this._viewport.maximumPageScaleFactor); this._viewport.maximumPageScaleFactor = Math.max(this._viewport.maximumPageScaleFactor, this._viewport.pageScaleFactor); this._viewportChangedThrottler.schedule(this._updateUIThrottled.bind(this)); } }, _updateUIThrottled: function(finishCallback) { this._updateUI(); finishCallback(); }, _pageScaleButtonClicked: function(increase, event) { this._pageScaleFactorThrottler.schedule(updatePageScaleFactor.bind(this)); function updatePageScaleFactor(finishCallback) { if (this._target && this._viewport) { var value = this._viewport.pageScaleFactor; value = increase ? value * 1.1 : value / 1.1; value = Math.min(this._viewport.maximumPageScaleFactor, value); value = Math.max(this._viewport.minimumPageScaleFactor, value); this._target.emulationAgent().setPageScaleFactor(value); } finishCallback(); } }, _resetPageScale: function() { this._pageScaleFactorThrottler.schedule(updatePageScaleFactor.bind(this)); function updatePageScaleFactor(finishCallback) { if (this._target && this._viewport && this._viewport.minimumPageScaleFactor <= 1 && this._viewport.maximumPageScaleFactor >= 1) this._target.emulationAgent().setPageScaleFactor(1); finishCallback(); } }, __proto__: WebInspector.VBox.prototype};WebInspector.EmulationDispatcher = function(responsiveDesignView) { this._responsiveDesignView = responsiveDesignView;}WebInspector.EmulationDispatcher.prototype = { viewportChanged: function(viewport) { this._responsiveDesignView._viewportChanged(viewport); }};WebInspector.OverridesView = function() { WebInspector.VBox.call(this); this.setMinimumSize(0, 30); this.registerRequiredCSS("emulation/overrides.css"); this.element.classList.add("overrides-view"); this._tabbedPane = new WebInspector.TabbedPane(); this._tabbedPane.setShrinkableTabs(false); this._tabbedPane.setVerticalTabLayout(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 = createTextButton(WebInspector.UIString("Reset"), WebInspector.overridesSupport.reset.bind(WebInspector.overridesSupport)); resetButtonElement.id = "overrides-reset-button"; this._tabbedPane.appendAfterTabStrip(resetButtonElement); var disableButtonElement = createTextButton(WebInspector.UIString("Disable"), this._toggleEmulationEnabled.bind(this), "overrides-disable-button"); disableButtonElement.id = "overrides-disable-button"; this._tabbedPane.appendAfterTabStrip(disableButtonElement); this._splashScreenElement = this.element.createChild("div", "overrides-splash-screen"); this._splashScreenElement.appendChild(createTextButton(WebInspector.UIString("Enable emulation"), this._toggleEmulationEnabled.bind(this), "overrides-enable-button")); this._unavailableSplashScreenElement = this.element.createChild("div", "overrides-splash-screen"); this._unavailableSplashScreenElement.createTextChild(WebInspector.UIString("Emulation is not available.")); 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() || !WebInspector.overridesSupport.canEmulate()); }, __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.toggleTabClass(this._id, "overrides-activate", 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"); footnote.appendChild(WebInspector.linkifyDocumentationURLAsNode("device-mode", WebInspector.UIString("More information about screen emulation")));}WebInspector.OverridesView.DeviceTab.prototype = { _createDeviceElement: function() { var fieldsetElement = createElement("fieldset"); fieldsetElement.id = "metrics-override-section"; var deviceModelElement = fieldsetElement.createChild("p", "overrides-device-model-section"); deviceModelElement.createChild("span").textContent = WebInspector.UIString("Model:"); var rotateButton = createElement("button"); rotateButton.textContent = " \u21C4 "; var deviceSelect = new WebInspector.DeviceSelect(rotateButton,null ); deviceModelElement.appendChild(deviceSelect.element); 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"); var rowElement = tableElement.createChild("tr"); var cellElement = rowElement.createChild("td"); cellElement.createTextChild(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); 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").createTextChild(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; }, __proto__: WebInspector.OverridesView.Tab.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 = 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 = 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.element.classList.add("overrides-network"); this._createUserAgentSection();}WebInspector.OverridesView.NetworkTab.prototype = { _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(); 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("emulation/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.createTextChild(WebInspector.UIString("Lat = ")); this._latitudeElement = WebInspector.SettingsUI.createInput(cellElement, "geolocation-override-latitude", String(geolocation.latitude), this._applyGeolocationUserInput.bind(this), true); cellElement.createTextChild(" , "); cellElement.createTextChild(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 = createCheckboxLabel(WebInspector.UIString("Emulate position unavailable"), !geolocation || !!geolocation.error); var geolocationErrorCheckboxElement = geolocationErrorLabelElement.checkboxElement; geolocationErrorCheckboxElement.id = "geolocation-error"; geolocationErrorCheckboxElement.addEventListener("click", this._applyGeolocationUserInput.bind(this), false); 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.createTextChild(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)); cellElement.appendChild(createTextButton(WebInspector.UIString("Reset"), this._resetDeviceOrientation.bind(this), "accelerometer-reset-button")); 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"); return Promise.resolve(); }};WebInspector.HelpScreenUntilReload = function(debuggerModel, title, message) { WebInspector.HelpScreen.call(this, title); this._debuggerModel = debuggerModel; var p = this.helpContentElement.createChild("p"); p.classList.add("help-section"); p.textContent = message; this._debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this.hide, this);}WebInspector.HelpScreenUntilReload.prototype = { willHide: function() { this._debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this.hide, this); WebInspector.HelpScreen.prototype.willHide.call(this); }, __proto__: WebInspector.HelpScreen.prototype};WebInspector.AdvancedApp = function() { WebInspector.dockController.addEventListener(WebInspector.DockController.Events.BeforeDockSideChanged, this._openToolboxWindow, this);};WebInspector.AdvancedApp.prototype = { presentUI: function(document) { var rootView = new WebInspector.RootView(); this._rootSplitWidget = new WebInspector.SplitWidget(false,true,"InspectorView.splitViewState",555,300,true); this._rootSplitWidget.show(rootView.element); this._rootSplitWidget.setSidebarWidget(WebInspector.inspectorView); 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._rootSplitWidget.setMainWidget(this._responsiveDesignView); 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(); WebInspector.inspectorView.showInitialPanel(); console.timeStamp("AdvancedApp.attachToBody"); rootView.attachToDocument(document); this._inspectedPagePlaceholder.update(); }, _openToolboxWindow: function(event) { if ((event.data.to) !== WebInspector.DockController.State.Undocked) return; if (this._toolboxWindow) return; var url = window.location.href.replace("inspector.html", "toolbox.html"); this._toolboxWindow = window.open(url, undefined); }, toolboxLoaded: function(toolboxDocument) { WebInspector.initializeUIUtils(toolboxDocument.defaultView); WebInspector.installComponentRootStyles((toolboxDocument.body)); WebInspector.ContextMenu.installHandler(toolboxDocument); var rootView = new WebInspector.RootView(); var inspectedPagePlaceholder = new WebInspector.InspectedPagePlaceholder(); inspectedPagePlaceholder.addEventListener(WebInspector.InspectedPagePlaceholder.Events.Update, this._onSetInspectedPageBounds.bind(this, true)); this._toolboxResponsiveDesignView = new WebInspector.ResponsiveDesignView(inspectedPagePlaceholder); this._toolboxResponsiveDesignView.show(rootView.element); rootView.attachToDocument(toolboxDocument); this._updatePageResizer(); }, inspectorFrontendHost: function() { return window.InspectorFrontendHost; }, _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._rootSplitWidget.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._rootSplitWidget.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._rootSplitWidget.setVertical(dockSide === WebInspector.DockController.State.DockedToRight); this._rootSplitWidget.setSecondIsSidebar(dockSide === WebInspector.DockController.State.DockedToRight || dockSide === WebInspector.DockController.State.DockedToBottom); this._rootSplitWidget.toggleResizer(this._rootSplitWidget.resizerElement(), true); this._rootSplitWidget.toggleResizer(WebInspector.inspectorView.topResizerElement(), dockSide === WebInspector.DockController.State.DockedToBottom); this._rootSplitWidget.showBoth(); }, _updateForUndocked: function() { this._rootSplitWidget.toggleResizer(this._rootSplitWidget.resizerElement(), false); this._rootSplitWidget.toggleResizer(WebInspector.inspectorView.topResizerElement(), false); this._rootSplitWidget.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); }};WebInspector.AdvancedApp._appInstance;WebInspector.AdvancedApp._instance = function() { if (!WebInspector.AdvancedApp._appInstance) WebInspector.AdvancedApp._appInstance = new WebInspector.AdvancedApp(); return WebInspector.AdvancedApp._appInstance;};WebInspector.AdvancedAppProvider = function() {};WebInspector.AdvancedAppProvider.prototype = { createApp: function() { return WebInspector.AdvancedApp._instance(); }};;WebInspector.RenderingOptions = function() { this._setterNames = new Map(); this._mapSettingToSetter(WebInspector.moduleSetting("showPaintRects"), "setShowPaintRects"); this._mapSettingToSetter(WebInspector.moduleSetting("showDebugBorders"), "setShowDebugBorders"); this._mapSettingToSetter(WebInspector.moduleSetting("showFPSCounter"), "setShowFPSCounter"); this._mapSettingToSetter(WebInspector.moduleSetting("continuousPainting"), "setContinuousPaintingEnabled"); this._mapSettingToSetter(WebInspector.moduleSetting("showScrollBottleneckRects"), "setShowScrollBottleneckRects"); WebInspector.targetManager.observeTargets(this, WebInspector.Target.Type.Page);}WebInspector.RenderingOptions.prototype = { targetAdded: function(target) { var settings = this._setterNames.keysArray(); for (var i = 0; i < settings.length; ++i) { var setting = settings[i]; if (setting.get()) { var setterName = this._setterNames.get(setting); target.renderingAgent()[setterName](true); } } }, targetRemoved: function(target) {}, _mapSettingToSetter: function(setting, setterName) { this._setterNames.set(setting, setterName); setting.addChangeListener(changeListener); function changeListener() { var targets = WebInspector.targetManager.targets(WebInspector.Target.Type.Page); for (var i = 0; i < targets.length; ++i) targets[i].renderingAgent()[setterName](setting.get()); } }}WebInspector.RenderingOptions.View = function() { WebInspector.VBox.call(this); this.registerRequiredCSS("ui/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.moduleSetting("showPaintRects"))); div.appendChild(WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Show composited layer borders"), WebInspector.moduleSetting("showDebugBorders"))); div.appendChild(WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Show FPS meter"), WebInspector.moduleSetting("showFPSCounter"))); div.appendChild(WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Enable continuous page repainting"), WebInspector.moduleSetting("continuousPainting"))); var child = WebInspector.SettingsUI.createSettingCheckbox(WebInspector.UIString("Show potential scroll bottlenecks"), WebInspector.moduleSetting("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.SimpleApp = function() {};WebInspector.SimpleApp.prototype = { presentUI: function(document) { var rootView = new WebInspector.RootView(); WebInspector.inspectorView.show(rootView.element); WebInspector.inspectorView.showInitialPanel(); rootView.attachToDocument(document); }};WebInspector.SimpleAppProvider = function() {};WebInspector.SimpleAppProvider.prototype = { createApp: function() { return new WebInspector.SimpleApp(); }};;WebInspector.evaluateForTestInFrontend = function(callId, script) { if (!InspectorFrontendHost.isUnderTest()) return; function invokeMethod() { try { script = script + "//# sourceURL=evaluateInWebInspector" + callId + ".js"; window.eval(script); } catch (e) { console.error(e.stack); } } InspectorBackend.connection().runAfterPendingDispatches(invokeMethod);};function createTestSuite(domAutomationController) { function TestSuite() { WebInspector.TestBase.call(this, domAutomationController); } ;TestSuite.prototype = { __proto__: WebInspector.TestBase.prototype }; TestSuite.prototype.showPanel = function(panelName) { return WebInspector.inspectorView.showPanel(panelName); } ; TestSuite.prototype.testShowScriptsTab = function() { var test = this; this.showPanel("sources").then(function() { this._waitUntilScriptsAreParsed(["debugger_test_page.html"], function() { test.releaseControl(); } ); } .bind(this)); this.takeControl(); } ; TestSuite.prototype.testScriptsTabIsPopulatedOnInspectedPageRefresh = function() { var test = this; var debuggerModel = WebInspector.DebuggerModel.fromTarget(WebInspector.targetManager.mainTarget()); debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed); this.showPanel("elements").then(function() { test.evaluateInConsole_("window.location.reload(true);", function(resultText) {} ); } ); function waitUntilScriptIsParsed() { debuggerModel.removeEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, waitUntilScriptIsParsed); test.showPanel("sources").then(function() { test._waitUntilScriptsAreParsed(["debugger_test_page.html"], function() { test.releaseControl(); } ); } ); } this.takeControl(); } ; TestSuite.prototype.testContentScriptIsPresent = function() { var test = this; this.showPanel("sources").then(function() { 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 = []; function switchToElementsTab() { test.showPanel("elements").then(function() { setTimeout(switchToScriptsTab, 0); } ); } function switchToScriptsTab() { test.showPanel("sources").then(function() { 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 = WebInspector.networkMapping.networkURL(uiSourceCodes[i]); for (var j = i + 1; j < uiSourceCodes.length; j++) test.assertTrue(scriptName !== WebInspector.networkMapping.networkURL(uiSourceCodes[j]), "Found script duplicates: " + test.uiSourceCodesToString_(uiSourceCodes)); } } this.showPanel("sources").then(function() { test._waitUntilScriptsAreParsed(["debugger_test_page.html"], function() { checkNoDuplicates(); setTimeout(switchToElementsTab, 0); } ); } ); this.takeControl(); } ; TestSuite.prototype.testPauseWhenLoadingDevTools = function() { var debuggerModel = WebInspector.DebuggerModel.fromTarget(WebInspector.targetManager.mainTarget()); if (debuggerModel.debuggerPausedDetails) return; this.showPanel("sources").then(function() { this._waitForScriptPause(this.releaseControl.bind(this)); } .bind(this)); this.takeControl(); } ; TestSuite.prototype.testPauseWhenScriptIsRunning = function() { this.showPanel("sources").then(function() { this.evaluateInConsole_('setTimeout("handleClick()", 0)', didEvaluateInConsole.bind(this)); } .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() { var target = WebInspector.targetManager.mainTarget(); target.pageAgent().navigate("about:crash"); target.pageAgent().navigate("about:blank"); target.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.testPauseInSharedWorkerInitialization1 = function() { function isReady() { return WebInspector.targetManager.targets().length == 2; } if (isReady()) return; this.takeControl(); this.addSniffer(WebInspector.TargetManager.prototype, "addTarget", targetAdded.bind(this)); function targetAdded() { if (isReady()) { this.releaseControl(); return; } this.addSniffer(WebInspector.TargetManager.prototype, "addTarget", targetAdded.bind(this)); } } ; TestSuite.prototype.testPauseInSharedWorkerInitialization2 = function() { var debuggerModel = WebInspector.DebuggerModel.fromTarget(WebInspector.targetManager.mainTarget()); if (debuggerModel.isPaused()) return; this._waitForScriptPause(this.releaseControl.bind(this)); this.takeControl(); } ; TestSuite.prototype.enableTouchEmulation = function() { WebInspector.overridesSupport._emulateTouchEventsInTarget(WebInspector.targetManager.mainTarget(), true, "mobile"); } ; 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) { WebInspector.targetManager.mainTarget().emulationAgent().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(); } WebInspector.overridesSupport._deviceMetricsChangedListenerMuted = true; test.takeControl(); this.waitForThrottler(WebInspector.overridesSupport._deviceMetricsThrottler, step1); } ; TestSuite.prototype.testScreenshotRecording = function() { var test = this; function performActionsInPage(callback) { var count = 0; var div = document.createElement("div"); div.setAttribute("style", "left: 0px; top: 0px; width: 100px; height: 100px; position: absolute;"); document.body.appendChild(div); requestAnimationFrame(frame); function frame() { var color = [0, 0, 0]; color[count % 3] = 255; div.style.backgroundColor = "rgb(" + color.join(",") + ")"; if (++count > 10) requestAnimationFrame(callback); else requestAnimationFrame(frame); } } var captureFilmStripSetting = WebInspector.settings.createSetting("timelineCaptureFilmStrip", false); captureFilmStripSetting.set(true); test.evaluateInConsole_(performActionsInPage.toString(), function() {} ); test.invokeAsyncWithTimeline_("performActionsInPage", onTimelineDone); function onTimelineDone() { captureFilmStripSetting.set(false); var filmStripModel = new WebInspector.FilmStripModel(WebInspector.panels.timeline._tracingModel); var frames = filmStripModel.frames(); test.assertTrue(frames.length > 4 && typeof frames.length === "number"); loadFrameImages(frames); } function loadFrameImages(frames) { var readyImages = []; for (var frame of frames) frame.imageDataPromise().then(onGotImageData) function onGotImageData(data) { var image = new Image(); test.assertTrue(!!data, "No image data for frame"); image.addEventListener("load", onLoad); image.src = "data:image/jpg;base64," + data; } function onLoad(event) { readyImages.push(event.target); if (readyImages.length === frames.length) validateImagesAndCompleteTest(readyImages); } } function validateImagesAndCompleteTest(images) { var redString = [255, 0, 0, 255].join(","); var greenString = [0, 255, 0, 255].join(","); var blueString = [0, 0, 255, 255].join(","); var redCount = 0; var greenCount = 0; var blueCount = 0; var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); for (var image of images) { test.assertTrue(image.naturalWidth > 10); test.assertTrue(image.naturalHeight > 10); canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; ctx.drawImage(image, 0, 0); var data = ctx.getImageData(0, 0, 1, 1); var color = Array.prototype.join.call(data.data, ","); if (color === redString) redCount++; else if (color === greenString) greenCount++; else if (color === blueString) blueCount++; else test.fail("Unexpected color: " + color); } test.assertTrue(redCount && greenCount && blueCount, "Color sanity check failed"); test.releaseControl(); } test.takeControl(); } TestSuite.prototype.testSettings = function() { var test = this; createSettings(); test.takeControl(); setTimeout(reset, 0); function createSettings() { var localSetting = WebInspector.settings.createSetting("local", undefined, true); localSetting.set({ s: "local", n: 1 }); var globalSetting = WebInspector.settings.createSetting("global", undefined, false); globalSetting.set({ s: "global", n: 2 }); } function reset() { Runtime.experiments.clearForTest(); InspectorFrontendHost.getPreferences(gotPreferences); } function gotPreferences(prefs) { WebInspector.Main._instanceForTest._createSettings(prefs); var localSetting = WebInspector.settings.createSetting("local", undefined, true); test.assertEquals("object", typeof localSetting.get()); test.assertEquals("local", localSetting.get().s); test.assertEquals(1, localSetting.get().n); var globalSetting = WebInspector.settings.createSetting("global", undefined, false); test.assertEquals("object", typeof globalSetting.get()); test.assertEquals("global", globalSetting.get().s); test.assertEquals(2, globalSetting.get().n); test.releaseControl(); } } 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.invokeAsyncWithTimeline_ = function(functionName, callback) { var test = this; test.showPanel("timeline").then(function() { WebInspector.panels.timeline._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStarted, onRecordingStarted); WebInspector.panels.timeline.toggleTimelineButton.element.click(); } ); function onRecordingStarted() { WebInspector.panels.timeline._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStarted, onRecordingStarted); test.evaluateInConsole_(functionName + "(function() { console.log('DONE'); });", function() {} ); WebInspector.multitargetConsoleModel.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, onConsoleMessage); } function onConsoleMessage(event) { var text = event.data.messageText; if (text === "DONE") { WebInspector.multitargetConsoleModel.removeEventListener(WebInspector.ConsoleModel.Events.MessageAdded, onConsoleMessage); pageActionsDone(); } } function pageActionsDone() { WebInspector.panels.timeline._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, onRecordingStopped); WebInspector.panels.timeline.toggleTimelineButton.element.click(); } function onRecordingStopped() { WebInspector.panels.timeline._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStopped, onRecordingStopped); callback(); } } ; TestSuite.prototype.uiSourceCodesToString_ = function(uiSourceCodes) { var names = []; for (var i = 0; i < uiSourceCodes.length; i++) names.push('"' + WebInspector.networkMapping.networkURL(uiSourceCodes[i]) + '"'); return names.join(","); } ; TestSuite.prototype.nonAnonymousUISourceCodes_ = function() { function filterOutAnonymous(uiSourceCode) { return !!WebInspector.networkMapping.networkURL(uiSourceCode); } 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.context.removeFlavorChangeListener(WebInspector.ExecutionContext, showConsoleAndEvaluate, this); var consoleView = WebInspector.ConsolePanel._view(); consoleView._prompt.setText(code); consoleView._promptElement.dispatchEvent(TestSuite.createKeyEvent("Enter")); this.addSniffer(WebInspector.ConsoleView.prototype, "_consoleMessageAddedForTest", function(viewMessage) { callback(viewMessage.toMessageElement().deepTextContent()); } .bind(this)); } function showConsoleAndEvaluate() { WebInspector.console.showPromise().then(innerEvaluate.bind(this)); } if (!WebInspector.context.flavor(WebInspector.ExecutionContext)) { WebInspector.context.addFlavorChangeListener(WebInspector.ExecutionContext, showConsoleAndEvaluate, this); return; } showConsoleAndEvaluate.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) { this.addSniffer(WebInspector.DebuggerModel.prototype, "_pausedScript", callback); } ; 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; } ; TestSuite.prototype.runTest = function(name) { var test = WebInspector.TestBase.prototype.runTest.bind(this, name); if (TestSuite._populatedInterface) test(); else TestSuite._pendingTest = test; } ; function runTests() { TestSuite._populatedInterface = true; var test = TestSuite._pendingTest; delete TestSuite._pendingTest; if (test) test(); } WebInspector.notifications.addEventListener(WebInspector.NotificationService.Events.InspectorAgentEnabledForTests, runTests); return new TestSuite();}if (window.uiTests) window.uiTests.testSuiteReady(createTestSuite, WebInspector.TestBase);;WebInspector.OverlayController = function() { WebInspector.moduleSetting("disablePausedStateOverlay").addChangeListener(this._updateOverlayMessage, this); WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.DebuggerPaused, this._updateOverlayMessage, this); WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.DebuggerResumed, this._updateOverlayMessage, this); WebInspector.targetManager.addModelListener(WebInspector.DebuggerModel, WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._updateOverlayMessage, this);}WebInspector.OverlayController.prototype = { _updateOverlayMessage: function(event) { var debuggerModel = (event.target); var message = debuggerModel.isPaused() && !WebInspector.moduleSetting("disablePausedStateOverlay").get() ? WebInspector.UIString("Paused in debugger") : undefined; debuggerModel.target().pageAgent().setOverlayMessage(message); }};WebInspector.Main = function() { WebInspector.console.setUIDelegate(this); WebInspector.Main._instanceForTest = this; runOnWindowLoad(this._loaded.bind(this));}WebInspector.Main.prototype = { showConsole: function() { return WebInspector.Revealer.revealPromise(WebInspector.console); }, _loaded: function() { console.timeStamp("Main._loaded"); if (InspectorFrontendHost.isUnderTest()) self.runtime.useTestBase(); InspectorFrontendHost.getPreferences(this._gotPreferences.bind(this)); }, _gotPreferences: function(prefs) { console.timeStamp("Main._gotPreferences"); this._createSettings(prefs); this._createAppUI(); }, _createSettings: function(prefs) { var settingsParam = Runtime.queryParam("settings"); if (settingsParam) { try { var settings = JSON.parse(window.decodeURI(settingsParam)); for (var key in settings) prefs[key] = settings[key]; } catch (e) {} } this._initializeExperiments(prefs); function trackPrefsObject(changes) { if (!Object.keys(prefs).length) { InspectorFrontendHost.clearPreferences(); return; } for (var change of changes) { var name = change.name; if (name in prefs) InspectorFrontendHost.setPreference(name, prefs[name]); else InspectorFrontendHost.removePreference(name); } } Object.observe(prefs, trackPrefsObject); WebInspector.settings = new WebInspector.Settings(prefs); if (!InspectorFrontendHost.isUnderTest()) new WebInspector.VersionController().updateVersion(); }, _initializeExperiments: function(prefs) { Runtime.experiments.register("accessibilityInspection", "Accessibility Inspection"); Runtime.experiments.register("animationInspection", "Animation Inspection"); Runtime.experiments.register("applyCustomStylesheet", "Allow custom UI themes"); Runtime.experiments.register("blackboxJSFramesOnTimeline", "Blackbox JavaScript frames on Timeline", true); Runtime.experiments.register("timelineDetailsChart", "Costly functions view in Timeline details", true); Runtime.experiments.register("customObjectFormatters", "Custom object formatters", true); Runtime.experiments.register("emptySourceMapAutoStepping", "Empty sourcemap auto-stepping"); Runtime.experiments.register("fileSystemInspection", "FileSystem inspection"); Runtime.experiments.register("gpuTimeline", "GPU data on timeline", true); Runtime.experiments.register("inputEventsOnTimelineOverview", "Input events on Timeline overview", true); Runtime.experiments.register("layersPanel", "Layers panel"); Runtime.experiments.register("layoutEditor", "Layout editor", true); Runtime.experiments.register("materialDesign", "Material design"); Runtime.experiments.register("networkRequestHeadersFilterInDetailsView", "Network request headers filter in details view", true); Runtime.experiments.register("networkRequestsOnTimeline", "Network requests on Timeline", true); Runtime.experiments.register("privateScriptInspection", "Private script inspection"); Runtime.experiments.register("promiseTracker", "Promise inspector"); Runtime.experiments.register("securityPanel", "Security panel", true); Runtime.experiments.register("serviceWorkersInPageFrontend", "Service workers in DevTools for page"); Runtime.experiments.register("serviceWorkersInResources", "Service workers in Resources panel", true); Runtime.experiments.register("showPrimaryLoadWaterfallInNetworkTimeline", "Show primary load waterfall in Network timeline", true); Runtime.experiments.register("stepIntoAsync", "Step into async"); Runtime.experiments.register("timelineInvalidationTracking", "Timeline invalidation tracking", true); Runtime.experiments.register("timelineTracingJSProfile", "Timeline tracing based JS profiler", true); Runtime.experiments.register("timelineFlowEvents", "Timeline flow events", true); Runtime.experiments.register("inlineVariableValues", "Display variable values inline while debugging"); Runtime.experiments.cleanUpStaleExperiments(); if (InspectorFrontendHost.isUnderTest()) { var testPath = JSON.parse(prefs["testPath"] || "\"\""); if (testPath.indexOf("debugger/promise") !== -1) Runtime.experiments.enableForTest("promiseTracker"); if (testPath.indexOf("elements/") !== -1) Runtime.experiments.enableForTest("animationInspection"); if (testPath.indexOf("layers/") !== -1) Runtime.experiments.enableForTest("layersPanel"); if (testPath.indexOf("service-workers/") !== -1) Runtime.experiments.enableForTest("serviceWorkersInResources"); if (testPath.indexOf("timeline/") !== -1 || testPath.indexOf("layers/") !== -1) Runtime.experiments.enableForTest("layersPanel"); } Runtime.experiments.setDefaultExperiments(["inlineVariableValues", "serviceWorkersInPageFrontend"]); }, _createAppUI: function() { console.timeStamp("Main._createApp"); WebInspector.initializeUIUtils(window); WebInspector.installComponentRootStyles((document.body)); this._addMainEventListeners(document); var canDock = !!Runtime.queryParam("can_dock"); WebInspector.zoomManager = new WebInspector.ZoomManager(window,InspectorFrontendHost); WebInspector.inspectorView = new WebInspector.InspectorView(); WebInspector.ContextMenu.initialize(); WebInspector.ContextMenu.installHandler(document); WebInspector.dockController = new WebInspector.DockController(canDock); WebInspector.overridesSupport = new WebInspector.OverridesSupport(); WebInspector.emulatedDevicesList = new WebInspector.EmulatedDevicesList(); WebInspector.multitargetConsoleModel = new WebInspector.MultitargetConsoleModel(); WebInspector.multitargetNetworkManager = new WebInspector.MultitargetNetworkManager(); WebInspector.shortcutsScreen = new WebInspector.ShortcutsScreen(); WebInspector.shortcutsScreen.section(WebInspector.UIString("Console")); WebInspector.shortcutsScreen.section(WebInspector.UIString("Elements Panel")); WebInspector.fileManager = new WebInspector.FileManager(); WebInspector.isolatedFileSystemManager = new WebInspector.IsolatedFileSystemManager(); WebInspector.workspace = new WebInspector.Workspace(WebInspector.isolatedFileSystemManager.mapping()); WebInspector.networkMapping = new WebInspector.NetworkMapping(WebInspector.workspace,WebInspector.isolatedFileSystemManager.mapping()); WebInspector.networkProjectManager = new WebInspector.NetworkProjectManager(WebInspector.targetManager,WebInspector.workspace,WebInspector.networkMapping); WebInspector.presentationConsoleMessageHelper = new WebInspector.PresentationConsoleMessageHelper(WebInspector.workspace); WebInspector.cssWorkspaceBinding = new WebInspector.CSSWorkspaceBinding(WebInspector.targetManager,WebInspector.workspace,WebInspector.networkMapping); WebInspector.debuggerWorkspaceBinding = new WebInspector.DebuggerWorkspaceBinding(WebInspector.targetManager,WebInspector.workspace,WebInspector.networkMapping); WebInspector.fileSystemWorkspaceBinding = new WebInspector.FileSystemWorkspaceBinding(WebInspector.isolatedFileSystemManager,WebInspector.workspace,WebInspector.networkMapping); WebInspector.breakpointManager = new WebInspector.BreakpointManager(null ,WebInspector.workspace,WebInspector.networkMapping,WebInspector.targetManager,WebInspector.debuggerWorkspaceBinding); WebInspector.extensionServer = new WebInspector.ExtensionServer(); new WebInspector.OverlayController(); new WebInspector.ContentScriptProjectDecorator(); new WebInspector.ExecutionContextSelector(WebInspector.targetManager,WebInspector.context); 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(); new WebInspector.ThrottlingIndicator(); WebInspector.domBreakpointsSidebarPane = new WebInspector.DOMBreakpointsSidebarPane(); WebInspector.actionRegistry = new WebInspector.ActionRegistry(); WebInspector.shortcutRegistry = new WebInspector.ShortcutRegistry(WebInspector.actionRegistry,document); WebInspector.ShortcutsScreen.registerShortcuts(); this._registerForwardedShortcuts(); this._registerMessageSinkListener(); var appExtension = self.runtime.extensions(WebInspector.AppProvider)[0]; appExtension.instancePromise().then(this._showAppUI.bind(this)); }, _showAppUI: function(appProvider) { var app = (appProvider).createApp(); WebInspector.dockController.initialize(); console.timeStamp("Main._presentUI"); app.presentUI(document); if (!Runtime.queryParam("isSharedWorker")) WebInspector.inspectElementModeController = new WebInspector.InspectElementModeController(); WebInspector.inspectorView.createToolbars(); InspectorFrontendHost.loadCompleted(); var extensions = self.runtime.extensions(WebInspector.QueryParamHandler); for (var extension of extensions) { var value = Runtime.queryParam(extension.descriptor()["name"]); if (value !== null ) extension.instancePromise().then(handleQueryParam.bind(null , value)); } setTimeout(this._createConnection.bind(this), 0); function handleQueryParam(value, handler) { handler.handleQueryParam(value); } }, _createConnection: function() { console.timeStamp("Main._createConnection"); InspectorBackend.loadFromJSONIfNeeded("../protocol.json"); if (Runtime.queryParam("ws")) { var ws = "ws://" + Runtime.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); var targetType = Runtime.queryParam("isSharedWorker") ? WebInspector.Target.Type.ServiceWorker : WebInspector.Target.Type.Page; WebInspector.targetManager.createTarget(WebInspector.UIString("Main"), targetType, connection, null , this._mainTargetCreated.bind(this)); }, _mainTargetCreated: function(target) { console.timeStamp("Main._mainTargetCreated"); this._mainTarget = (target); this._registerShortcuts(); this._mainTarget.registerInspectorDispatcher(this); if (this._mainTarget.isServiceWorker()) this._mainTarget.runtimeAgent().run(); WebInspector.overridesSupport.init(this._mainTarget, overridesReady); function overridesReady() { if (!WebInspector.dockController.canDock() && WebInspector.overridesSupport.emulationEnabled()) WebInspector.inspectorView.showViewInDrawer("emulation", true); target.inspectorAgent().enable(inspectorAgentEnableCallback); } function inspectorAgentEnableCallback() { console.timeStamp("Main.inspectorAgentEnableCallback"); WebInspector.notifications.dispatchEventToListeners(WebInspector.NotificationService.Events.InspectorAgentEnabledForTests); setTimeout(function() { WebInspector.extensionServer.initializeExtensions(); } , 0); } }, _registerForwardedShortcuts: function() { var forwardedActions = ["main.reload", "main.hard-reload", "main.toggle-dock"]; 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 target = event.target; if (target.shadowRoot) target = event.deepElementFromPoint(); if (!target) return; var anchor = target.enclosingNodeOrSelfWithNodeName("a"); if (!anchor || !anchor.href) return; event.consume(true); if (anchor.preventFollow) return; function followLink() { if (WebInspector.isBeingEdited(target)) return; if (WebInspector.openAnchorLocationRegistry.dispatch({ url: anchor.href, lineNumber: anchor.lineNumber })) return; var uiSourceCode = WebInspector.networkMapping.uiSourceCodeForURLForAnyTarget(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; } if (!anchor.classList.contains("webkit-html-external-link")) followLink(); else InspectorFrontendHost.openInNewTab(anchor.href); }, _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.dockController.canDock()) { section.addKey(shortcut.makeDescriptor("M", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Shift), WebInspector.UIString("Toggle device mode")); section.addKey(shortcut.makeDescriptor("D", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Shift), WebInspector.UIString("Toggle dock side")); } 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; var target = event.deepActiveElement(); if (target) { var anchor = target.enclosingNodeOrSelfWithNodeName("a"); if (anchor && anchor.preventFollow) event.preventDefault(); } 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(document) { document.addEventListener("keydown", this._postDocumentKeyDown.bind(this), false); document.addEventListener("beforecopy", this._documentCanCopy.bind(this), true); document.addEventListener("copy", this._documentCopy.bind(this), false); document.addEventListener("cut", this._documentCut.bind(this), false); document.addEventListener("paste", this._documentPaste.bind(this), false); document.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), true); document.addEventListener("click", this._documentClick.bind(this), false); }, inspect: function(payload, hints) { var object = this._mainTarget.runtimeModel.createRemoteObject(payload); if (object.isNode()) { WebInspector.Revealer.revealPromise(object).then(object.release.bind(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() { var debuggerModel = WebInspector.DebuggerModel.fromTarget(this._mainTarget); if (!debuggerModel) return; (new WebInspector.HelpScreenUntilReload(debuggerModel,WebInspector.UIString("Inspected target disconnected"),WebInspector.UIString("Inspected target disconnected. Once it reloads we will attach to it automatically."))).showModal(); }, evaluateForTestInFrontend: function(callId, script) { WebInspector.evaluateForTestInFrontend(callId, script); }}WebInspector.reload = function() { if (WebInspector.dockController.canDock() && WebInspector.dockController.dockSide() === WebInspector.DockController.State.Undocked) InspectorFrontendHost.setIsDocked(true, function() {} ); window.location.reload();}WebInspector.Main.ReloadActionDelegate = function() {}WebInspector.Main.ReloadActionDelegate.prototype = { handleAction: function(context, actionId) { switch (actionId) { case "main.reload": WebInspector.Main._reloadPage(false); break; case "main.hard-reload": WebInspector.Main._reloadPage(true); break; case "main.debug-reload": WebInspector.reload(); break; } }}WebInspector.Main.ZoomActionDelegate = function() {}WebInspector.Main.ZoomActionDelegate.prototype = { handleAction: function(context, actionId) { if (InspectorFrontendHost.isHostedMode()) return; switch (actionId) { case "main.zoom-in": InspectorFrontendHost.zoomIn(); break; case "main.zoom-out": InspectorFrontendHost.zoomOut(); break; case "main.zoom-reset": InspectorFrontendHost.resetZoom(); break; } }}WebInspector.Main._reloadPage = function(hard) { if (!WebInspector.targetManager.hasTargets()) return; if (WebInspector.targetManager.mainTarget().isServiceWorker()) return; WebInspector.targetManager.reloadPage(hard);}WebInspector.Main._addWebSocketTarget = function(ws) { function callback(connection) { WebInspector.targetManager.createTarget(ws, WebInspector.Target.Type.Page, connection, null ); } new InspectorBackendClass.WebSocketConnection(ws,callback);}WebInspector.Main.WarningErrorCounter = function() { this._counter = new WebInspector.ToolbarCounter(["error-icon", "revokedError-icon", "warning-icon"]); WebInspector.Main.WarningErrorCounter._instanceForTest = this._counter; 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 revokedErrors = 0; var warnings = 0; var targets = WebInspector.targetManager.targets(); for (var i = 0; i < targets.length; ++i) { errors += targets[i].consoleModel.errors(); revokedErrors += targets[i].consoleModel.revokedErrors(); warnings += targets[i].consoleModel.warnings(); } this._counter.setCounter("error-icon", errors, WebInspector.UIString(errors === 1 ? "%d error" : "%d errors", errors)); this._counter.setCounter("revokedError-icon", revokedErrors, WebInspector.UIString(revokedErrors === 1 ? "%d handled promise rejection" : "%d handled promise rejections", revokedErrors)); this._counter.setCounter("warning-icon", warnings, WebInspector.UIString(warnings === 1 ? "%d warning" : "%d warnings", warnings)); WebInspector.inspectorView.toolbarItemResized(); }, item: function() { return this._counter; }}WebInspector.ThrottlingIndicator = function() { var networkConditionsSetting = WebInspector.moduleSetting("networkConditions"); networkConditionsSetting.addChangeListener(updateVisibility); updateVisibility(); function updateVisibility() { var throttlingEnabled = WebInspector.NetworkManager.IsThrottlingEnabled(networkConditionsSetting.get()); WebInspector.inspectorView.setPanelIcon("network", throttlingEnabled ? "warning-icon" : "", WebInspector.UIString("Network throttling is enabled")); }}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 debuggerPausedDetails = (event.data); var debuggerModel = (event.target); WebInspector.context.setFlavor(WebInspector.Target, debuggerModel.target()); WebInspector.Revealer.reveal(debuggerPausedDetails); }}WebInspector.Main.InspectedNodeRevealer = function() { WebInspector.targetManager.addModelListener(WebInspector.DOMModel, WebInspector.DOMModel.Events.NodeInspected, this._inspectNode, this);}WebInspector.Main.InspectedNodeRevealer.prototype = { _inspectNode: function(event) { var deferredNode = (event.data); WebInspector.Revealer.reveal(deferredNode); }}WebInspector.RemoteDebuggingTerminatedScreen = function(reason) { WebInspector.HelpScreen.call(this, WebInspector.UIString("Detached from the target")); var p = this.helpContentElement.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.helpContentElement.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}new WebInspector.Main();;applicationDescriptor = [{ "name": "ui_lazy"}, { "name": "promises"}, { "name": "accessibility"}, { "name": "sources"}, { "type": "remote", "name": "emulated_devices"}, { "name": "audits"}, { "type": "autostart", "name": "bindings"}, { "name": "snippets"}, { "name": "layers"}, { "name": "console"}, { "name": "network"}, { "name": "components_lazy"}, { "type": "remote", "name": "cm_modes"}, { "type": "autostart", "name": "platform"}, { "name": "animation"}, { "name": "source_frame"}, { "type": "autostart", "name": "main"}, { "name": "resources"}, { "type": "worker", "name": "script_formatter_worker"}, { "name": "elements"}, { "type": "autostart", "name": "workspace"}, { "name": "timeline"}, { "type": "autostart", "name": "host"}, { "type": "autostart", "name": "emulation"}, { "type": "autostart", "name": "ui"}, { "type": "autostart", "name": "sdk"}, { "type": "worker", "name": "temp_storage_shared_worker"}, { "name": "settings"}, { "type": "worker", "name": "heap_snapshot_worker"}, { "name": "profiler"}, { "type": "remote", "name": "screencast", "condition": "remoteFrontend"}, { "type": "autostart", "name": "extensions"}, { "type": "autostart", "name": "common"}, { "type": "autostart", "name": "components"}, { "name": "security"}];Runtime.cachedResources["ui/checkboxTextLabel.css"] = "/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n padding: 0;\n margin: 0;\n display: inline-flex;\n flex-shrink: 0;\n align-items: center !important;\n}\n\ninput {\n height: 12px;\n width: 12px;\n flex-shrink: 0;\n}\n\ninput.dt-checkbox-themed {\n -webkit-appearance: none;\n margin: 0 5px auto 2px;\n border: 1px solid rgb(45, 45, 45);\n border-radius: 3px;\n background-color: rgb(102, 102, 102);\n position: relative;\n top: 1px;\n}\n\ninput.dt-checkbox-themed:after {\n content: '';\n line-height: 10px;\n position: absolute;\n cursor: pointer;\n width: 12px;\n height: 12px;\n background: none;\n}\n\ninput.dt-checkbox-themed:checked:after {\n background-color: #333;\n}\n\ninput.dt-checkbox-themed:after {\n -webkit-mask-image: url(Images/toolbarButtonGlyphs.png);\n -webkit-mask-size: 352px 144px;\n -webkit-mask-position: -128px -110px;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\ninput.dt-checkbox-themed:after {\n -webkit-mask-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n\n} /* media */\n\n/*# sourceURL=ui/checkboxTextLabel.css */";Runtime.cachedResources["ui/closeButton.css"] = "/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\ndiv {\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\ndiv {\n background-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.close-button {\n width: 14px;\n height: 14px;\n background-position: -128px -96px;\n cursor: default;\n}\n\n.close-button:hover {\n background-position: -96px -96px;\n}\n\n.close-button:active {\n background-position: -111px -96px;\n}\n\n.close-button-gray {\n width: 13px;\n height: 13px;\n background-position: -175px -96px;\n}\n\n.close-button-gray:hover {\n background-position: -143px -96px;\n}\n\n.close-button-gray:active {\n background-position: -160px -96px;\n}\n\n/*# sourceURL=ui/closeButton.css */";Runtime.cachedResources["ui/colorSwatch.css"] = "/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n white-space: nowrap;\n}\n\n.color-swatch {\n position: relative;\n margin-left: 1px;\n margin-right: 2px;\n width: 10px;\n height: 10px;\n top: 1px;\n display: inline-block;\n -webkit-user-select: none;\n background-image: url(Images/checker.png);\n line-height: 10px;\n}\n\n.color-swatch-inner {\n width: 100%;\n height: 100%;\n display: inline-block;\n border: 1px solid rgba(128, 128, 128, 0.6);\n}\n\n.color-swatch-inner:hover {\n border: 1px solid rgba(64, 64, 64, 0.8);\n}\n\n\n/*# sourceURL=ui/colorSwatch.css */";Runtime.cachedResources["ui/dropTarget.css"] = "/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n display: flex;\n background-color: rgba(255,255,255,0.8);\n z-index: 1000;\n}\n\n.drop-target-message {\n flex: auto;\n font-size: 30px;\n color: #999;\n display: flex;\n justify-content: center;\n align-items: center;\n margin: 20px;\n border: 4px dashed #ddd;\n pointer-events: none;\n}\n\n/*# sourceURL=ui/dropTarget.css */";Runtime.cachedResources["ui/emptyWidget.css"] = "/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.empty-view {\n font-size: 24px;\n color: rgb(75%, 75%, 75%);\n font-weight: bold;\n padding: 10px;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n/*# sourceURL=ui/emptyWidget.css */";Runtime.cachedResources["ui/filter.css"] = "/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.filter-bar {\n background-color: #f3f3f3;\n padding: 4px 0 2px 0;\n flex: none;\n border-bottom: 1px solid #dadada;\n}\n\n.filter-text-filter {\n display: inline-flex;\n margin-left: 1px;\n margin-right: 2px;\n min-width: 40px;\n max-width: 200px;\n height: 24px;\n align-items: center;\n}\n\n.filter-text-filter label {\n margin: auto 0;\n}\n\n.filter-bitset-filter {\n padding: 2px;\n display: inline-flex;\n overflow: hidden;\n height: 24px;\n position: relative;\n top: -1px;\n}\n\n.filter-bitset-filter li {\n display: inline-block;\n flex: none;\n margin: auto 2px;\n padding: 3px 6px 3px 3px;\n background: transparent;\n text-shadow: rgba(255, 255, 255, 0.5) 0 1px 0;\n border-radius: 8px;\n overflow: hidden;\n}\n\n.filter-bitset-filter-divider {\n background-color: #ccc;\n height: 16px;\n width: 1px;\n margin: auto 2px;\n display: inline-block;\n}\n\n.filter-bitset-filter li.selected,\n.filter-bitset-filter li:hover,\n.filter-bitset-filter li:active {\n color: white;\n text-shadow: rgba(0, 0, 0, 0.4) 0 1px 0;\n}\n\n.filter-bitset-filter li:hover {\n background: rgba(0, 0, 0, 0.2);\n}\n\n.filter-bitset-filter li.selected {\n background: rgba(0, 0, 0, 0.3);\n}\n\n.filter-bitset-filter li:active {\n background: rgba(0, 0, 0, 0.5);\n}\n\n.filter-combobox-filter {\n margin-left: 5px;\n margin-right: 2px;\n flex: 0 0 auto;\n display: inline-block;\n}\n\n.filter-checkbox-filter {\n padding-left: 4px;\n padding-right: 2px;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n display: inline-flex;\n vertical-align: middle;\n height: 24px;\n position: relative;\n top: -2px;\n}\n\n.filter-checkbox-filter > label {\n display: flex;\n margin: auto 0;\n}\n\n.filter-text-invalid {\n background-color: rgb(255, 200, 200);\n}\n\n.filter-checkbox-filter .checkbox-filter-checkbox {\n width: 10px;\n height: 10px;\n margin: auto 3px;\n padding: 0;\n border-radius: 2px;\n border: solid 1px;\n display: inline-block;\n overflow: visible;\n opacity: 0.8;\n flex-shrink: 0;\n}\n\n.filter-input-field {\n -webkit-appearance: none;\n border: 1px solid rgb(163, 163, 163);\n border-radius: 2px;\n padding: 1px 3px 0;\n margin: 0 0 0 1px;\n width: 253px;\n height: 20px;\n line-height: 17px;\n flex: 1;\n}\n\n/*# sourceURL=ui/filter.css */";Runtime.cachedResources["ui/helpScreen.css"] = ".help-window-outer {\n position: absolute !important;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2000;\n}\n\n.help-window-main {\n color: white;\n background-color: rgba(17, 17, 17, 0.85);\n display: -webkit-flex;\n -webkit-flex-direction: column;\n border-top-width: 0;\n border-radius: 10px;\n}\n\n.help-window-caption {\n border-bottom: solid 1px rgb(153, 153, 153);\n margin: 0 8px;\n padding: 0 2px;\n line-height: 28px;\n}\n\n.help-window-title {\n font-size: 16px;\n margin: 0;\n padding-top: 1px;\n margin-bottom: -1px;\n}\n\n.help-content {\n overflow-y: auto;\n overflow-x: hidden;\n margin: 8px;\n padding: 0 4px;\n flex: auto;\n}\n\n.help-footnote {\n border-top: 1px solid #EEEEEE;\n margin: 0;\n padding: 12px;\n}\n\n.help-window-main .help-container-wrapper::-webkit-scrollbar {\n width: 11px;\n}\n\n.help-window-main .help-container-wrapper::-webkit-scrollbar-corner,\n.help-window-main .help-container-wrapper::-webkit-resizer {\n display: none;\n}\n\n.help-window-main .help-container-wrapper::-webkit-scrollbar-thumb:vertical {\n background: linear-gradient(to right, rgb(128, 128, 128), rgb(96, 96, 96) 40%, rgb(128, 128, 128));\n border-radius: 5px;\n min-height: 20px;\n}\n\n.help-window-main .help-container-wrapper::-webkit-scrollbar-thumb:vertical:hover,\n.help-window-main .help-container-wrapper::-webkit-scrollbar-thumb:vertical:active {\n background: linear-gradient(to right, rgb(176, 176, 176), rgb(144, 144, 144) 40%, rgb(176, 176, 176));\n}\n\n.help-window-main .help-container-wrapper::-webkit-scrollbar-track:vertical {\n background: linear-gradient(to right, rgb(10, 10, 10), rgb(32, 32, 32) 25%, rgb(32, 32, 32));\n border-radius: 5px;\n}\n\n.help-close-button {\n position: absolute;\n top: 8px;\n right: 8px;\n z-index: 10;\n}\n\nbody.dock-to-bottom .help-content {\n margin-bottom: 8px;\n}\n\n.help-container {\n width: 100%;\n -webkit-user-select: auto;\n -webkit-column-width: 470px;\n}\n\n.help-no-columns {\n -webkit-column-width: initial !important;\n}\n\n.help-block {\n display: block;\n padding-bottom: 9px;\n width: 470px;\n -webkit-column-break-inside: avoid;\n}\n\n.settings-tab.help-container {\n -webkit-column-width: 410px;\n}\n\n.settings-tab .help-block {\n width: 410px;\n margin-left: 20px;\n}\n\n.settings-tab .field-error-message {\n color: DarkRed;\n height: 0; /* Avoid changing element height when content is set. */\n}\n\n.help-line {\n padding-bottom: 5px;\n margin-bottom: 5px;\n}\n\n.help-key-cell {\n display: inline-block;\n width: 270px;\n text-align: right;\n}\n\n.help-cell {\n display: inline-block;\n width: 200px;\n vertical-align: middle;\n}\n\n.help-section-title {\n font-size: 120%;\n}\n\n.help-key {\n padding: 0.1em 0.6em;\n border: 1px solid #ccc;\n font-size: 11px;\n background-color: #f7f7f7;\n color: #333;\n box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2), 0 0 0 2px #ffffff inset;\n border-radius: 3px;\n display: inline-block;\n margin: 0 0.1em;\n text-shadow: 0 1px 0 #fff;\n line-height: 1.5;\n white-space: nowrap;\n font-family: Lucida Grande, sans-serif;\n}\n\n.help-combine-keys,\n.help-key-delimiter {\n font-size: 9px;\n}\n\n.help-combine-keys {\n margin: 0 0.3em;\n}\n\n.help-key-delimiter {\n margin: 0 0.5em;\n}\n\n.help-window-outer fieldset {\n margin: 0;\n padding: 0;\n border: none;\n}\n\n.settings-tab label {\n padding-right: 4px;\n display: inline-flex;\n}\n\n#general-tab-content .help-block fieldset legend {\n font-size: 14px;\n}\n\n.help-block p p {\n padding-left: 30px;\n}\n\n.help-content p.help-section {\n margin: 0 0 15px 0;\n}\n\n.settings-experiments-warning-subsection-warning {\n color: rgb(200, 0, 0);\n}\n\n.settings-experiments-warning-subsection-message {\n color: inherit;\n}\n\n.help-content input[type=checkbox] {\n margin: 1px 7px 1px 2px;\n}\n\n.help-content option {\n background-color: #EEEEEE;\n color: #222;\n}\n\n#settings-screen .help-window-main{\n color: rgb(48, 57, 66);\n background-color: white;\n border-radius: 0;\n}\n\n#settings-screen .help-window-main {\n position: absolute;\n top: 10px;\n right: 10px;\n bottom: 10px;\n left: 10px;\n height: initial;\n padding: 11px 0 0 0;\n box-shadow: 1px 1px 5px 2px rgba(128, 128, 128, 0.7);\n}\n\n#settings-screen .help-window-label {\n font-size: 18px;\n color: inherit;\n padding: 1px 0 15px 17px;\n}\n\n.help-container-wrapper {\n position: absolute;\n top: 40px;\n left: 15px;\n right: 0;\n bottom: 0;\n overflow: auto;\n}\n\n.settings-tab.help-content {\n margin: 0;\n padding: 0;\n}\n\n.settings-tab input:not([type]),\n.settings-tab input[type=\"text\"] {\n border: 1px solid rgb(213, 213, 213);\n border-radius: 2px;\n color: #444444;\n padding: 3px;\n}\n\n.settings-tab input.numeric {\n text-align: right;\n}\n\n.settings-tab-container {\n flex: auto;\n overflow: hidden;\n}\n\n.settings-tab-container header {\n padding: 0 0 6px;\n border-bottom: 1px solid #EEEEEE;\n}\n\n#tab-shortcuts {\n margin-top: 25px !important;\n}\n\n#experiments-tab-content .help-container {\n -webkit-column-width: 470px;\n}\n\n#experiments-tab-content .help-block {\n width: 470px;\n}\n\n.settings-tab-container header > h3 {\n font-size: 18px;\n font-weight: normal;\n margin: 0;\n padding-bottom: 3px;\n}\n\n.settings-tab .help-section-title {\n margin-left: -20px;\n color: #222;\n}\n\n.settings-tab .help-block fieldset:disabled label:hover {\n color: inherit;\n}\n\n.settings-tab .help-block label:hover {\n color: #222;\n}\n\n.settings-tab p {\n margin: 12px 0;\n}\n\n.settings-tab select {\n margin-left: 10px;\n}\n\n#workspace-tab-content .settings-tab.help-content.help-container {\n -webkit-column-width: initial;\n}\n\n\n#workspace-tab-content .button:hover {\n opacity: 1.0 !important;\n}\n\n.settings-tab .settings-list-container {\n background-color: white;\n margin-bottom: 10px;\n}\n\n.settings-tab .settings-list {\n border: 1px solid hsl(0, 0%, 85%);\n border-radius: 2px;\n}\n\n.settings-tab .settings-list .settings-list-item .settings-list-item-contents {\n width: 100%;\n height: 40px;\n -webkit-box-align: center;\n -webkit-transition: 150ms background-color;\n display: -webkit-box;\n padding-right: 3px;\n}\n\n.settings-tab .settings-list .settings-list-item .settings-list-item-contents > :first-child {\n -webkit-box-align: center;\n -webkit-box-flex: 1;\n -webkit-padding-end: 5px;\n display: -webkit-box;\n}\n\n.settings-tab .settings-list .settings-list-item.selected:not(.editable) {\n background-color: hsl(0, 0%, 82%);\n}\n\n.settings-tab .settings-list .settings-list-item:hover {\n background-color: hsl(215, 54%, 93%);\n}\n\n.settings-tab .settings-list .settings-list-item.selected:not(.editable):hover {\n background-color: hsl(215, 51%, 82%);\n}\n\n.settings-tab .settings-list .settings-list-item .remove-item-button {\n -webkit-transition: 150ms opacity;\n background-color: hsla(0, 0%, 0%, 0);\n background-image: -webkit-image-set(\n url(Images/settingsListRemove.png) 1x,\n url(Images/settingsListRemove_2x.png) 2x);\n background-size: 48px 16px;\n border: none;\n display: block;\n height: 16px;\n width: 16px;\n opacity: 0;\n pointer-events: none;\n}\n\n.settings-tab .settings-list .settings-list-item.selected .remove-item-button,\n.settings-tab .settings-list .settings-list-item:hover .remove-item-button {\n opacity: 1;\n pointer-events: auto;\n}\n\n.settings-tab .settings-list .settings-list-item .remove-item-button:hover {\n background-position-x: -32px;\n}\n\n.settings-tab .settings-list .settings-list-item .remove-item-button:active {\n background-position-x: -16px;\n}\n\n.settings-list-item-columns {\n height: 100%;\n}\n\n.settings-tab .settings-list .settings-list-item .list-column {\n displaY: -webkit-box;\n -webkit-box-align: center;\n padding-left: 5px;\n padding-right: 2px;\n box-sizing: border-box;\n overflow: hidden;\n text-overflow: ellipsis;\n height: 100%;\n}\n\n.settings-tab .settings-list .settings-list-item .list-column .list-column-editor {\n width: 100%;\n}\n\n.settings-tab .settings-list .settings-list-item.add-list-item .remove-item-button {\n visibility: hidden;\n}\n\n.settings-tab .settings-list .settings-list-item.editable .list-column .list-column-editor {\n display: none;\n}\n\n.settings-tab .settings-list .settings-list-item.editable.item-editing .list-column .list-column-editor {\n display: block;\n}\n\n.settings-tab .settings-list .settings-list-item.editable.item-editing .list-column .list-column-text {\n display: none;\n}\n\n.settings-tab .settings-list .settings-list-item.editable.item-editing .list-column .list-column-editor.editable-item-error {\n background-color: pink;\n}\n\ninput.list-column-editor {\n border: 1px solid rgb(213, 213, 213);\n border-radius: 2px;\n color: #444444;\n padding: 3px;\n}\nselect.list-column-editor {\n padding: 2px;\n margin-left: 0;\n}\n\n.settings-tab .settings-list .settings-list-item .file-system-path {\n white-space: nowrap;\n font-size: 12px;\n padding-left: 6px;\n padding-right: 5px;\n -webkit-box-flex: 1;\n color: hsl(210, 16%, 22%);\n}\n\n.settings-tab .settings-list .settings-list-item .file-system-path-name {\n padding-right: 6px;\n font-weight: bold;\n}\n\n.file-systems-list .settings-list-item .list-column.settings-list-column-path {\n width: 100%;\n}\n\n.file-mappings-list .settings-list-item .list-column.settings-list-column-url {\n width: 50%;\n}\n\n.file-mappings-list .settings-list-item .list-column.settings-list-column-path {\n width: 50%;\n}\n\n.blackbox-patterns-list .settings-list-item .list-column.settings-list-column-pattern {\n width: 50%;\n}\n\n.blackbox-patterns-list .settings-list-item .list-column.settings-list-column-value {\n width: 50%;\n}\n\n.excluded-folders-list .settings-list-item .list-column.settings-list-column-path {\n width: 100%;\n}\n\n.settings-tab .settings-list .settings-list-item.disabled .settings-list-column-pattern .list-column-text {\n color: #666;\n text-decoration: line-through;\n}\n\n.settings-dialog {\n border-radius: 3px;\n box-shadow: 0 4px 23px 5px rgba(0, 0, 0, 0.2), 0 2px 6px rgba(0,0,0,0.15);\n display: -webkit-flex;\n -webkit-flex-direction: column;\n background: white;\n}\n\n.settings-dialog .dialog-contents {\n display: flex;\n flex-direction: column;\n}\n\n.settings-dialog .header {\n flex: 0 0 auto;\n color: #333;\n font-size: 14px;\n margin: 0;\n padding: 14px 17px 14px;\n}\n\n.settings-dialog .contents {\n flex: 1 1 auto;\n padding: 0 17px;\n overflow-x: hidden;\n overflow-y: auto;\n}\n\n.settings-dialog .block-header {\n color: black;\n font-size: 1.2em;\n margin-bottom: 0.8em;\n}\n\n.blackbox-dialog .columns-header {\n color: black;\n font-weight: bold;\n margin-bottom: 0.4em;\n display: -webkit-box;\n padding: 0;\n}\n\n.blackbox-dialog .columns-header span {\n width: 50%;\n display: -webkit-box;\n}\n\n.blackbox-dialog .columns-header span + span {\n margin-left: -7px\n}\n\n.blackbox-content-scripts {\n padding: 0 0 14px 0;\n margin-left: -4px;\n}\n\n.settings-dialog .done-button {\n float: right;\n}\n\n.settings-glass-pane {\n -webkit-box-align: center;\n -webkit-box-orient: vertical;\n -webkit-box-pack: center;\n display: -webkit-box;\n z-index: 2000 !important;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.4) !important;\n}\n\n.help-indent-labels label {\n padding-left: 10px;\n}\n\n.dialog-contents .section {\n min-width: 400px;\n}\n\n.settings-experiment-hidden {\n display: none;\n}\n\n.settings-experiment-hidden label {\n background-color: #ddd;\n}\n\n.settings-developer-mode .settings-experiment-hidden {\n display: block;\n}\n\n/*# sourceURL=ui/helpScreen.css */";Runtime.cachedResources["ui/infobar.css"] = "/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.infobar {\n color: rgb(34, 34, 34);\n padding: 4px 6px;\n white-space: nowrap;\n display: flex;\n align-items: flex-start;\n flex: auto;\n border-bottom: 1px solid rgb(171, 171, 171);\n}\n\n.infobar-warning {\n background-color: rgb(253, 242, 192);\n}\n\n.infobar-info {\n background-color: rgb(255, 255, 255);\n}\n\n.infobar .icon {\n flex: none;\n}\n\n.infobar .content {\n flex: auto;\n padding-left: 3px;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.infobar .close-button {\n flex: none;\n}\n\n.infobar .disable-button {\n flex: none;\n margin-right: 5px;\n text-decoration: underline;\n cursor: pointer;\n}\n\n/*# sourceURL=ui/infobar.css */";Runtime.cachedResources["ui/inspectorCommon.css"] = "/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n* {\n /* This is required for correct sizing of flex items because we rely\n * on an old version of the flexbox spec.\n * Longer-term we should remove this, see crbug.com/473625 */\n min-width: 0;\n min-height: 0;\n}\n\n:host-context(.platform-mac) .monospace,\n:host-context(.platform-mac) .source-code,\n.platform-mac .monospace,\n.platform-mac .source-code {\n font-size: 11px !important;\n font-family: Menlo, monospace;\n}\n\n:host-context(.platform-windows) .monospace,\n:host-context(.platform-windows) .source-code,\n.platform-windows .monospace,\n.platform-windows .source-code {\n font-size: 12px !important;\n font-family: Consolas, Lucida Console, monospace;\n}\n\n:host-context(.platform-linux) .monospace,\n:host-context(.platform-linux) .source-code,\n.platform-linux .monospace,\n.platform-linux .source-code {\n font-size: 11px !important;\n font-family: dejavu sans mono, monospace;\n}\n\n.source-code {\n font-family: monospace;\n font-size: 11px !important;\n white-space: pre-wrap;\n}\n\n* {\n box-sizing: border-box;\n}\n\n:focus {\n outline: none;\n}\n\nimg {\n -webkit-user-drag: none;\n}\n\niframe,\na img {\n border: none;\n}\n\n.fill {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n}\n\niframe.fill {\n width: 100%;\n height: 100%;\n}\n\n.widget {\n position: relative;\n flex: auto;\n}\n\n.hbox {\n display: flex;\n flex-direction: row !important;\n position: relative;\n}\n\n.vbox {\n display: flex;\n flex-direction: column !important;\n position: relative;\n}\n\n.flex-auto {\n flex: auto;\n}\n\n.flex-none {\n flex: none;\n}\n\n.flex-centered {\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\niframe.widget {\n position: absolute;\n width: 100%;\n height: 100%;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n}\n\n.hidden {\n display: none !important;\n}\n\n.monospace {\n font-size: 10px !important;\n font-family: monospace;\n}\n\n.highlighted-search-result {\n border-radius: 1px;\n padding: 1px;\n margin: -1px;\n background-color: rgba(255, 255, 0, 0.8);\n}\n\n.link {\n cursor: pointer;\n text-decoration: underline;\n color: rgb(17, 85, 204);\n}\n\nbutton,\ninput,\nselect {\n font-family: inherit;\n font-size: inherit;\n}\n\ninput[type=\"search\"]:focus,\ninput[type=\"text\"]:focus {\n outline: auto 5px -webkit-focus-ring-color;\n}\n\n\n.highlighted-search-result.current-search-result {\n border-radius: 1px;\n padding: 1px;\n margin: -1px;\n background-color: rgba(255, 127, 0, 0.8);\n}\n\n.dimmed {\n opacity: 0.6;\n}\n\n/*# sourceURL=ui/inspectorCommon.css */";Runtime.cachedResources["ui/inspectorSyntaxHighlight.css"] = "/*\n * Copyright (C) 2009 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n.cm-js-keyword {color: rgb(170, 13, 145);}\n.cm-js-number {color: rgb(28, 0, 207);}\n.cm-js-comment {color: rgb(0, 116, 0);}\n.cm-js-string {color: rgb(196, 26, 22);}\n.cm-js-string-2 {color: rgb(196, 26, 22);}\n\n.cm-css-keyword { color: rgb(7, 144, 154);}\n.cm-css-number {color: rgb(50, 0, 255);}\n.cm-css-comment {color: rgb(0, 116, 0);}\n.cm-css-def {color: rgb(200, 0, 0);}\n.cm-css-meta {color: rgb(200, 0, 0);}\n.cm-css-atom {color: rgb(7, 144, 154);}\n.cm-css-string {color: rgb(7, 144, 154);}\n.cm-css-string-2 {color: rgb(7, 144, 154);}\n.cm-css-link {color: rgb(7, 144, 154);}\n.cm-css-variable {color: rgb(200, 0, 0);}\n.cm-css-variable-2 {color: rgb(0, 0, 128);}\n.cm-css-property, .webkit-css-property {color: rgb(200, 0, 0);}\n\n.cm-xml-meta {color: rgb(192, 192, 192);}\n.cm-xml-comment {color: rgb(35, 110, 37);}\n.cm-xml-string {color: rgb(26, 26, 166);}\n.cm-xml-tag {color: rgb(136, 18, 128);}\n.cm-xml-attribute {color: rgb(153, 69, 0);}\n.cm-xml-link {color: #00e;}\n\n.webkit-html-comment {\n /* Keep this in sync with view-source.css (.webkit-html-comment) */\n color: rgb(35, 110, 37);\n}\n\n.webkit-html-tag {\n /* Keep this in sync with view-source.css (.webkit-html-tag) */\n color: rgb(136, 18, 128);\n}\n\n.webkit-html-pseudo-element {\n /* This one is non-standard. */\n color: brown;\n}\n\n.webkit-html-js-node,\n.webkit-html-css-node {\n white-space: pre;\n}\n\n.webkit-html-text-node {\n unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-entity-value {\n /* This one is non-standard. */\n background-color: rgba(0, 0, 0, 0.15);\n unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-doctype {\n /* Keep this in sync with view-source.css (.webkit-html-doctype) */\n color: rgb(192, 192, 192);\n}\n\n.webkit-html-attribute-name {\n /* Keep this in sync with view-source.css (.webkit-html-attribute-name) */\n color: rgb(153, 69, 0);\n unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-attribute-value {\n /* Keep this in sync with view-source.css (.webkit-html-attribute-value) */\n color: rgb(26, 26, 166);\n unicode-bidi: -webkit-isolate;\n}\n\n.webkit-html-external-link,\n.webkit-html-resource-link {\n /* Keep this in sync with view-source.css (.webkit-html-external-link, .webkit-html-resource-link) */\n color: #00e;\n}\n\n.webkit-html-resource-link {\n /* Required for consistency with view-source.css, since anchors may not have href attributes */\n text-decoration: underline;\n cursor: pointer;\n}\n\n.webkit-html-external-link {\n /* Keep this in sync with view-source.css (.webkit-html-external-link) */\n text-decoration: none;\n}\n\n.webkit-html-external-link:hover {\n /* Keep this in sync with view-source.css (.webkit-html-external-link:hover) */\n text-decoration: underline;\n}\n\n.webkit-html-end-of-file {\n /* Keep this in sync with view-source.css (.webkit-html-end-of-file) */\n color: rgb(255, 0, 0);\n font-weight: bold;\n}\n\n/*# sourceURL=ui/inspectorSyntaxHighlight.css */";Runtime.cachedResources["ui/panelEnablerView.css"] = "/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.panel-enabler-view {\n background-color: white;\n font-size: 13px;\n text-align: center;\n overflow-x: hidden;\n overflow-y: overlay;\n flex: auto;\n display: flex;\n}\n\n.panel-enabler-view h1 {\n color: rgb(110, 116, 128);\n font-size: 16px;\n line-height: 20px;\n font-weight: normal;\n margin-top: 0;\n}\n\n.panel-enabler-view img {\n height: 100%;\n min-height: 200px;\n max-width: 100%;\n top: 0;\n bottom: 0;\n padding: 20px 0 20px 20px;\n margin: auto;\n vertical-align: middle;\n}\n\n.panel-enabler-view img.hidden {\n display: initial !important;\n width: 0;\n}\n\n.panel-enabler-view .flexible-space {\n -webkit-flex: 1;\n}\n\n.panel-enabler-view form {\n display: inline-block;\n vertical-align: middle;\n width: 330px;\n margin: 0;\n padding: 15px;\n white-space: normal;\n}\n\n.panel-enabler-view label {\n position: relative;\n display: block;\n text-align: left;\n word-break: break-word;\n margin: 0 0 5px 20px;\n}\n\n/*# sourceURL=ui/panelEnablerView.css */";Runtime.cachedResources["ui/progressIndicator.css"] = "/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.progress-indicator-shadow-stop-button {\n background-color: rgb(216, 0, 0) !important;\n border: 0;\n width: 10px;\n height: 12px;\n border-radius: 2px;\n}\n\n.progress-indicator-shadow-container {\n display: flex;\n flex: 1 0 auto;\n align-items: center;\n}\n\n.progress-indicator-shadow-container .title {\n text-overflow: ellipsis;\n overflow: hidden;\n max-width: 150px;\n margin-right: 2px;\n color: #777;\n}\n\n.progress-indicator-shadow-container progress {\n flex: auto;\n margin: 0 2px;\n width: 100px\n}\n\n/*# sourceURL=ui/progressIndicator.css */";Runtime.cachedResources["ui/propertiesSection.css"] = "/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.properties-tree {\n margin: 0;\n padding: 0 6px 2px;\n list-style: none;\n min-height: 18px;\n}\n\n.properties-tree ol {\n display: none;\n margin: 0;\n -webkit-padding-start: 12px;\n list-style: none;\n}\n\n.properties-tree ol.expanded {\n display: block;\n}\n\n.properties-tree li {\n margin-left: 12px;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n -webkit-user-select: text;\n cursor: default;\n padding-top: 2px;\n line-height: 12px;\n}\n\n.properties-tree li.parent {\n margin-left: 1px;\n}\n\n.properties-tree li.parent::before {\n -webkit-user-select: none;\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n opacity: 0.5;\n content: \"a\";\n width: 8px;\n float: left;\n margin-right: 4px;\n color: transparent;\n text-shadow: none;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.properties-tree li.parent::before {\n background-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.properties-tree li.parent::before {\n background-position: -4px -96px;\n}\n\n.properties-tree li.parent.expanded::before {\n background-position: -20px -96px;\n}\n\n.properties-tree li .info {\n padding-top: 4px;\n padding-bottom: 3px;\n}\n\n.properties-tree li.editing {\n margin-left: 10px;\n text-overflow: clip;\n}\n\n.properties-tree li.editing-sub-part {\n padding: 3px 6px 8px 18px;\n margin: -1px -6px -8px -6px;\n text-overflow: clip;\n}\n\n.properties-tree .name {\n color: rgb(136, 19, 145);\n flex-shrink: 0;\n}\n\n.properties-tree .separator {\n flex-shrink: 0;\n}\n\n.properties-tree .dimmed {\n opacity: 0.6;\n}\n\n.properties-tree .value.error {\n color: red;\n}\n\n.properties-tree .number {\n color: blue;\n}\n\n.properties-tree .keyword {\n color: rgb(136, 19, 79);\n}\n\n.properties-tree .color {\n color: rgb(118, 15, 21);\n}\n\n/*# sourceURL=ui/propertiesSection.css */";Runtime.cachedResources["ui/radioButton.css"] = "/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n::content .dt-radio-button {\n height: 17px;\n width: 17px;\n min-width: 17px;\n border: 1px solid rgb(165, 165, 165);\n background-image: linear-gradient(to bottom, rgb(252, 252, 252), rgb(223, 223, 223));\n border-radius: 8px;\n -webkit-appearance: none;\n vertical-align: middle;\n margin: 0 5px 5px 0;\n}\n\n::content .dt-radio-button:active:not(:disabled) {\n background-image: linear-gradient(to bottom, rgb(194, 194, 194), rgb(239, 239, 239));\n}\n\n::content .dt-radio-button:checked {\n background: url(Images/radioDot.png) center no-repeat,\n linear-gradient(to bottom, rgb(252, 252, 252), rgb(223, 223, 223));\n}\n\n::content .dt-radio-button:checked:active {\n background: url(Images/radioDot.png) center no-repeat,\n linear-gradient(to bottom, rgb(194, 194, 194), rgb(239, 239, 239));\n}\n\n/*# sourceURL=ui/radioButton.css */";Runtime.cachedResources["ui/searchableView.css"] = "/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.search-bar {\n flex: 0 0 23px;\n background-color: #eee;\n border-top: 1px solid #ccc;\n display: flex;\n overflow: hidden;\n}\n\n.search-bar.replaceable {\n flex: 0 0 44px;\n}\n\n.search-replace {\n -webkit-appearance: none;\n border: 0;\n padding: 0 3px;\n margin: 0;\n flex: 1;\n}\n\n.search-replace:focus {\n outline: none;\n}\n\n.toolbar-search {\n border-spacing: 1px;\n}\n\n.toolbar-search td {\n padding: 0 5px 0 0;\n}\n\n.toolbar-search td > span {\n display: flex;\n align-items: baseline;\n line-height: 17px;\n}\n\n.toolbar-search-navigation-controls {\n align-self: stretch;\n background-image: linear-gradient(rgb(228, 228, 228), rgb(206, 206, 206));\n}\n\n.toolbar-search-navigation {\n display: inline-block;\n width: 18px;\n height: 18px;\n background-repeat: no-repeat;\n background-position: 4px 7px;\n border-left: 1px solid rgb(170, 170, 170);\n opacity: 0.3;\n}\n\n.toolbar-search-navigation.enabled {\n opacity: 1.0;\n}\n\n.toolbar-search button.search-action-button {\n border: 1px solid rgb(163, 163, 163);\n border-radius: 8px;\n margin: 0;\n background-image: linear-gradient(rgb(241, 241, 241), rgb(220, 220, 220));\n width: 100%;\n height: 20px;\n}\n\n.toolbar-search button.search-action-button:active {\n background-image: linear-gradient(rgb(185, 185, 185), rgb(156, 156, 156));\n}\n\n.toolbar-search-control {\n display: -webkit-flex;\n position: relative;\n background-color: white;\n}\n\n.toolbar-replace-control,\n#search-input-field {\n padding-top: 1px;\n line-height: 17px;\n}\n\n.toolbar-search-control, .toolbar-replace-control {\n border: 1px solid rgb(163, 163, 163);\n height: 20px;\n border-radius: 2px;\n width: 253px;\n margin-left: 1px;\n}\n\n.toolbar-search-navigation.enabled:active {\n background-position: 4px 7px, 0 0;\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-prev {\n background-image: url(Images/searchPrev.png);\n border-left: 1px solid rgb(163, 163, 163);\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-prev.enabled:active {\n background-image: url(Images/searchPrev.png), linear-gradient(rgb(168, 168, 168), rgb(116, 116, 116));\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-next {\n background-image: url(Images/searchNext.png);\n border-left: 1px solid rgb(230, 230, 230);\n}\n\n.toolbar-search-navigation.toolbar-search-navigation-next.enabled:active {\n background-image: url(Images/searchNext.png), linear-gradient(rgb(168, 168, 168), rgb(116, 116, 116));\n}\n\n.search-results-matches {\n display: inline-block;\n text-align: right;\n font-size: 11px;\n padding: 0 4px;\n color: rgb(165, 165, 165);\n}\n\n/*# sourceURL=ui/searchableView.css */";Runtime.cachedResources["ui/section.css"] = "/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.section {\n position: relative;\n margin-top: 1px;\n}\n\n.section > .header {\n padding: 0 8px 0 5px;\n min-height: 18px;\n white-space: nowrap;\n background-origin: padding-box;\n background-clip: padding-box;\n}\n\n.section > .header::before {\n -webkit-user-select: none;\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n opacity: 0.5;\n content: \"a\";\n color: transparent;\n text-shadow: none;\n float: left;\n width: 8px;\n margin-right: 4px;\n margin-top: 2px;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.section > .header::before {\n background-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.section > .header::before {\n background-position: -4px -96px;\n}\n\n.section.expanded > .header::before {\n background-position: -20px -96px;\n}\n\n.section > .header .title {\n font-weight: normal;\n word-wrap: break-word;\n white-space: normal;\n line-height: 18px;\n}\n\n.section > .header label {\n display: none;\n}\n\n.section.expanded .header label {\n display: inline;\n}\n\n.section > .header .subtitle {\n float: right;\n margin-left: 5px;\n max-width: 55%;\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.section > .header .subtitle a {\n color: inherit;\n}\n\n.section > .properties {\n display: none;\n}\n\n.section.expanded > .properties {\n display: block;\n}\n\n/*# sourceURL=ui/section.css */";Runtime.cachedResources["ui/smallIcon.css"] = "/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\ndiv {\n width: 10px;\n height: 10px;\n margin-right: 2px;\n display: inline-block;\n}\n\ndiv.error-icon,\ndiv.revokedError-icon,\ndiv.warning-icon,\ndiv.info-icon,\ndiv.device-icon,\ndiv.red-ball,\ndiv.green-ball,\ndiv.orange-ball {\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\ndiv.error-icon,\ndiv.revokedError-icon,\ndiv.warning-icon,\ndiv.info-icon,\ndiv.device-icon,\ndiv.red-ball,\ndiv.green-ball,\ndiv.orange-ball {\n background-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\ndiv.error-icon {\n background-position: -213px -96px;\n}\n\ndiv.revokedError-icon {\n background-position: -245px -107px;\n}\n\ndiv.warning-icon {\n background-position: -202px -107px;\n}\n\ndiv.info-icon {\n background-position: -213px -107px;\n}\n\ndiv.device-icon {\n background-position: -224px -107px;\n}\n\ndiv.red-ball {\n background-position: -224px -96px;\n}\n\ndiv.green-ball {\n background-position: -235px -96px;\n}\n\ndiv.orange-ball {\n background-position: -246px -96px;\n}\n\n/*# sourceURL=ui/smallIcon.css */";Runtime.cachedResources["ui/softContextMenu.css"] = "/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n position: absolute;\n border: 1px solid rgba(196, 196, 196, 0.9);\n border-top: 1px solid rgba(196, 196, 196, 0.5);\n border-bottom: 1px solid rgba(150, 150, 150, 0.9);\n padding: 4px 0 4px 0;\n border-radius: 4px;\n background-color: white;\n box-shadow: 0 5px 10px rgba(0, 0, 0, 0.25);\n}\n\n.soft-context-menu-item {\n width: 100%;\n line-height: 13px;\n font-size: 14px;\n border-top: 1px solid transparent;\n border-bottom: 1px solid transparent;\n padding: 2px 7px 2px 6px;\n margin: 0 13px 0 0;\n white-space: nowrap;\n}\n\n.soft-context-menu-separator {\n height: 10px;\n margin: 0 1px;\n}\n\n.soft-context-menu-separator > .separator-line {\n margin: 0;\n height: 5px;\n border-bottom: 1px solid rgb(227, 227, 227);\n pointer-events: none;\n}\n\n.soft-context-menu-item-mouse-over {\n border-top: 1px solid rgb(56, 121, 217);\n border-bottom: 1px solid rgb(56, 121, 217);\n background-color: rgb(56, 121, 217);\n color: white;\n}\n\n:host-context(.platform-mac) .soft-context-menu-item-mouse-over {\n border-top: 1px solid rgb(90, 131, 236);\n border-bottom: 1px solid rgb(18, 88, 233);\n background-image: linear-gradient(to bottom, rgb(100, 140, 243), rgb(36, 101, 243));\n}\n\n.soft-context-menu-item-checkmark {\n color: rgb(108, 108, 108);\n pointer-events: none;\n}\n\n.soft-context-menu-item-submenu-arrow {\n color: #222;\n float: right;\n pointer-events: none;\n}\n\n.soft-context-menu-item-mouse-over .soft-context-menu-item-checkmark {\n color: white;\n}\n\n/*# sourceURL=ui/softContextMenu.css */";Runtime.cachedResources["ui/splitWidget.css"] = "/*\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC.\n * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n:host {\n overflow: hidden;\n}\n\n.shadow-split-widget {\n display: flex;\n overflow: hidden;\n}\n\n.shadow-split-widget-contents {\n display: flex;\n position: relative;\n flex-direction: column;\n}\n\n.shadow-split-widget-sidebar {\n flex: none;\n}\n\n.shadow-split-widget-main, .shadow-split-widget-sidebar.maximized {\n flex: auto;\n}\n\n.shadow-split-widget.hbox > .shadow-split-widget-resizer {\n position: absolute;\n top: 0;\n bottom: 0;\n width: 6px;\n z-index: 500;\n}\n\n.shadow-split-widget.vbox > .shadow-split-widget-resizer {\n position: absolute;\n left: 0;\n right: 0;\n height: 6px;\n z-index: 500;\n}\n\n.shadow-split-widget.hbox.shadow-split-widget-first-is-sidebar {\n flex-direction: row-reverse !important;\n}\n\n.shadow-split-widget.vbox.shadow-split-widget-first-is-sidebar {\n flex-direction: column-reverse !important;\n}\n\n.shadow-split-widget-resizer-border {\n pointer-events: none;\n}\n\n.shadow-split-widget.vbox > .shadow-split-widget-sidebar:not(.maximized) {\n border: 0;\n border-top: 1px solid rgb(64%, 64%, 64%);\n}\n\n.shadow-split-widget.vbox.shadow-split-widget-first-is-sidebar > .shadow-split-widget-sidebar:not(.maximized) {\n border: 0;\n border-bottom: 1px solid rgb(64%, 64%, 64%);\n}\n\n.shadow-split-widget.hbox > .shadow-split-widget-sidebar:not(.maximized) {\n border: 0;\n border-left: 1px solid rgb(64%, 64%, 64%);\n}\n\n.shadow-split-widget.hbox.shadow-split-widget-first-is-sidebar > .shadow-split-widget-sidebar:not(.maximized) {\n border: 0;\n border-right: 1px solid rgb(64%, 64%, 64%);\n}\n\n.shadow-split-widget button.sidebar-show-hide-button {\n position: absolute;\n -webkit-mask-image: url(Images/toolbarButtonGlyphs.png);\n -webkit-mask-size: 352px 144px;\n height: 16px;\n width: 16px;\n border: none;\n z-index: 20;\n background-color: #5a5a5a;\n}\n\n.shadow-split-widget button.sidebar-show-hide-button:hover {\n background-color: #333;\n}\n\n.shadow-split-widget button.sidebar-show-hide-button:active {\n background-color: #5a5a5a;\n}\n\n.shadow-split-widget button.sidebar-show-hide-button:disabled {\n background-color: rgba(0, 0, 0, 0.35);\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.shadow-split-widget button.sidebar-show-hide-button {\n -webkit-mask-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.shadow-split-widget button.left-sidebar-show-hide-button,\n.shadow-split-widget button.top-sidebar-show-hide-button {\n top: 5px;\n left: 5px;\n}\n\n:host-context(.material) .shadow-split-widget button.left-sidebar-show-hide-button,\n:host-context(.material) .shadow-split-widget button.top-sidebar-show-hide-button {\n top: 5px;\n}\n\n.shadow-split-widget button.right-sidebar-show-hide-button {\n top: 5px;\n right:4px;\n}\n\n:host-context(.material) .shadow-split-widget button.right-sidebar-show-hide-button {\n top: 5px;\n right: 5px;\n}\n\n.shadow-split-widget button.bottom-sidebar-show-hide-button {\n bottom: 5px;\n right: 3px;\n}\n\n.shadow-split-widget button.left-sidebar-show-hide-button.toggled-show {\n -webkit-mask-position: -168px -76px; /* |> */\n}\n\n.shadow-split-widget button.left-sidebar-show-hide-button.toggled-hide {\n -webkit-mask-position: -199px -76px; /* |< */\n}\n\n.shadow-split-widget button.right-sidebar-show-hide-button.toggled-show {\n -webkit-mask-position: -296px -76px; /* <| */\n}\n\n.shadow-split-widget button.right-sidebar-show-hide-button.toggled-hide {\n -webkit-mask-position: -264px -76px; /* >| */\n}\n\n.shadow-split-widget button.top-sidebar-show-hide-button.toggled-show {\n -webkit-mask-position: -168px -76px; /* |> */\n transform: rotate(90deg);\n}\n\n.shadow-split-widget button.top-sidebar-show-hide-button.toggled-hide {\n -webkit-mask-position: -199px -76px; /* |< */\n transform: rotate(90deg);\n}\n\n.shadow-split-widget button.bottom-sidebar-show-hide-button.toggled-show {\n -webkit-mask-position: -296px -76px; /* <| */\n transform: rotate(90deg);\n}\n\n.shadow-split-widget button.bottom-sidebar-show-hide-button.toggled-hide {\n -webkit-mask-position: -264px -76px; /* >| */\n transform: rotate(90deg);\n}\n\n/*# sourceURL=ui/splitWidget.css */";Runtime.cachedResources["ui/toolbar.css"] = "/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n flex: none;\n padding: 0 2px;\n}\n\n.toolbar-shadow {\n position: relative;\n white-space: nowrap;\n height: 26px;\n overflow: hidden;\n z-index: 12;\n display: flex;\n flex: none;\n align-items: center;\n}\n\n.toolbar-shadow.vertical {\n flex-direction: column;\n height: auto;\n width: 26px;\n}\n\n.toolbar-shadow.floating {\n flex-direction: column;\n height: auto;\n background-color: white;\n border: 1px solid #ccc;\n margin-top: -1px;\n width: 26px;\n left: -2px;\n}\n\n.toolbar-item {\n position: relative;\n display: flex;\n background-color: transparent;\n flex: none;\n align-items: center;\n justify-content: center;\n padding: 0;\n height: 26px;\n border: none;\n color: #5a5a5a;\n}\n\n.toolbar-text {\n white-space: nowrap;\n overflow: hidden;\n margin-left: 6px;\n -webkit-user-select: text;\n}\n\n.toolbar-item:active {\n position: relative;\n z-index: 200;\n}\n\n.toolbar-item:hover .toolbar-button-text {\n color: #333;\n}\n\n.toolbar-item .toolbar-button-text {\n font-weight: bold;\n color: #5a5a5a;\n}\n\n.long-click-glyph {\n background-color: #595959;\n -webkit-mask-image: url(Images/toolbarButtonGlyphs.png);\n -webkit-mask-position: -288px -48px;\n -webkit-mask-size: 352px 144px;\n z-index: 1;\n width: 32px;\n height: 26px;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.long-click-glyph {\n -webkit-mask-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\nbutton.toolbar-item {\n width: 26px;\n}\n\nbutton.toolbar-item.toggled-on .glyph {\n background-color: rgb(66, 129, 235) !important;\n}\n\nbutton.toolbar-item:enabled:hover .glyph {\n background-color: #333;\n}\n\n.toolbar-counter:hover,\n.toolbar-item.checkbox:hover {\n color: #333;\n}\n\nbutton.toolbar-item:active .glyph {\n background-color: #5a5a5a !important;\n}\n\nbutton.toolbar-item:disabled {\n background-position: 0 0 !important;\n}\n\nbutton.toolbar-item:disabled .glyph {\n opacity: 0.5 !important;\n}\n\nbutton.toolbar-item.extension {\n background-image: none;\n}\n\n.toolbar-select-container {\n display: inline-flex;\n flex-shrink: 0;\n margin-right: 6px;\n}\n\n.toolbar-select-arrow {\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n opacity: 0.7;\n width: 12px;\n height: 12px;\n background-position: -18px -96px;\n display: inline-block;\n pointer-events: none;\n margin: auto 0;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.toolbar-select-arrow {\n background-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\ninput.toolbar-item {\n width: 200px;\n height: 20px;\n padding: 3px;\n margin: 1px 3px;\n background-color: white;\n border: solid 1px rgb(216, 216, 216);\n}\n\ninput.toolbar-item:focus,\ninput.toolbar-item:hover {\n border: solid 1px rgb(202, 202, 202);\n}\n\nselect.toolbar-item {\n min-width: 48px;\n color: rgb(48, 48, 48);\n text-shadow: rgba(255, 255, 255, 0.75) 0 1px 0;\n -webkit-appearance: none;\n border: 0;\n border-radius: 0;\n padding: 0 15px 0 5px;\n margin-right: -10px;\n position: relative;\n line-height: 22px;\n}\n\n.toolbar-item.checkbox {\n padding: 0 5px 0 2px;\n}\n\n.toolbar-item > .glyph {\n -webkit-mask-image: url(Images/toolbarButtonGlyphs.png);\n -webkit-mask-size: 352px 144px;\n background-color: #5a5a5a;\n z-index: 1;\n width: 32px;\n height: 24px;\n}\n\n.toolbar-item > .glyph {\n position: relative;\n left: -3px;\n}\n\n.toolbar-item > .long-click-glyph {\n left: -5px;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.toolbar-item > .glyph {\n -webkit-mask-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.toolbar-item.emulate-active {\n background-color: rgb(163,163,163);\n}\n\n.toolbar-counter {\n cursor: pointer;\n padding: 0 2px;\n min-width: 26px;\n}\n\n.toolbar-counter-item {\n margin-left: 6px;\n}\n\n.toolbar-counter-item label {\n cursor: inherit;\n}\n\n.toolbar-counter-item.toolbar-counter-item-first {\n margin-left: 0;\n}\n\n.toolbar-counter-item > div {\n margin-right: 2px;\n}\n\n.toolbar-divider {\n background-color: #ccc;\n width: 1px;\n margin: 2px 4px;\n height: 17px;\n}\n\n.toolbar-group-label {\n margin-left: 5px;\n margin-right: 3px;\n color: #888;\n}\n\n/* Predefined items */\n\n.dock-toolbar-item.toggled-undocked .glyph {\n -webkit-mask-position: 0 -48px;\n}\n\n.dock-toolbar-item.toggled-bottom .glyph {\n -webkit-mask-position: -32px -24px;\n}\n\n.dock-toolbar-item.toggled-right .glyph {\n -webkit-mask-position: -256px -48px;\n}\n\n.dock-toolbar-item.toggled-left .glyph {\n -webkit-mask-position: -32px -120px;\n}\n\n.settings-toolbar-item .glyph {\n -webkit-mask-position: -160px -24px;\n}\n\n.node-search-toolbar-item .glyph {\n -webkit-mask-position: -224px -24px;\n}\n\n.emulation-toolbar-item .glyph {\n -webkit-mask-position: -160px 1px;\n}\n\n.emulation-toolbar-item.warning::after {\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n width: 10px;\n height: 12px;\n content: \"\";\n position: absolute;\n right: 3px;\n bottom: 2px;\n background-position: -202px -107px;\n z-index: 1;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.emulation-toolbar-item.warning::before {\n background-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.delete-toolbar-item .glyph {\n -webkit-mask-position: -128px 0;\n}\n\n.clear-toolbar-item .glyph {\n -webkit-mask-position: -64px 0;\n}\n\n.refresh-toolbar-item .glyph {\n -webkit-mask-position: 0 0;\n}\n\n.focus-toolbar-item .glyph {\n -webkit-mask-position: -96px 0;\n}\n\n.console-toolbar-item .glyph {\n -webkit-mask-position: -64px -24px;\n}\n\n.large-list-toolbar-item .glyph {\n -webkit-mask-position: -224px 0;\n}\n\n.screencast-toolbar-item .glyph {\n -webkit-mask-position: -160px 0;\n}\n\n.record-toolbar-item .glyph {\n -webkit-mask-position: -288px 0;\n}\n\nbutton.record-toolbar-item.toggled-on .glyph {\n -webkit-mask-position: -288px -24px;\n background-color: rgb(216, 0, 0) !important;\n}\n\n.camera-toolbar-item .glyph {\n -webkit-mask-position: -96px -24px;\n}\n\n.last-step-toolbar-item .glyph {\n -webkit-mask-position: 0 -72px;\n}\n\n.first-step-toolbar-item .glyph {\n -webkit-mask-position: 0 -72px;\n transform: rotate(180deg);\n top: 0;\n bottom: 0;\n}\n\n.step-in-toolbar-item .glyph {\n -webkit-mask-position: -64px -72px;\n}\n\n.step-out-toolbar-item .glyph {\n -webkit-mask-position: -96px -72px;\n}\n\n.step-over-toolbar-item .glyph {\n -webkit-mask-position: -128px -72px;\n}\n\n.step-backwards-toolbar-item .glyph {\n -webkit-mask-position: -128px -72px;\n transform: scaleX(-1);\n}\n\n.play-toolbar-item .glyph {\n -webkit-mask-position: -64px -48px;\n}\n\n.play-backwards-toolbar-item .glyph {\n -webkit-mask-position: -64px -48px;\n transform: scaleX(-1);\n}\n\n.pause-on-exceptions-toolbar-item .glyph {\n -webkit-mask-position: -256px 0;\n}\n\n.pause-on-exceptions-toolbar-item.toggled-on .glyph {\n background-color: rgb(66, 129, 235);\n}\n\n.pause-toolbar-item .glyph {\n -webkit-mask-position: -32px -72px;\n}\n\n.pause-toolbar-item.toggled-on .glyph {\n -webkit-mask-position: 0 -72px;\n}\n\n.breakpoint-toolbar-item.toggled-on .glyph {\n -webkit-mask-position: -32px 0;\n}\n\n.breakpoint-toolbar-item .glyph {\n -webkit-mask-position: 0 -24px;\n}\n\n.format-toolbar-item .glyph {\n -webkit-mask-position: -256px -24px;\n}\n\n.format-toolbar-item.toggled .glyph {\n background-color: rgb(66, 129, 235);\n}\n\n.garbage-collect-toolbar-item .glyph {\n -webkit-mask-position: -128px -24px;\n}\n\n.histogram-toolbar-item .glyph {\n -webkit-mask-position: -160px -48px;\n}\n\n.flame-chart-toolbar-item .glyph {\n -webkit-mask-position: -192px -48px;\n}\n\n.filter-toolbar-item > .glyph {\n -webkit-mask-position: -32px -48px;\n}\n\n.filter-toolbar-item.toggled-shown .glyph {\n background-color: rgb(66, 129, 235) !important;\n}\n\n.filter-toolbar-item.toggled-shown {\n background-color: #f3f3f3;\n}\n\n.filter-toolbar-item.toggled-active .glyph {\n background-color: rgb(216, 0, 0);\n}\n\n.waterfall-toolbar-item .glyph {\n -webkit-mask-position: -128px -48px;\n}\n\n.pan-toolbar-item .glyph {\n -webkit-mask-position: -98px -120px;\n}\n\n.center-toolbar-item .glyph {\n -webkit-mask-position: -128px -120px;\n}\n\n.rotate-toolbar-item .glyph {\n -webkit-mask-position: -160px -120px;\n}\n\n.pin-toolbar-item .glyph {\n -webkit-mask-position: -256px -120px;\n}\n\n.pin-toolbar-item.toggled-on,\n.animation-toolbar-item.toggled-on {\n background-color: #f3f3f3;\n}\n\n.animation-toolbar-item .glyph {\n -webkit-mask-position: -192px -120px;\n}\n\n.eyedropper-toolbar-item .glyph {\n -webkit-mask-position: -288px -120px;\n}\n\n.add-toolbar-item .glyph {\n -webkit-mask-position: -224px -120px;\n}\n\n.pause-outline-toolbar-item .glyph {\n -webkit-mask-position: -320px 0px;\n}\n\n.replay-outline-toolbar-item .glyph {\n -webkit-mask-position: -320px -24px;\n}\n\n.play-outline-toolbar-item .glyph {\n -webkit-mask-position: -320px -48px;\n}\n\n.case-sensitive-search-toolbar-item.toggled-on .toolbar-button-text {\n color: rgb(94, 146, 233);\n}\n\n.regex-search-toolbar-item.toggled-on {\n color: rgb(66, 129, 235);\n}\n\n.regex-search-toolbar-item.toggled-on .toolbar-button-text {\n color: rgb(94, 146, 233);\n}\n\n.playback-rate-button.toggled-on > .toolbar-button-text {\n color: rgb(66, 129, 235);\n}\n\nbutton.playback-rate-button {\n width: auto;\n margin-right: 10px;\n}\n\n/*# sourceURL=ui/toolbar.css */";Runtime.cachedResources["ui/suggestBox.css"] = "/*\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n:host {\n position: absolute;\n background-color: transparent;\n z-index: 1000;\n pointer-events: none;\n overflow: hidden;\n display: flex;\n flex-direction: row;\n}\n\n.suggest-box-left-spacer {\n flex: 0 1 auto;\n}\n\n.suggest-box-horizontal {\n display: flex;\n flex-direction: column;\n flex: 0 0 auto;\n max-width: 300px;\n}\n\n.suggest-box-top-spacer {\n flex: auto;\n}\n\n:host(.under-anchor) .suggest-box-top-spacer,\n:host(:not(.under-anchor)) .suggest-box-bottom-spacer {\n flex: 0 0 auto;\n}\n\n.suggest-box {\n background-color: #FFFFFF;\n border: 1px solid rgb(66%, 66%, 66%);\n pointer-events: auto;\n margin-left: -3px;\n overflow-x: hidden;\n overflow-y: auto;\n display: flex;\n flex-direction: column;\n flex: 0 0 auto;\n border-radius: 5px 5px 5px 0;\n}\n\n:host(.under-anchor) .suggest-box {\n border-radius: 0 5px 5px 5px;\n}\n\n.suggest-box .suggest-box-content-item {\n padding: 1px;\n margin: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n border: 1px solid transparent;\n flex: 0 0 auto;\n padding-right: 0;\n white-space: nowrap;\n}\n\n.suggest-box .suggest-box-content-item .prefix {\n font-weight: bold;\n}\n\n.suggest-box .suggest-box-content-item .spacer {\n display: inline-block;\n width: 20px;\n}\n\n.suggest-box .suggest-box-content-item.selected {\n background-color: rgba(56, 121, 217, 0.1);\n}\n\n.suggest-box .suggest-box-content-item:hover:not(.selected) {\n border: 1px solid rgb(204, 204, 204);\n}\n\n/*# sourceURL=ui/suggestBox.css */";Runtime.cachedResources["ui/tabbedPane.css"] = "/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n * Copyright (C) 2011 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC.\n * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.tabbed-pane {\n flex: auto;\n overflow: hidden;\n}\n\n.tabbed-pane-content {\n position: relative;\n overflow: auto;\n flex: auto;\n display: flex;\n flex-direction: column;\n}\n\n.tabbed-pane-content.has-no-tabs {\n background-color: lightgray;\n}\n\n.tabbed-pane-placeholder {\n font-size: 14px;\n text-align: center;\n margin-top: 20px;\n text-shadow: rgba(255, 255, 255, 0.75) 0 1px 0;\n}\n\n.tabbed-pane-header {\n display: flex;\n flex: 0 0 27px;\n border-bottom: 1px solid #ccc;\n overflow: hidden;\n width: 100%;\n background-color: #f3f3f3;\n}\n\n.tabbed-pane-header-contents {\n flex: auto;\n pointer-events: none;\n margin-left: 5px;\n position: relative;\n}\n\n.tabbed-pane-header-contents > * {\n pointer-events: initial;\n}\n\n.tabbed-pane-header-tab-icon {\n margin-right: 2px;\n}\n\n.tabbed-pane-header-tab {\n float: left;\n margin-top: 2px;\n padding: 2px 4px 2px 4px;\n height: 24px;\n border: 1px solid transparent;\n border-bottom: none;\n line-height: 15px;\n white-space: nowrap;\n cursor: default;\n display: flex;\n align-items: center;\n color: #5a5a5a;\n}\n\n.tabbed-pane-header-tab:hover {\n color: #333;\n}\n\n.tabbed-pane-header-tab-title {\n text-overflow: ellipsis;\n overflow: hidden;\n}\n\n.tabbed-pane-header-tab.measuring {\n visibility: hidden;\n}\n\n.tabbed-pane-header-tab.selected {\n border: 1px solid #ccc;\n border-bottom: none;\n color: #333;\n}\n\n.tabbed-pane-header-tab.selected {\n background: white;\n border-top-color: #ccc;\n}\n\n.tabbed-pane-header-tab .tabbed-pane-close-button {\n display: inline-block;\n position: relative;\n top: 2px;\n left: 1px;\n margin-left: 2px;\n margin-top: -3px;\n visibility: hidden;\n}\n\n.tabbed-pane-header-tab:hover .tabbed-pane-close-button,\n.tabbed-pane-header-tab.selected .tabbed-pane-close-button {\n visibility: visible;\n}\n\n.tabbed-pane-header-tabs-drop-down-container {\n float: left;\n position: relative;\n vertical-align: bottom;\n line-height: 24px;\n opacity: 0.8;\n color: inherit;\n font-size: 133%;\n padding: 0 7px;\n cursor: default;\n height: 25px;\n}\n\n.tabbed-pane-header-tabs-drop-down-container:hover {\n background-color: rgba(105, 105, 105, 0.1);\n}\n\n.tabbed-pane-header-tabs-drop-down-container.measuring {\n visibility: hidden;\n}\n\n.tabbed-pane-header-tabs-drop-down-container:hover {\n opacity: 1.0;\n}\n\n.tabbed-pane-header-tabs-drop-down-container:active {\n opacity: 0.8;\n}\n\n/* Web page style */\n\n.tabbed-pane-shadow.vertical-tab-layout {\n flex-direction: row !important;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header {\n background-color: transparent;\n border: none transparent !important;\n width: auto;\n flex: 0 0 auto;\n flex-direction: column;\n padding-top: 10px;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-content {\n padding: 10px 10px 10px 0;\n overflow-x: hidden;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-contents {\n margin: 0;\n flex: none;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tabs {\n display: flex;\n flex-direction: column;\n width: 120px;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab {\n background-color: transparent;\n border: none transparent;\n font-weight: normal;\n text-shadow: none;\n color: #777;\n height: 26px;\n padding-left: 10px;\n border-left: 6px solid transparent;\n margin: 0;\n display: flex;\n align-items: center;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab:not(.selected) {\n cursor: pointer !important;\n}\n\n.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab.selected {\n color: inherit;\n border: none transparent;\n border-left: 6px solid #666;\n}\n\n.tabbed-pane-tab-slider {\n height: 2px;\n position: absolute;\n bottom: -1px;\n background-color: #3E82F7;\n left: 0;\n z-index: 50;\n transform-origin: 0 0;\n transition: transform 150ms cubic-bezier(0, 0, 0.2, 1);\n visibility: hidden;\n}\n\n.tabbed-pane-tab-slider.enabled {\n visibility: visible;\n}\n\n.tabbed-pane-header.tabbed-pane-no-header-background {\n background-color: transparent;\n}\n\n/*# sourceURL=ui/tabbedPane.css */";Runtime.cachedResources["ui/textButton.css"] = "/*\n * Copyright (c) 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n background-image: linear-gradient(hsl(0, 0%, 93%), hsl(0, 0%, 93%) 38%, hsl(0, 0%, 87%));\n border: 1px solid hsla(0, 0%, 0%, 0.25);\n border-radius: 2px;\n box-shadow: 0 1px 0 hsla(0, 0%, 0%, 0.08), inset 0 1px 2px hsla(0, 100%, 100%, 0.75);\n color: hsl(0, 0%, 27%);\n font-size: 12px;\n margin: 0 1px 0 0;\n text-shadow: 0 1px 0 hsl(0, 0%, 94%);\n min-height: 2em !important;\n padding-left: 10px;\n padding-right: 10px;\n -webkit-user-select: none;\n flex: none;\n}\n\n:host-context(body.inactive),\n:host(:disabled) {\n background-image: linear-gradient(#f1f1f1, #f1f1f1 38%, #e6e6e6);\n border-color: rgba(80, 80, 80, 0.2);\n box-shadow: 0 1px 0 rgba(80, 80, 80, 0.08), inset 0 1px 2px rgba(255, 255, 255, 0.75);\n color: #aaa;\n}\n\n:host(:not(:disabled):hover) {\n background-image: linear-gradient(hsl(0, 0%, 94%), hsl(0, 0%, 94%) 38%, hsl(0, 0%, 88%));\n border-color: hsla(0, 0%, 0%, 0.3);\n box-shadow: 0 1px 0 hsla(0, 0%, 0%, 0.12), inset 0 1px 2px hsla(0, 100%, 100%, 0.95);\n color: hsl(0, 0%, 0%);\n}\n\n:host(:not(:disabled):active) {\n background-image: linear-gradient(hsl(0, 0%, 91%), hsl(0, 0%, 91%) 38%, hsl(0, 0%, 84%));\n box-shadow: none;\n text-shadow: none;\n}\n\n:host(:not(:disabled):focus) {\n -webkit-transition: border-color 200ms;\n border-color: rgb(77, 144, 254);\n outline: none;\n}\n\n/*# sourceURL=ui/textButton.css */";Runtime.cachedResources["ui/textPrompt.css"] = "/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.text-prompt-editing {\n -webkit-user-select: text;\n box-shadow: rgba(0, 0, 0, .5) 3px 3px 4px;\n outline: 1px solid rgb(66%, 66%, 66%) !important;\n background-color: white;\n -webkit-user-modify: read-write-plaintext-only;\n text-overflow: clip !important;\n padding-left: 2px;\n margin-left: -2px;\n padding-right: 2px;\n margin-right: -2px;\n margin-bottom: -1px;\n padding-bottom: 1px;\n opacity: 1.0 !important;\n}\n\n.text-prompt-editing,\n.text-prompt-editing ::content * {\n color: #222 !important;\n text-decoration: none !important;\n -webkit-user-modify: read-write-plaintext-only;\n}\n\n::content .auto-complete-text,\n.text-prompt-editing ::content .auto-complete-text {\n color: rgb(128, 128, 128) !important;\n -webkit-user-select: none;\n -webkit-user-modify: read-only;\n}\n\n.text-prompt-editing ::content br {\n display: none;\n}\n\n/*# sourceURL=ui/textPrompt.css */";Runtime.cachedResources["ui/treeoutline.css"] = "/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tree-outline {\n padding: 0 0 4px 4px;\n margin: 0;\n z-index: 0;\n position: relative;\n}\n\n.tree-outline li.hovered:not(.selected) .selection {\n display: block;\n left: 3px;\n right: 3px;\n background-color: rgba(56, 121, 217, 0.1);\n border-radius: 5px;\n}\n\n.tree-outline li .selection {\n display: none;\n position: absolute;\n left: 0;\n right: 0;\n height: 17px;\n z-index: -1;\n margin-top: -1px;\n}\n\n.tree-outline li.selected .selection {\n display: block;\n background-color: #ddd;\n}\n\n.tree-outline li.in-clipboard .highlight {\n outline: 1px dotted darkgrey;\n}\n\n.tree-outline li.elements-drag-over .selection {\n display: block;\n margin-top: -2px;\n border-top: 2px solid rgb(56, 121, 217);\n}\n\nol.tree-outline:focus li.selected .selection {\n background-color: rgb(56, 121, 217);\n}\n\nol.tree-outline:focus li.parent.selected::before {\n background-color: white;\n}\n\nol.tree-outline,\n.tree-outline ol {\n list-style-type: none;\n}\n\n.tree-outline-no-padding {\n padding: 0;\n}\n\n.tree-outline ol {\n padding-left: 12px;\n}\n\n.tree-outline li {\n text-overflow: ellipsis;\n white-space: nowrap;\n overflow: hidden;\n min-height: 17px;\n padding-top: 2px;\n}\n\nol.tree-outline:focus li.selected {\n color: white;\n}\n\nol.tree-outline:focus li.selected * {\n color: inherit;\n}\n\n.tree-outline li::before {\n float: left;\n -webkit-user-select: none;\n -webkit-mask-image: url(Images/toolbarButtonGlyphs.png);\n -webkit-mask-size: 352px 144px;\n content: \"a\";\n color: transparent;\n text-shadow: none;\n position: relative;\n margin-right: 1px;\n top: 1px;\n width: 10px;\n height: 10px;\n}\n\n.tree-outline li:not(.parent)::before {\n background-color: transparent;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.tree-outline li::before {\n -webkit-mask-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.tree-outline li::before {\n -webkit-mask-position: -4px -96px;\n background-color: rgb(110, 110, 110);\n}\n\n.tree-outline li.parent.expanded::before {\n -webkit-mask-position: -20px -96px;\n}\n\n.tree-outline ol.children {\n display: none;\n}\n\n.tree-outline ol.children.expanded {\n display: block;\n}\n\n/*# sourceURL=ui/treeoutline.css */";Runtime.cachedResources["components/breakpointsList.css"] = "/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.sidebar-pane .breakpoint-condition {\n display: block;\n margin-top: 4px;\n margin-bottom: 4px;\n margin-left: 23px;\n margin-right: 8px;\n}\n\n.breakpoint-list .editing.being-edited {\n overflow: hidden;\n white-space: nowrap;\n}\n\n#breakpoint-condition-input {\n display: block;\n margin-left: 0;\n margin-right: 0;\n outline: none !important;\n border: 1px solid rgb(66%, 66%, 66%);\n}\n\nol.breakpoint-list {\n -webkit-padding-start: 0;\n list-style: none;\n margin: 0;\n padding-bottom: 3px;\n}\n\n.breakpoints-list-deactivated {\n background-color: #eee;\n opacity: 0.3;\n}\n\n.breakpoint-list li {\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n padding: 2px 0;\n}\n\n.breakpoint-list li:hover {\n background-color: #eee;\n}\n\n.breakpoint-list .source-text {\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n margin: 2px 0 0 20px;\n}\n\n.sidebar-pane .breakpoint-hit {\n background-color: rgb(255, 255, 194);\n}\n\nli.breakpoint-hit .breakpoint-hit-marker {\n background-color: rgb(255, 255, 194);\n height: 18px;\n left: 0;\n margin-top: -16px;\n position: absolute;\n right: 0;\n z-index: -1;\n}\n\n.event-listener-breakpoints {\n margin-top: 0;\n padding: 2px 6px;\n list-style: none;\n min-height: 18px;\n}\n\n.event-listener-breakpoints ol {\n display: none;\n margin: 0;\n -webkit-padding-start: 12px;\n list-style: none;\n}\n\n.event-listener-breakpoints ol.expanded {\n display: block;\n}\n\n.event-listener-breakpoints li {\n margin-left: 12px;\n text-overflow: ellipsis;\n -webkit-user-select: text;\n cursor: default;\n}\n\n.event-listener-breakpoints li.parent {\n margin-left: 1px;\n}\n\n.event-listener-breakpoints li.parent::before {\n -webkit-user-select: none;\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n opacity: 0.5;\n content: \"a\";\n width: 8px;\n float: left;\n margin: 2px 2px 0 -2px;\n color: transparent;\n text-shadow: none;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.event-listener-breakpoints li.parent::before {\n background-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.event-listener-breakpoints li.parent::before {\n background-position: -4px -96px;\n}\n\n.event-listener-breakpoints li.parent.expanded::before {\n background-position: -20px -96px;\n}\n\n.event-listener-breakpoints .children li {\n margin-left: 12px;\n}\n\n.async-operations li > label {\n float: left;\n}\n\n.async-operations li > div {\n float: right;\n margin: 2px 3px 0 2px;\n}\n\n.dom-breakpoints-list > li {\n display: flex;\n}\n\n.dom-breakpoints-list .dom-breakpoint > div {\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n/*# sourceURL=components/breakpointsList.css */";Runtime.cachedResources["components/customPreviewSection.css"] = "/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.custom-expandable-section {\n display: inline-flex;\n flex-direction: column;\n}\n\n.custom-expandable-section-header::before {\n -webkit-user-select: none;\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n opacity: 0.5;\n content: \"a\";\n width: 8px;\n margin-right: 4px;\n padding-right: 2px;\n color: transparent;\n text-shadow: none;\n}\n\n.custom-expandable-section-header::before {\n background-position: -4px -96px;\n}\n\n.custom-expandable-section-header.expanded::before {\n background-position: -20px -96px;\n}\n\n.custom-expandable-section-standard-section {\n display: inline-flex;\n}\n/*# sourceURL=components/customPreviewSection.css */";Runtime.cachedResources["components/eventListenersView.css"] = "/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.event-listener-tree li {\n padding: 2px 0 0 5px;\n}\n\n.event-listener-tree > li {\n border-top: 1px solid #f0f0f0;\n}\n\n.event-listener-tree > li:first-of-type {\n border-top: none;\n}\n\n.event-listener-tree {\n padding-left: 0 !important;\n padding-right: 3px;\n}\n\n.event-listener-tree li.parent::before {\n top: 0 !important;\n}\n\n.event-listener-tree .name {\n color: rgb(136, 19, 145);\n}\n\n.event-listener-tree-subtitle {\n float: right;\n}\n\n/*# sourceURL=components/eventListenersView.css */";Runtime.cachedResources["components/domUtils.css"] = "/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n:host {\n display: inline;\n}\n\n.node-link {\n text-decoration: underline;\n cursor: pointer;\n display: inline;\n}\n\n.stack-preview-async-description {\n padding: 3px 0 1px;\n font-style: italic;\n}\n\n.stack-preview-container .webkit-html-blackbox-link {\n opacity: 0.6;\n}\n\n.stack-preview-container > tr {\n height: 17px;\n}\n\n/*# sourceURL=components/domUtils.css */";Runtime.cachedResources["components/inspectorViewTabbedPane.css"] = "/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.tabbed-pane-header {\n background-color: #f3f3f3;\n flex: 0 0 27px;\n overflow: visible;\n}\n\n.tabbed-pane-header-tab,\n.tabbed-pane-header-tab.selected {\n height: 26px;\n margin: 0;\n background: none;\n border: none;\n border-left: 2px solid transparent;\n border-right: 2px solid transparent;\n padding: 0 6px;\n}\n\n.tabbed-pane-header-tab {\n color: #5a5a5a;\n}\n\n.tabbed-pane-header-tab.selected {\n color: #333;\n border-width: 0 2px 0 2px;\n -webkit-border-image: url(Images/toolbarItemSelected.png) 0 2 0 2;\n}\n\n/*# sourceURL=components/inspectorViewTabbedPane.css */";Runtime.cachedResources["components/objectPropertiesSection.css"] = "/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.object-properties-section .name {\n color: rgb(136, 19, 145);\n flex-shrink: 0;\n}\n\n.object-properties-section-separator {\n flex-shrink: 0;\n}\n\n.object-properties-section-dimmed {\n opacity: 0.6;\n}\n\n.object-properties-section {\n padding: 0 0 0px 0px;\n color: rgb(33,33,33) !important;\n}\n\n.object-properties-section li {\n min-height: inherit;\n line-height: 12px;\n -webkit-user-select: text;\n}\n\n.object-properties-section li::before {\n top: -1px;\n}\n\n.object-properties-section li.editing-sub-part {\n padding: 3px 6px 8px;\n margin: -1px -6px -8px -6px;\n text-overflow: clip;\n}\n\n.object-properties-section li.editing {\n margin-left: 10px;\n text-overflow: clip;\n}\n\n.tree-outline ol.title-less-mode {\n padding-left: 0px;\n}\n\n\n/*# sourceURL=components/objectPropertiesSection.css */";Runtime.cachedResources["components/objectValue.css"] = "/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.object-value-scientific-notation-exponent {\n flex-shrink: 0;\n}\n\n.object-value-scientific-notation-mantissa {\n overflow: hidden;\n text-overflow: ellipsis;\n flex-shrink: 1;\n min-width: 1ex;\n}\n\n.object-value-scientific-notation-number {\n display: flex !important;\n}\n\n.object-value-node:hover {\n background-color: rgba(56, 121, 217, 0.1);\n}\n\n.object-value-function::before {\n content: \"function\";\n color: rgb(170, 13, 145);\n padding-right: 5px;\n}\n\n.object-value-function {\n font-style: italic;\n}\n\n.object-value-function.linkified:hover {\n background-color: rgba(0, 0, 0, 0.1);\n cursor: pointer;\n}\n\n.object-value-object,\n.object-value-map,\n.object-value-set,\n.object-value-iterator,\n.object-value-generator,\n.object-value-node,\n.object-value-array {\n position: relative;\n vertical-align: top;\n color: inherit;\n display: inline-block;\n}\n\n.object-value-number,\n.object-value-boolean {\n color: rgb(28, 0, 207);\n}\n\n.object-value-string,\n.object-value-regexp,\n.object-value-symbol {\n color: rgb(196, 26, 22);\n white-space: nowrap;\n unicode-bidi: -webkit-isolate;\n}\n\n.object-value-node {\n color: rgb(136, 18, 128);\n}\n\n.object-value-null,\n.object-value-undefined {\n color: rgb(128, 128, 128);\n}\n\n.object-value {\n text-overflow: ellipsis;\n overflow: hidden;\n -webkit-user-select: text;\n}\n\n.object-value-calculate-value-button:hover {\n text-decoration: underline;\n}\n\n.object-value-object .section,\n.object-formatted-map .section,\n.object-value-set .section,\n.object-value-iterator .section,\n.object-value-generator .section,\n.object-value-node .section,\n.object-value-array .section {\n position: static;\n}\n.object-value-object .section > .header::before {\n margin-top: 0;\n}\n\n\n.object-value-object .properties-tree,\n.object-value-map .properties-tree,\n.object-value-set .properties-tree,\n.object-value-iterator .properties-tree,\n.object-value-generator .properties-tree,\n.object-value-node .properties-tree {\n padding-left: 0 !important;\n}\n\n.object-value-preview-node,\n.section .object-value-node {\n color: rgb(136, 18, 128);\n}\n\n.object-properties-section-custom-section {\n display: inline-flex;\n flex-direction: column;\n}\n/*# sourceURL=components/objectValue.css */";Runtime.cachedResources["emulation/accelerometer.css"] = "/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.accelerometer-stage {\n -webkit-perspective: 700px;\n -webkit-perspective-origin: 50% 50%;\n width: 200px;\n height: 130px;\n}\n\n.accelerometer-box {\n pointer-events:none;\n margin-top: -54px;\n margin-left: -40px;\n position: absolute;\n top: 50%;\n left: 50%;\n width: 80px;\n height: 108px;\n -webkit-transform-style: preserve-3d;\n}\n\n.accelerometer-box section {\n margin-top: -54px;\n margin-left: -40px;\n position: absolute;\n display: block;\n overflow: hidden;\n top: 50%;\n left: 50%;\n -webkit-transform-style: flat;\n -webkit-box-shadow: inset 0 0 15px rgba(0, 0, 0, 0.7);\n}\n\n.accelerometer-box .front {\n border:15px solid black;\n width: 80px;\n height: 107px;\n background-color: gray;\n transform: translate3d(0, 0, 10px);\n}\n\n.accelerometer-box .back {\n width: 80px;\n height: 107px;\n background-color: black;\n transform: rotateY(-180deg) translate3d(0, 0, 10px);\n}\n\n.accelerometer-box .top {\n overflow: hidden;\n width: 80px;\n height: 20px;\n background-color: #75CE89;\n transform: rotateX(-90deg) translate3d(0, 0, -10px);\n}\n\n.accelerometer-box .bottom {\n overflow: hidden;\n width: 80px;\n height: 20px;\n background-color: #865C6C;\n transform: rotateX(90deg) translate3d(0, 0, -97px);\n}\n\n.accelerometer-box .left {\n width: 20px;\n height: 107px;\n background-color: #7992CB;\n transform: rotateY(90deg) translate3d(0, 0, 70px);\n}\n\n.accelerometer-box .right {\n width: 20px;\n height: 107px;\n background-color: #7992CB;\n transform: rotateY(-90deg) translate3d(0, 0, 10px);\n}\n\n.accelerometer-axis-input-container {\n margin-bottom: 10px;\n}\n\n.accelerometer-inputs-cell {\n vertical-align: top;\n}\n\n.accelerometer-reset-button {\n width: 100%;\n}\n/*# sourceURL=emulation/accelerometer.css */";Runtime.cachedResources["emulation/devicesSettingsTab.css"] = "/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.devices-settings-tab .settings-tab.help-content {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n height: 100%;\n margin: 0;\n}\n\n.devices-settings-tab .devices-title {\n font-size: 120%;\n color: #222;\n flex: none;\n}\n\n.devices-settings-tab .devices-button-row {\n flex: none;\n display: flex;\n}\n\n.devices-settings-tab .devices-button-row button {\n margin-right: 10px;\n min-width: 120px;\n flex: none;\n}\n\n.devices-settings-tab .devices-list {\n width: 350px;\n overflow-y: auto;\n margin: 10px 0;\n border: 1px solid rgb(231, 231, 231);\n flex: auto 0 1;\n}\n\n.devices-settings-tab .devices-custom-separator {\n background: rgb(231, 231, 231);\n height: 1px;\n}\n\n.devices-settings-tab .devices-list-item {\n padding: 3px 0 3px 10px;\n height: 30px;\n display: flex;\n align-items: center;\n cursor: pointer;\n}\n\n.devices-settings-tab .devices-list-item:hover {\n background: hsl(0, 0%, 85%);\n}\n\n.devices-settings-tab .devices-list-checkbox {\n height: 12px;\n width: 12px;\n margin: 3px 5px 2px 2px;\n flex: none;\n pointer-events: none;\n}\n\n.devices-settings-tab .devices-list-title {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n flex: auto;\n -webkit-user-select: none;\n color: #aaa;\n}\n\n.devices-settings-tab .device-list-item-show .devices-list-title {\n color: #222;\n}\n\n.devices-settings-tab .devices-list-remove,\n.devices-settings-tab .devices-list-edit {\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n width: 32px;\n height: 24px;\n opacity: 0.5;\n cursor: pointer;\n flex: none;\n visibility: hidden;\n}\n\n.devices-settings-tab .devices-list:not(.devices-list-editing) .devices-list-item:hover .devices-list-remove,\n.devices-settings-tab .devices-list-item:hover .devices-list-edit {\n visibility: visible;\n}\n\n.devices-settings-tab .devices-list-remove:hover,\n.devices-settings-tab .devices-list-edit:hover {\n opacity: 0.7;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.devices-settings-tab .devices-list-remove,\n.devices-settings-tab .devices-list-edit {\n background-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.devices-settings-tab .devices-list-remove {\n background-position: -128px -24px;\n}\n\n.devices-settings-tab .devices-list-edit {\n background-position: -224px -72px;\n}\n\n.devices-settings-tab .devices-edit-container {\n display: flex;\n flex-direction: row;\n align-items: flex-start;\n flex: none;\n padding: 10px 20px 0 10px;\n background: hsl(0, 0%, 95%);\n}\n\n.devices-settings-tab .devices-edit-checkbox {\n height: 12px;\n width: 12px;\n margin: 3px 5px 2px 2px;\n flex: none;\n cursor: pointer;\n}\n\n.devices-settings-tab .devices-edit-fields {\n flex: auto;\n display: flex;\n flex-direction: column;\n align-items: stretch;\n}\n\n.devices-settings-tab .devices-edit-fields input {\n margin-right: 10px;\n}\n\n.devices-settings-tab .devices-edit-fields input.error-input {\n outline: auto 2px red;\n background-color: white;\n}\n\n.devices-settings-tab .devices-edit-fields > * {\n flex: none;\n margin-bottom: 10px;\n}\n\n.devices-settings-tab .devices-edit-buttons > button {\n margin-right: 10px;\n}\n\n\n/*# sourceURL=emulation/devicesSettingsTab.css */";Runtime.cachedResources["emulation/responsiveDesignView.css"] = "/*\n * Copyright 2014 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.responsive-design {\n position: relative;\n background-color: rgb(0, 0, 0);\n overflow: hidden;\n}\n\n.responsive-design-view {\n overflow: hidden;\n}\n\n.responsive-design-canvas {\n pointer-events: none;\n}\n\n.responsive-design-sliders-container {\n position: absolute;\n overflow: visible;\n}\n\n.responsive-design-generic-outline-container {\n position: absolute;\n overflow: hidden;\n top: 0;\n left: 0;\n right: -19px;\n bottom: -19px;\n}\n\n.responsive-design-generic-outline {\n position: absolute;\n top: -10px;\n left: -10px;\n right: 5px;\n bottom: 5px;\n border-radius: 8px;\n background-color: rgb(51, 51, 51);\n box-shadow: rgb(20, 20, 20) 3px 3px 4px;\n}\n\n.responsive-design-slider-width {\n position: absolute;\n top: 0;\n bottom: 0;\n right: -14px;\n width: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.responsive-design-slider-height {\n position: absolute;\n left: 0;\n right: 0;\n bottom: -14px;\n height: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.responsive-design-slider-corner {\n position: absolute;\n right: -14px;\n width: 14px;\n bottom: -14px;\n height: 14px;\n}\n\n.responsive-design-thumb-handle {\n content: url(Images/toolbarResizerHorizontal.png);\n pointer-events: none;\n}\n\n.responsive-design-slider-height .responsive-design-thumb-handle {\n transform: rotate(90deg);\n}\n\n.responsive-design-page-container {\n background-color: #171717;\n}\n\n.responsive-design-page-scale-container {\n position: absolute !important;\n top: 0;\n right: 0;\n padding: 10px;\n background-color: rgba(0, 0, 0, 0.3);\n align-items: center;\n}\n\n.responsive-design-page-scale-label {\n display: block;\n height: 20px;\n margin: 0 4px;\n padding-top: 3px;\n color: white;\n cursor: default !important;\n}\n\n.responsive-design-page-scale-container .responsive-design-page-scale-button > .glyph {\n display: block;\n width: 18px;\n height: 18px;\n border: 1px solid transparent;\n border-radius: 2px;\n}\n\n.responsive-design-page-scale-container .responsive-design-page-scale-button:not(:disabled):hover {\n box-shadow: rgb(255, 255, 255) 0 0 3px;\n}\n\n.responsive-design-page-scale-container .responsive-design-page-scale-button {\n border: none;\n background-color: transparent;\n padding: 2px 0 0 0;\n}\n\n.responsive-design-page-scale-container .responsive-design-page-scale-button > .glyph {\n background-color: rgb(180, 180, 180);\n -webkit-mask-image: url(Images/responsiveDesign.png);\n -webkit-mask-size: 112px 16px;\n opacity: 1;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.responsive-design-page-scale-container .responsive-design-page-scale-button > .glyph {\n -webkit-mask-image: url(Images/responsiveDesign_2x.png);\n}\n} /* media */\n\n.responsive-design-page-scale-increase > .glyph {\n -webkit-mask-position: -80px 0;\n}\n\n.responsive-design-page-scale-decrease > .glyph {\n -webkit-mask-position: -96px 0;\n}\n\n/* Toolbar */\n\n.responsive-design-toolbar {\n display: flex;\n flex: none;\n background: linear-gradient(to bottom, rgb(83, 81, 81), rgb(59, 59, 59));\n color: rgb(255, 255, 255);\n overflow: hidden;\n border-bottom: 1px solid rgb(71, 71, 71);\n}\n\n.responsive-design-separator {\n flex: none;\n width: 3px;\n background-color: rgb(46, 46, 46);\n border-right: 1px solid rgb(75, 75, 75);\n}\n\n.responsive-design-section {\n display: flex;\n flex: none;\n flex-direction: column;\n white-space: nowrap;\n align-items: stretch;\n justify-content: flex-start;\n padding-top: 1px;\n}\n\n.responsive-design-section-decorator {\n height: 2px;\n margin-left: -2px;\n margin-right: -1px;\n position: relative;\n}\n\n.responsive-design-suite {\n display: flex;\n flex-direction: row;\n padding: 2px 11px;\n color: rgb(180, 180, 180);\n}\n\n.responsive-design-suite.responsive-design-suite-top {\n color: rgb(255, 255, 255);\n}\n\n.responsive-design-suite-separator {\n flex: none;\n width: 1px;\n background-color: rgb(43, 43, 43);\n margin: 0 6px;\n}\n\n.responsive-design-suite > div:not(.responsive-design-suite-separator) {\n flex: none;\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n height: 23px;\n overflow: hidden;\n}\n\n/* Toolbar controls */\n\n.responsive-design-toolbar fieldset,\n.responsive-design-toolbar p {\n margin: 0;\n border: 0;\n padding: 0;\n display: inline-block;\n}\n\n.responsive-design-toolbar .field-error-message {\n display: none;\n}\n\n.responsive-design-toolbar label {\n cursor: default !important;\n margin: 0 2px;\n}\n\n.responsive-design-toolbar input[type='text'] {\n text-align: left;\n background-color: transparent;\n border: none;\n margin: 0 1px 1px 0;\n padding: 3px 2px;\n}\n\n.responsive-design-toolbar input[type='text'].numeric {\n text-align: center;\n}\n\n.responsive-design-toolbar input:focus::-webkit-input-placeholder {\n color: transparent !important;\n}\n\n.responsive-design-toolbar fieldset:disabled input,\n.responsive-design-toolbar fieldset:disabled button {\n opacity: 0.7;\n}\n\n.responsive-design-toolbar input.error-input {\n color: red !important;\n text-decoration: line-through;\n}\n\n.responsive-design-toolbar select {\n height: 18px;\n background-color: rgb(87, 87, 87);\n border: 0;\n margin-left: 10px;\n line-height: 16px;\n}\n\n.responsive-design-toolbar input:focus {\n background-color: rgb(81, 81, 81);\n}\n\n/* Toolbar icons */\n\n.responsive-design-icon {\n background-color: rgb(180, 180, 180);\n -webkit-mask-image: url(Images/responsiveDesign.png);\n -webkit-mask-size: 112px 16px;\n}\n\n.responsive-design-icon {\n display: inline-block;\n width: 16px;\n height: 16px;\n position: relative;\n top: 3px;\n}\n\ndiv.responsive-design-icon:disabled {\n opacity: 1 !important;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.responsive-design-icon {\n -webkit-mask-image: url(Images/responsiveDesign_2x.png);\n}\n} /* media */\n\n.responsive-design-icon-resolution {\n -webkit-mask-position: 0 0;\n}\n\n.responsive-design-icon-dpr {\n -webkit-mask-position: -16px 0;\n}\n\n.responsive-design-icon-swap {\n background-color: rgb(255, 170, 0);\n -webkit-mask-position: -32px 0;\n -webkit-appearance: none;\n padding: 0;\n border: 0;\n}\n\n.responsive-design-icon-swap {\n margin-left: 1px;\n top: 4px;\n}\n\n.responsive-design-icon-swap:hover {\n background-color: rgb(255, 180, 0);\n}\n\n.responsive-design-icon-swap:active {\n opacity: 0.8;\n}\n\n/* Buttons section */\n\n.responsive-design-section-buttons {\n padding: 4px 0 0 0;\n background: rgb(17, 17, 17);\n}\n\n.responsive-design-more-button-container {\n flex: auto;\n display: flex;\n justify-content: flex-end;\n align-items: flex-end;\n overflow: hidden;\n}\n\n.responsive-design-more-button {\n -webkit-appearance: none;\n border: 0;\n background-color: transparent;\n color: white;\n opacity: 0.8;\n font-size: 16px;\n text-shadow: black 1px 1px;\n}\n\n.responsive-design-more-button:hover {\n opacity: 1;\n}\n\n.responsive-design-more-button:active {\n opacity: 0.8;\n}\n\n/* Device section */\n\n.responsive-design-section-device .responsive-design-section-decorator {\n background: linear-gradient(to bottom, rgb(255, 186, 68), rgb(255, 119, 0));\n margin-left: 0;\n}\n\n.responsive-design-section-device .device-select {\n width: 140px;\n}\n\n.responsive-design-section-device .mode-container {\n display: inline-block;\n width: 116px;\n padding: 0 10px;\n}\n\n.responsive-design-section-device .mode-select select {\n width: 82px;\n}\n\n.responsive-design-section-device .mode-select label {\n margin-left: 4px;\n color: rgb(255, 156, 0);\n position: relative;\n top: 1px;\n}\n\n.responsive-design-section-device input[type='text'],\n.responsive-design-section-device input[type='text']::-webkit-input-placeholder,\n.responsive-design-section-device select {\n color: rgb(255, 156, 0);\n}\n\n.responsive-design-section-device input[type='checkbox']:checked:after {\n background: rgb(255, 156, 0);\n}\n\n/* Network section */\n\n.responsive-design-section-network select {\n width: 145px;\n}\n\n.responsive-design-section-network input[type='text'] {\n width: 182px;\n margin-left: 5px;\n text-overflow: ellipsis;\n}\n\n.responsive-design-section-network input[type='text'],\n.responsive-design-section-network input[type='text']::-webkit-input-placeholder,\n.responsive-design-section-network select {\n color: rgb(65, 175, 255);\n}\n\n.responsive-design-section-network .responsive-design-section-decorator {\n background: linear-gradient(to bottom, rgb(77, 170, 243), rgb(0, 130, 255));\n}\n\n/* Warning message */\n\n.responsive-design-warning {\n position: absolute;\n left: 0;\n right: 0;\n top: 0;\n overflow: hidden;\n border-bottom: 1px solid rgb(187, 187, 187);\n}\n\n/* Media query inspector */\n\n.responsive-design-media-container {\n position: absolute;\n right: 0;\n top: 0;\n padding-bottom: 5px;\n overflow: hidden;\n}\n\n/* Media query bars */\n\n.media-inspector-marker-container {\n position: relative;\n height: 14px;\n margin: 2px 0;\n}\n\n.media-inspector-marker {\n position: absolute;\n top: 1px;\n bottom: 1px;\n white-space: nowrap;\n border-radius: 2px;\n}\n\n.media-inspector-marker-inactive {\n -webkit-filter: brightness(80%);\n}\n\n.media-inspector-marker:hover {\n top: -1px;\n bottom: -1px;\n -webkit-filter: brightness(115%) !important;\n}\n\n.media-inspector-marker-max-width {\n background: linear-gradient(to left, rgba(255, 255, 255, 0.27), rgba(0,0,0,0) 30px), linear-gradient(to bottom, rgb(72, 139, 249), rgb(26, 113, 233));\n border-radius: 0 2px 2px 0;\n border-right: 2px solid rgb(171, 207, 255);\n}\n\n.media-inspector-marker-min-max-width {\n background: linear-gradient(to right, rgba(255, 255, 255, 0.27), rgba(0,0,0,0) 30px), linear-gradient(to left, rgba(255, 255, 255, 0.27), rgba(0,0,0,0) 30px), linear-gradient(to bottom, rgb(112, 174, 7), rgb(3, 131, 0));\n border-radius: 2px;\n border-left: 2px solid rgb(80, 226, 40);\n border-right: 2px solid rgb(80, 226, 40);\n}\n\n.media-inspector-marker-min-max-width:hover {\n z-index: 1;\n}\n\n.media-inspector-marker-min-width {\n background: linear-gradient(to right, rgba(255, 255, 255, 0.27), rgba(0,0,0,0) 30px), linear-gradient(to bottom, rgb(222, 129, 30), rgb(204, 104, 31));\n border-radius: 2px 0 0 2px;\n border-left: 2px solid rgb(255, 181, 142);\n}\n\n/* Media query labels */\n\n.media-inspector-marker:not(:hover) .media-inspector-marker-label-container {\n display: none;\n}\n\n.media-inspector-marker-label-container {\n position: absolute;\n}\n\n.media-inspector-marker-label-container-left {\n left: -2px;\n}\n\n.media-inspector-marker-label-container-right {\n right: -2px;\n}\n\n.media-inspector-marker-label {\n color: #eee;\n position: absolute;\n top: 1px;\n bottom: 0;\n font-size: 10px;\n text-shadow: rgba(0, 0, 0, 0.6) 1px 1px;\n pointer-events: none;\n}\n\n.media-inspector-label-right {\n right: 4px;\n}\n\n.media-inspector-label-left {\n left: 4px;\n}\n\n/*# sourceURL=emulation/responsiveDesignView.css */";Runtime.cachedResources["emulation/overrides.css"] = "/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.overrides-view fieldset {\n border: none;\n padding: 0 0 5px 15px;\n}\n\n.overrides-view fieldset p {\n display: inline-block;\n padding: 0;\n margin: 0;\n border: 0;\n}\n\n.overrides-view fieldset p label {\n display: inline-block;\n}\n\n.overrides-view .field-error-message {\n display: none;\n}\n\n.overrides-view input[type='text']:focus::-webkit-input-placeholder {\n color: transparent !important;\n}\n\n.overrides-view > .tabbed-pane {\n overflow: hidden;\n}\n\n/* Network tab */\n\n.overrides-network fieldset {\n padding-top: 5px;\n}\n\n.overrides-network fieldset p {\n width: 100%;\n margin-left: 2px;\n}\n\n.overrides-network fieldset select {\n margin: 5px 0;\n}\n\n.overrides-network fieldset p label {\n cursor: default;\n margin-right: 5px;\n}\n\n.overrides-network fieldset input[type='text'] {\n display: block;\n width: 100%;\n max-width: 400px;\n min-width: 176px;\n margin: 5px 0;\n}\n\n/* Device tab */\n\n.overrides-device {\n width: 100%;\n}\n\n.overrides-device input.numeric {\n text-align: right;\n}\n\n.overrides-device input[type=range] {\n width: 100%;\n}\n\n.overrides-device > label {\n display: block;\n margin-bottom: 7px;\n white-space: nowrap;\n}\n\n.overrides-device button {\n margin: 0 3px;\n}\n\n.overrides-device label {\n margin-bottom: 10px;\n}\n\n.overrides-device table {\n margin-bottom: 5px;\n white-space: nowrap !important;\n}\n\n.overrides-device > label {\n margin-bottom: 4px;\n}\n\n.overrides-device .help-footnote {\n border-top: 1px solid #EEEEEE;\n margin: 0;\n padding: 12px;\n}\n\n.overrides-view label {\n display: flex;\n height: auto;\n}\n\n.overrides-view fieldset[disabled] * {\n cursor: default !important;\n}\n\n.overrides-device .overrides-device-model-section {\n margin-bottom: 15px;\n white-space: nowrap;\n}\n\n.overrides-device .overrides-device-model-section > span {\n padding: 0 10px 0 3px;\n}\n\n.overrides-device .overrides-device-model-section select {\n height: 20px;\n}\n\n.overrides-device .overrides-device-model-section select.device-select {\n width: 180px;\n margin-right: 6px;\n}\n\n.overrides-device .overrides-device-model-section .mode-container {\n display: inline-block;\n width: 140px;\n}\n\n/* Media tab */\n\n.overrides-media > label {\n margin-bottom: 4px;\n}\n\n/* Sensors tab */\n\n.overrides-sensors > label {\n margin-bottom: 10px;\n}\n\n.overrides-device, .overrides-media, .overrides-network, .overrides-sensors {\n flex: none !important;\n}\n\n.overrides-sensors input {\n text-align: right;\n}\n\n.tabbed-pane-header-tab.overrides-activate {\n opacity: 0.8;\n}\n\n.tabbed-pane-header-tab.overrides-activate .tabbed-pane-header-tab-title::after {\n padding-left: 3px;\n content: \"\\2713\";\n color: rgb(25, 100, 228);\n}\n\n.tabbed-pane-header-tab.overrides-activate.selected {\n opacity: 1;\n}\n\n.overrides-view input[type=text]:enabled:focus,\n.overrides-view select:enabled:focus {\n -webkit-transition: border-color 200ms;\n border-color: rgb(77, 144, 254);\n outline: none;\n}\n\n.overrides-view input[type=text],\n.overrides-view select {\n border: 1px solid #bfbfbf;\n border-radius: 2px;\n box-sizing: border-box;\n color: #444;\n font: inherit;\n border-width: 1px;\n}\n\n.overrides-view input[type=text] {\n margin-left: 3px;\n min-height: 2em;\n padding: 3px;\n}\n\n.overrides-view input[readonly] {\n background-color: rgb(235, 235, 228);\n}\n\n.overrides-view .overrides-footer {\n flex: none;\n padding: 0 0 1px 3px;\n border-top: 1px solid rgb(203,203,203);\n background-color: #eee;\n}\n\n.overrides-view .overrides-footer::before {\n background-image: url(Images/toolbarButtonGlyphs.png);\n background-size: 352px 144px;\n width: 10px;\n height: 10px;\n content: \"\";\n position: relative;\n top: 2px;\n background-position: -202px -107px;\n float: left;\n margin-right: 4px;\n}\n\n@media (-webkit-min-device-pixel-ratio: 1.5) {\n.overrides-view .overrides-footer::before {\n background-image: url(Images/toolbarButtonGlyphs_2x.png);\n}\n} /* media */\n\n.overrides-view .overrides-footer label[is=dt-icon-label] {\n margin-right: 3px;\n}\n\n.overrides-splash-screen {\n padding: 10px 10px;\n flex: auto;\n}\n\n.overrides-splash-screen .toolbar {\n display: inline-block;\n margin-left: -4px;\n position: relative;\n top: 8px;\n}\n\n#overrides-reset-button,\n#overrides-disable-button {\n margin: 9px 0 0 17px;\n display: block;\n width: 60px;\n}\n\n.overrides-enable-button {\n margin: 4px !important;\n}\n\n/*# sourceURL=emulation/overrides.css */";Runtime.startApplication("inspector");
阅读全文
0 0
- chrome的devtool源码inspectjs
- Chrome Devtool学习
- chrome devtool extension debug 方法
- Devtool
- chrome DevTool For Improving web app performance
- 如何使用chrome devtool调试Mobile网页?
- 下载chrome的源码
- 【DEVTool】 VIM/VI编辑器的使用FQA
- Chrome源码剖析--Chrome的进程模型
- Chrome源码剖析--Chrome的UI绘制
- Chrome源码剖析-- Chrome的插件模型
- Vue.js devtool插件安装后无法使用的解决办法
- Chrome-Chrome源码剖析
- chrome源码
- Chrome源码剖析【一】 Chrome的多线程模型
- Chrome源码剖析【二】Chrome的进程间通信
- Chrome源码剖析【三】 Chrome的进程模型
- Chrome源码剖析--Chrome的多线程模型 上
- CC2640之OAD固件升级(内置Flash)
- 模拟Json加载数据(添加购物车)
- 扫地机器人排行榜
- 利用matlab点云工具处理点云
- MySql中利用insert into select 准备数据uuid主键冲突
- chrome的devtool源码inspectjs
- MyEclipse里保存文件时报错
- hdu6166Senior Pan(spfa)
- 相似度算法
- HDU 6168 Numbers(数列,思维)
- 《剑指offer》问题5 替换空格 Java实现
- Hadoop发行版本比较与选型
- Fizz Buzz
- HDU 6162 Ch’s gift